spi.c 133 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. // SPI init/core code
  3. //
  4. // Copyright (C) 2005 David Brownell
  5. // Copyright (C) 2008 Secret Lab Technologies Ltd.
  6. #include <linux/acpi.h>
  7. #include <linux/cache.h>
  8. #include <linux/clk/clk-conf.h>
  9. #include <linux/delay.h>
  10. #include <linux/device.h>
  11. #include <linux/dmaengine.h>
  12. #include <linux/dma-mapping.h>
  13. #include <linux/export.h>
  14. #include <linux/gpio/consumer.h>
  15. #include <linux/highmem.h>
  16. #include <linux/idr.h>
  17. #include <linux/init.h>
  18. #include <linux/ioport.h>
  19. #include <linux/kernel.h>
  20. #include <linux/kthread.h>
  21. #include <linux/mod_devicetable.h>
  22. #include <linux/mutex.h>
  23. #include <linux/of_device.h>
  24. #include <linux/of_irq.h>
  25. #include <linux/percpu.h>
  26. #include <linux/platform_data/x86/apple.h>
  27. #include <linux/pm_domain.h>
  28. #include <linux/pm_runtime.h>
  29. #include <linux/property.h>
  30. #include <linux/ptp_clock_kernel.h>
  31. #include <linux/sched/rt.h>
  32. #include <linux/slab.h>
  33. #include <linux/spi/spi.h>
  34. #include <linux/spi/spi-mem.h>
  35. #include <uapi/linux/sched/types.h>
  36. #define CREATE_TRACE_POINTS
  37. #include <trace/events/spi.h>
  38. EXPORT_TRACEPOINT_SYMBOL(spi_transfer_start);
  39. EXPORT_TRACEPOINT_SYMBOL(spi_transfer_stop);
  40. #include "internals.h"
  41. static DEFINE_IDR(spi_master_idr);
  42. static void spidev_release(struct device *dev)
  43. {
  44. struct spi_device *spi = to_spi_device(dev);
  45. spi_controller_put(spi->controller);
  46. kfree(spi->driver_override);
  47. free_percpu(spi->pcpu_statistics);
  48. kfree(spi);
  49. }
  50. static ssize_t
  51. modalias_show(struct device *dev, struct device_attribute *a, char *buf)
  52. {
  53. const struct spi_device *spi = to_spi_device(dev);
  54. int len;
  55. len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
  56. if (len != -ENODEV)
  57. return len;
  58. return sysfs_emit(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
  59. }
  60. static DEVICE_ATTR_RO(modalias);
  61. static ssize_t driver_override_store(struct device *dev,
  62. struct device_attribute *a,
  63. const char *buf, size_t count)
  64. {
  65. struct spi_device *spi = to_spi_device(dev);
  66. int ret;
  67. ret = driver_set_override(dev, &spi->driver_override, buf, count);
  68. if (ret)
  69. return ret;
  70. return count;
  71. }
  72. static ssize_t driver_override_show(struct device *dev,
  73. struct device_attribute *a, char *buf)
  74. {
  75. const struct spi_device *spi = to_spi_device(dev);
  76. ssize_t len;
  77. device_lock(dev);
  78. len = sysfs_emit(buf, "%s\n", spi->driver_override ? : "");
  79. device_unlock(dev);
  80. return len;
  81. }
  82. static DEVICE_ATTR_RW(driver_override);
  83. static struct spi_statistics __percpu *spi_alloc_pcpu_stats(struct device *dev)
  84. {
  85. struct spi_statistics __percpu *pcpu_stats;
  86. if (dev)
  87. pcpu_stats = devm_alloc_percpu(dev, struct spi_statistics);
  88. else
  89. pcpu_stats = alloc_percpu_gfp(struct spi_statistics, GFP_KERNEL);
  90. if (pcpu_stats) {
  91. int cpu;
  92. for_each_possible_cpu(cpu) {
  93. struct spi_statistics *stat;
  94. stat = per_cpu_ptr(pcpu_stats, cpu);
  95. u64_stats_init(&stat->syncp);
  96. }
  97. }
  98. return pcpu_stats;
  99. }
  100. static ssize_t spi_emit_pcpu_stats(struct spi_statistics __percpu *stat,
  101. char *buf, size_t offset)
  102. {
  103. u64 val = 0;
  104. int i;
  105. for_each_possible_cpu(i) {
  106. const struct spi_statistics *pcpu_stats;
  107. u64_stats_t *field;
  108. unsigned int start;
  109. u64 inc;
  110. pcpu_stats = per_cpu_ptr(stat, i);
  111. field = (void *)pcpu_stats + offset;
  112. do {
  113. start = u64_stats_fetch_begin(&pcpu_stats->syncp);
  114. inc = u64_stats_read(field);
  115. } while (u64_stats_fetch_retry(&pcpu_stats->syncp, start));
  116. val += inc;
  117. }
  118. return sysfs_emit(buf, "%llu\n", val);
  119. }
  120. #define SPI_STATISTICS_ATTRS(field, file) \
  121. static ssize_t spi_controller_##field##_show(struct device *dev, \
  122. struct device_attribute *attr, \
  123. char *buf) \
  124. { \
  125. struct spi_controller *ctlr = container_of(dev, \
  126. struct spi_controller, dev); \
  127. return spi_statistics_##field##_show(ctlr->pcpu_statistics, buf); \
  128. } \
  129. static struct device_attribute dev_attr_spi_controller_##field = { \
  130. .attr = { .name = file, .mode = 0444 }, \
  131. .show = spi_controller_##field##_show, \
  132. }; \
  133. static ssize_t spi_device_##field##_show(struct device *dev, \
  134. struct device_attribute *attr, \
  135. char *buf) \
  136. { \
  137. struct spi_device *spi = to_spi_device(dev); \
  138. return spi_statistics_##field##_show(spi->pcpu_statistics, buf); \
  139. } \
  140. static struct device_attribute dev_attr_spi_device_##field = { \
  141. .attr = { .name = file, .mode = 0444 }, \
  142. .show = spi_device_##field##_show, \
  143. }
  144. #define SPI_STATISTICS_SHOW_NAME(name, file, field) \
  145. static ssize_t spi_statistics_##name##_show(struct spi_statistics __percpu *stat, \
  146. char *buf) \
  147. { \
  148. return spi_emit_pcpu_stats(stat, buf, \
  149. offsetof(struct spi_statistics, field)); \
  150. } \
  151. SPI_STATISTICS_ATTRS(name, file)
  152. #define SPI_STATISTICS_SHOW(field) \
  153. SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
  154. field)
  155. SPI_STATISTICS_SHOW(messages);
  156. SPI_STATISTICS_SHOW(transfers);
  157. SPI_STATISTICS_SHOW(errors);
  158. SPI_STATISTICS_SHOW(timedout);
  159. SPI_STATISTICS_SHOW(spi_sync);
  160. SPI_STATISTICS_SHOW(spi_sync_immediate);
  161. SPI_STATISTICS_SHOW(spi_async);
  162. SPI_STATISTICS_SHOW(bytes);
  163. SPI_STATISTICS_SHOW(bytes_rx);
  164. SPI_STATISTICS_SHOW(bytes_tx);
  165. #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
  166. SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
  167. "transfer_bytes_histo_" number, \
  168. transfer_bytes_histo[index])
  169. SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
  170. SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
  171. SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
  172. SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
  173. SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
  174. SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
  175. SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
  176. SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
  177. SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
  178. SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
  179. SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
  180. SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
  181. SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
  182. SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
  183. SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
  184. SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
  185. SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
  186. SPI_STATISTICS_SHOW(transfers_split_maxsize);
  187. static struct attribute *spi_dev_attrs[] = {
  188. &dev_attr_modalias.attr,
  189. &dev_attr_driver_override.attr,
  190. NULL,
  191. };
  192. static const struct attribute_group spi_dev_group = {
  193. .attrs = spi_dev_attrs,
  194. };
  195. static struct attribute *spi_device_statistics_attrs[] = {
  196. &dev_attr_spi_device_messages.attr,
  197. &dev_attr_spi_device_transfers.attr,
  198. &dev_attr_spi_device_errors.attr,
  199. &dev_attr_spi_device_timedout.attr,
  200. &dev_attr_spi_device_spi_sync.attr,
  201. &dev_attr_spi_device_spi_sync_immediate.attr,
  202. &dev_attr_spi_device_spi_async.attr,
  203. &dev_attr_spi_device_bytes.attr,
  204. &dev_attr_spi_device_bytes_rx.attr,
  205. &dev_attr_spi_device_bytes_tx.attr,
  206. &dev_attr_spi_device_transfer_bytes_histo0.attr,
  207. &dev_attr_spi_device_transfer_bytes_histo1.attr,
  208. &dev_attr_spi_device_transfer_bytes_histo2.attr,
  209. &dev_attr_spi_device_transfer_bytes_histo3.attr,
  210. &dev_attr_spi_device_transfer_bytes_histo4.attr,
  211. &dev_attr_spi_device_transfer_bytes_histo5.attr,
  212. &dev_attr_spi_device_transfer_bytes_histo6.attr,
  213. &dev_attr_spi_device_transfer_bytes_histo7.attr,
  214. &dev_attr_spi_device_transfer_bytes_histo8.attr,
  215. &dev_attr_spi_device_transfer_bytes_histo9.attr,
  216. &dev_attr_spi_device_transfer_bytes_histo10.attr,
  217. &dev_attr_spi_device_transfer_bytes_histo11.attr,
  218. &dev_attr_spi_device_transfer_bytes_histo12.attr,
  219. &dev_attr_spi_device_transfer_bytes_histo13.attr,
  220. &dev_attr_spi_device_transfer_bytes_histo14.attr,
  221. &dev_attr_spi_device_transfer_bytes_histo15.attr,
  222. &dev_attr_spi_device_transfer_bytes_histo16.attr,
  223. &dev_attr_spi_device_transfers_split_maxsize.attr,
  224. NULL,
  225. };
  226. static const struct attribute_group spi_device_statistics_group = {
  227. .name = "statistics",
  228. .attrs = spi_device_statistics_attrs,
  229. };
  230. static const struct attribute_group *spi_dev_groups[] = {
  231. &spi_dev_group,
  232. &spi_device_statistics_group,
  233. NULL,
  234. };
  235. static struct attribute *spi_controller_statistics_attrs[] = {
  236. &dev_attr_spi_controller_messages.attr,
  237. &dev_attr_spi_controller_transfers.attr,
  238. &dev_attr_spi_controller_errors.attr,
  239. &dev_attr_spi_controller_timedout.attr,
  240. &dev_attr_spi_controller_spi_sync.attr,
  241. &dev_attr_spi_controller_spi_sync_immediate.attr,
  242. &dev_attr_spi_controller_spi_async.attr,
  243. &dev_attr_spi_controller_bytes.attr,
  244. &dev_attr_spi_controller_bytes_rx.attr,
  245. &dev_attr_spi_controller_bytes_tx.attr,
  246. &dev_attr_spi_controller_transfer_bytes_histo0.attr,
  247. &dev_attr_spi_controller_transfer_bytes_histo1.attr,
  248. &dev_attr_spi_controller_transfer_bytes_histo2.attr,
  249. &dev_attr_spi_controller_transfer_bytes_histo3.attr,
  250. &dev_attr_spi_controller_transfer_bytes_histo4.attr,
  251. &dev_attr_spi_controller_transfer_bytes_histo5.attr,
  252. &dev_attr_spi_controller_transfer_bytes_histo6.attr,
  253. &dev_attr_spi_controller_transfer_bytes_histo7.attr,
  254. &dev_attr_spi_controller_transfer_bytes_histo8.attr,
  255. &dev_attr_spi_controller_transfer_bytes_histo9.attr,
  256. &dev_attr_spi_controller_transfer_bytes_histo10.attr,
  257. &dev_attr_spi_controller_transfer_bytes_histo11.attr,
  258. &dev_attr_spi_controller_transfer_bytes_histo12.attr,
  259. &dev_attr_spi_controller_transfer_bytes_histo13.attr,
  260. &dev_attr_spi_controller_transfer_bytes_histo14.attr,
  261. &dev_attr_spi_controller_transfer_bytes_histo15.attr,
  262. &dev_attr_spi_controller_transfer_bytes_histo16.attr,
  263. &dev_attr_spi_controller_transfers_split_maxsize.attr,
  264. NULL,
  265. };
  266. static const struct attribute_group spi_controller_statistics_group = {
  267. .name = "statistics",
  268. .attrs = spi_controller_statistics_attrs,
  269. };
  270. static const struct attribute_group *spi_master_groups[] = {
  271. &spi_controller_statistics_group,
  272. NULL,
  273. };
  274. static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
  275. struct spi_transfer *xfer,
  276. struct spi_message *msg)
  277. {
  278. int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
  279. struct spi_statistics *stats;
  280. if (l2len < 0)
  281. l2len = 0;
  282. get_cpu();
  283. stats = this_cpu_ptr(pcpu_stats);
  284. u64_stats_update_begin(&stats->syncp);
  285. u64_stats_inc(&stats->transfers);
  286. u64_stats_inc(&stats->transfer_bytes_histo[l2len]);
  287. u64_stats_add(&stats->bytes, xfer->len);
  288. if (spi_valid_txbuf(msg, xfer))
  289. u64_stats_add(&stats->bytes_tx, xfer->len);
  290. if (spi_valid_rxbuf(msg, xfer))
  291. u64_stats_add(&stats->bytes_rx, xfer->len);
  292. u64_stats_update_end(&stats->syncp);
  293. put_cpu();
  294. }
  295. /*
  296. * modalias support makes "modprobe $MODALIAS" new-style hotplug work,
  297. * and the sysfs version makes coldplug work too.
  298. */
  299. static const struct spi_device_id *spi_match_id(const struct spi_device_id *id, const char *name)
  300. {
  301. while (id->name[0]) {
  302. if (!strcmp(name, id->name))
  303. return id;
  304. id++;
  305. }
  306. return NULL;
  307. }
  308. const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
  309. {
  310. const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
  311. return spi_match_id(sdrv->id_table, sdev->modalias);
  312. }
  313. EXPORT_SYMBOL_GPL(spi_get_device_id);
  314. const void *spi_get_device_match_data(const struct spi_device *sdev)
  315. {
  316. const void *match;
  317. match = device_get_match_data(&sdev->dev);
  318. if (match)
  319. return match;
  320. return (const void *)spi_get_device_id(sdev)->driver_data;
  321. }
  322. EXPORT_SYMBOL_GPL(spi_get_device_match_data);
  323. static int spi_match_device(struct device *dev, const struct device_driver *drv)
  324. {
  325. const struct spi_device *spi = to_spi_device(dev);
  326. const struct spi_driver *sdrv = to_spi_driver(drv);
  327. /* Check override first, and if set, only use the named driver */
  328. if (spi->driver_override)
  329. return strcmp(spi->driver_override, drv->name) == 0;
  330. /* Attempt an OF style match */
  331. if (of_driver_match_device(dev, drv))
  332. return 1;
  333. /* Then try ACPI */
  334. if (acpi_driver_match_device(dev, drv))
  335. return 1;
  336. if (sdrv->id_table)
  337. return !!spi_match_id(sdrv->id_table, spi->modalias);
  338. return strcmp(spi->modalias, drv->name) == 0;
  339. }
  340. static int spi_uevent(const struct device *dev, struct kobj_uevent_env *env)
  341. {
  342. const struct spi_device *spi = to_spi_device(dev);
  343. int rc;
  344. rc = acpi_device_uevent_modalias(dev, env);
  345. if (rc != -ENODEV)
  346. return rc;
  347. return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
  348. }
  349. static int spi_probe(struct device *dev)
  350. {
  351. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  352. struct spi_device *spi = to_spi_device(dev);
  353. int ret;
  354. ret = of_clk_set_defaults(dev->of_node, false);
  355. if (ret)
  356. return ret;
  357. if (dev->of_node) {
  358. spi->irq = of_irq_get(dev->of_node, 0);
  359. if (spi->irq == -EPROBE_DEFER)
  360. return -EPROBE_DEFER;
  361. if (spi->irq < 0)
  362. spi->irq = 0;
  363. }
  364. if (has_acpi_companion(dev) && spi->irq < 0) {
  365. struct acpi_device *adev = to_acpi_device_node(dev->fwnode);
  366. spi->irq = acpi_dev_gpio_irq_get(adev, 0);
  367. if (spi->irq == -EPROBE_DEFER)
  368. return -EPROBE_DEFER;
  369. if (spi->irq < 0)
  370. spi->irq = 0;
  371. }
  372. ret = dev_pm_domain_attach(dev, true);
  373. if (ret)
  374. return ret;
  375. if (sdrv->probe) {
  376. ret = sdrv->probe(spi);
  377. if (ret)
  378. dev_pm_domain_detach(dev, true);
  379. }
  380. return ret;
  381. }
  382. static void spi_remove(struct device *dev)
  383. {
  384. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  385. if (sdrv->remove)
  386. sdrv->remove(to_spi_device(dev));
  387. dev_pm_domain_detach(dev, true);
  388. }
  389. static void spi_shutdown(struct device *dev)
  390. {
  391. if (dev->driver) {
  392. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  393. if (sdrv->shutdown)
  394. sdrv->shutdown(to_spi_device(dev));
  395. }
  396. }
  397. const struct bus_type spi_bus_type = {
  398. .name = "spi",
  399. .dev_groups = spi_dev_groups,
  400. .match = spi_match_device,
  401. .uevent = spi_uevent,
  402. .probe = spi_probe,
  403. .remove = spi_remove,
  404. .shutdown = spi_shutdown,
  405. };
  406. EXPORT_SYMBOL_GPL(spi_bus_type);
  407. /**
  408. * __spi_register_driver - register a SPI driver
  409. * @owner: owner module of the driver to register
  410. * @sdrv: the driver to register
  411. * Context: can sleep
  412. *
  413. * Return: zero on success, else a negative error code.
  414. */
  415. int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
  416. {
  417. sdrv->driver.owner = owner;
  418. sdrv->driver.bus = &spi_bus_type;
  419. /*
  420. * For Really Good Reasons we use spi: modaliases not of:
  421. * modaliases for DT so module autoloading won't work if we
  422. * don't have a spi_device_id as well as a compatible string.
  423. */
  424. if (sdrv->driver.of_match_table) {
  425. const struct of_device_id *of_id;
  426. for (of_id = sdrv->driver.of_match_table; of_id->compatible[0];
  427. of_id++) {
  428. const char *of_name;
  429. /* Strip off any vendor prefix */
  430. of_name = strnchr(of_id->compatible,
  431. sizeof(of_id->compatible), ',');
  432. if (of_name)
  433. of_name++;
  434. else
  435. of_name = of_id->compatible;
  436. if (sdrv->id_table) {
  437. const struct spi_device_id *spi_id;
  438. spi_id = spi_match_id(sdrv->id_table, of_name);
  439. if (spi_id)
  440. continue;
  441. } else {
  442. if (strcmp(sdrv->driver.name, of_name) == 0)
  443. continue;
  444. }
  445. pr_warn("SPI driver %s has no spi_device_id for %s\n",
  446. sdrv->driver.name, of_id->compatible);
  447. }
  448. }
  449. return driver_register(&sdrv->driver);
  450. }
  451. EXPORT_SYMBOL_GPL(__spi_register_driver);
  452. /*-------------------------------------------------------------------------*/
  453. /*
  454. * SPI devices should normally not be created by SPI device drivers; that
  455. * would make them board-specific. Similarly with SPI controller drivers.
  456. * Device registration normally goes into like arch/.../mach.../board-YYY.c
  457. * with other readonly (flashable) information about mainboard devices.
  458. */
  459. struct boardinfo {
  460. struct list_head list;
  461. struct spi_board_info board_info;
  462. };
  463. static LIST_HEAD(board_list);
  464. static LIST_HEAD(spi_controller_list);
  465. /*
  466. * Used to protect add/del operation for board_info list and
  467. * spi_controller list, and their matching process also used
  468. * to protect object of type struct idr.
  469. */
  470. static DEFINE_MUTEX(board_lock);
  471. /**
  472. * spi_alloc_device - Allocate a new SPI device
  473. * @ctlr: Controller to which device is connected
  474. * Context: can sleep
  475. *
  476. * Allows a driver to allocate and initialize a spi_device without
  477. * registering it immediately. This allows a driver to directly
  478. * fill the spi_device with device parameters before calling
  479. * spi_add_device() on it.
  480. *
  481. * Caller is responsible to call spi_add_device() on the returned
  482. * spi_device structure to add it to the SPI controller. If the caller
  483. * needs to discard the spi_device without adding it, then it should
  484. * call spi_dev_put() on it.
  485. *
  486. * Return: a pointer to the new device, or NULL.
  487. */
  488. struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
  489. {
  490. struct spi_device *spi;
  491. if (!spi_controller_get(ctlr))
  492. return NULL;
  493. spi = kzalloc(sizeof(*spi), GFP_KERNEL);
  494. if (!spi) {
  495. spi_controller_put(ctlr);
  496. return NULL;
  497. }
  498. spi->pcpu_statistics = spi_alloc_pcpu_stats(NULL);
  499. if (!spi->pcpu_statistics) {
  500. kfree(spi);
  501. spi_controller_put(ctlr);
  502. return NULL;
  503. }
  504. spi->controller = ctlr;
  505. spi->dev.parent = &ctlr->dev;
  506. spi->dev.bus = &spi_bus_type;
  507. spi->dev.release = spidev_release;
  508. spi->mode = ctlr->buswidth_override_bits;
  509. device_initialize(&spi->dev);
  510. return spi;
  511. }
  512. EXPORT_SYMBOL_GPL(spi_alloc_device);
  513. static void spi_dev_set_name(struct spi_device *spi)
  514. {
  515. struct device *dev = &spi->dev;
  516. struct fwnode_handle *fwnode = dev_fwnode(dev);
  517. if (is_acpi_device_node(fwnode)) {
  518. dev_set_name(dev, "spi-%s", acpi_dev_name(to_acpi_device_node(fwnode)));
  519. return;
  520. }
  521. if (is_software_node(fwnode)) {
  522. dev_set_name(dev, "spi-%pfwP", fwnode);
  523. return;
  524. }
  525. dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
  526. spi_get_chipselect(spi, 0));
  527. }
  528. /*
  529. * Zero(0) is a valid physical CS value and can be located at any
  530. * logical CS in the spi->chip_select[]. If all the physical CS
  531. * are initialized to 0 then It would be difficult to differentiate
  532. * between a valid physical CS 0 & an unused logical CS whose physical
  533. * CS can be 0. As a solution to this issue initialize all the CS to -1.
  534. * Now all the unused logical CS will have -1 physical CS value & can be
  535. * ignored while performing physical CS validity checks.
  536. */
  537. #define SPI_INVALID_CS ((s8)-1)
  538. static inline bool is_valid_cs(s8 chip_select)
  539. {
  540. return chip_select != SPI_INVALID_CS;
  541. }
  542. static inline int spi_dev_check_cs(struct device *dev,
  543. struct spi_device *spi, u8 idx,
  544. struct spi_device *new_spi, u8 new_idx)
  545. {
  546. u8 cs, cs_new;
  547. u8 idx_new;
  548. cs = spi_get_chipselect(spi, idx);
  549. for (idx_new = new_idx; idx_new < SPI_CS_CNT_MAX; idx_new++) {
  550. cs_new = spi_get_chipselect(new_spi, idx_new);
  551. if (is_valid_cs(cs) && is_valid_cs(cs_new) && cs == cs_new) {
  552. dev_err(dev, "chipselect %u already in use\n", cs_new);
  553. return -EBUSY;
  554. }
  555. }
  556. return 0;
  557. }
  558. static int spi_dev_check(struct device *dev, void *data)
  559. {
  560. struct spi_device *spi = to_spi_device(dev);
  561. struct spi_device *new_spi = data;
  562. int status, idx;
  563. if (spi->controller == new_spi->controller) {
  564. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
  565. status = spi_dev_check_cs(dev, spi, idx, new_spi, 0);
  566. if (status)
  567. return status;
  568. }
  569. }
  570. return 0;
  571. }
  572. static void spi_cleanup(struct spi_device *spi)
  573. {
  574. if (spi->controller->cleanup)
  575. spi->controller->cleanup(spi);
  576. }
  577. static int __spi_add_device(struct spi_device *spi)
  578. {
  579. struct spi_controller *ctlr = spi->controller;
  580. struct device *dev = ctlr->dev.parent;
  581. int status, idx;
  582. u8 cs;
  583. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
  584. /* Chipselects are numbered 0..max; validate. */
  585. cs = spi_get_chipselect(spi, idx);
  586. if (is_valid_cs(cs) && cs >= ctlr->num_chipselect) {
  587. dev_err(dev, "cs%d >= max %d\n", spi_get_chipselect(spi, idx),
  588. ctlr->num_chipselect);
  589. return -EINVAL;
  590. }
  591. }
  592. /*
  593. * Make sure that multiple logical CS doesn't map to the same physical CS.
  594. * For example, spi->chip_select[0] != spi->chip_select[1] and so on.
  595. */
  596. if (!spi_controller_is_target(ctlr)) {
  597. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
  598. status = spi_dev_check_cs(dev, spi, idx, spi, idx + 1);
  599. if (status)
  600. return status;
  601. }
  602. }
  603. /* Set the bus ID string */
  604. spi_dev_set_name(spi);
  605. /*
  606. * We need to make sure there's no other device with this
  607. * chipselect **BEFORE** we call setup(), else we'll trash
  608. * its configuration.
  609. */
  610. status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
  611. if (status)
  612. return status;
  613. /* Controller may unregister concurrently */
  614. if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
  615. !device_is_registered(&ctlr->dev)) {
  616. return -ENODEV;
  617. }
  618. if (ctlr->cs_gpiods) {
  619. u8 cs;
  620. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) {
  621. cs = spi_get_chipselect(spi, idx);
  622. if (is_valid_cs(cs))
  623. spi_set_csgpiod(spi, idx, ctlr->cs_gpiods[cs]);
  624. }
  625. }
  626. /*
  627. * Drivers may modify this initial i/o setup, but will
  628. * normally rely on the device being setup. Devices
  629. * using SPI_CS_HIGH can't coexist well otherwise...
  630. */
  631. status = spi_setup(spi);
  632. if (status < 0) {
  633. dev_err(dev, "can't setup %s, status %d\n",
  634. dev_name(&spi->dev), status);
  635. return status;
  636. }
  637. /* Device may be bound to an active driver when this returns */
  638. status = device_add(&spi->dev);
  639. if (status < 0) {
  640. dev_err(dev, "can't add %s, status %d\n",
  641. dev_name(&spi->dev), status);
  642. spi_cleanup(spi);
  643. } else {
  644. dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
  645. }
  646. return status;
  647. }
  648. /**
  649. * spi_add_device - Add spi_device allocated with spi_alloc_device
  650. * @spi: spi_device to register
  651. *
  652. * Companion function to spi_alloc_device. Devices allocated with
  653. * spi_alloc_device can be added onto the SPI bus with this function.
  654. *
  655. * Return: 0 on success; negative errno on failure
  656. */
  657. int spi_add_device(struct spi_device *spi)
  658. {
  659. struct spi_controller *ctlr = spi->controller;
  660. int status;
  661. /* Set the bus ID string */
  662. spi_dev_set_name(spi);
  663. mutex_lock(&ctlr->add_lock);
  664. status = __spi_add_device(spi);
  665. mutex_unlock(&ctlr->add_lock);
  666. return status;
  667. }
  668. EXPORT_SYMBOL_GPL(spi_add_device);
  669. static void spi_set_all_cs_unused(struct spi_device *spi)
  670. {
  671. u8 idx;
  672. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
  673. spi_set_chipselect(spi, idx, SPI_INVALID_CS);
  674. }
  675. /**
  676. * spi_new_device - instantiate one new SPI device
  677. * @ctlr: Controller to which device is connected
  678. * @chip: Describes the SPI device
  679. * Context: can sleep
  680. *
  681. * On typical mainboards, this is purely internal; and it's not needed
  682. * after board init creates the hard-wired devices. Some development
  683. * platforms may not be able to use spi_register_board_info though, and
  684. * this is exported so that for example a USB or parport based adapter
  685. * driver could add devices (which it would learn about out-of-band).
  686. *
  687. * Return: the new device, or NULL.
  688. */
  689. struct spi_device *spi_new_device(struct spi_controller *ctlr,
  690. struct spi_board_info *chip)
  691. {
  692. struct spi_device *proxy;
  693. int status;
  694. /*
  695. * NOTE: caller did any chip->bus_num checks necessary.
  696. *
  697. * Also, unless we change the return value convention to use
  698. * error-or-pointer (not NULL-or-pointer), troubleshootability
  699. * suggests syslogged diagnostics are best here (ugh).
  700. */
  701. proxy = spi_alloc_device(ctlr);
  702. if (!proxy)
  703. return NULL;
  704. WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
  705. /* Use provided chip-select for proxy device */
  706. spi_set_all_cs_unused(proxy);
  707. spi_set_chipselect(proxy, 0, chip->chip_select);
  708. proxy->max_speed_hz = chip->max_speed_hz;
  709. proxy->mode = chip->mode;
  710. proxy->irq = chip->irq;
  711. strscpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
  712. proxy->dev.platform_data = (void *) chip->platform_data;
  713. proxy->controller_data = chip->controller_data;
  714. proxy->controller_state = NULL;
  715. /*
  716. * By default spi->chip_select[0] will hold the physical CS number,
  717. * so set bit 0 in spi->cs_index_mask.
  718. */
  719. proxy->cs_index_mask = BIT(0);
  720. if (chip->swnode) {
  721. status = device_add_software_node(&proxy->dev, chip->swnode);
  722. if (status) {
  723. dev_err(&ctlr->dev, "failed to add software node to '%s': %d\n",
  724. chip->modalias, status);
  725. goto err_dev_put;
  726. }
  727. }
  728. status = spi_add_device(proxy);
  729. if (status < 0)
  730. goto err_dev_put;
  731. return proxy;
  732. err_dev_put:
  733. device_remove_software_node(&proxy->dev);
  734. spi_dev_put(proxy);
  735. return NULL;
  736. }
  737. EXPORT_SYMBOL_GPL(spi_new_device);
  738. /**
  739. * spi_unregister_device - unregister a single SPI device
  740. * @spi: spi_device to unregister
  741. *
  742. * Start making the passed SPI device vanish. Normally this would be handled
  743. * by spi_unregister_controller().
  744. */
  745. void spi_unregister_device(struct spi_device *spi)
  746. {
  747. if (!spi)
  748. return;
  749. if (spi->dev.of_node) {
  750. of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
  751. of_node_put(spi->dev.of_node);
  752. }
  753. if (ACPI_COMPANION(&spi->dev))
  754. acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
  755. device_remove_software_node(&spi->dev);
  756. device_del(&spi->dev);
  757. spi_cleanup(spi);
  758. put_device(&spi->dev);
  759. }
  760. EXPORT_SYMBOL_GPL(spi_unregister_device);
  761. static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
  762. struct spi_board_info *bi)
  763. {
  764. struct spi_device *dev;
  765. if (ctlr->bus_num != bi->bus_num)
  766. return;
  767. dev = spi_new_device(ctlr, bi);
  768. if (!dev)
  769. dev_err(ctlr->dev.parent, "can't create new device for %s\n",
  770. bi->modalias);
  771. }
  772. /**
  773. * spi_register_board_info - register SPI devices for a given board
  774. * @info: array of chip descriptors
  775. * @n: how many descriptors are provided
  776. * Context: can sleep
  777. *
  778. * Board-specific early init code calls this (probably during arch_initcall)
  779. * with segments of the SPI device table. Any device nodes are created later,
  780. * after the relevant parent SPI controller (bus_num) is defined. We keep
  781. * this table of devices forever, so that reloading a controller driver will
  782. * not make Linux forget about these hard-wired devices.
  783. *
  784. * Other code can also call this, e.g. a particular add-on board might provide
  785. * SPI devices through its expansion connector, so code initializing that board
  786. * would naturally declare its SPI devices.
  787. *
  788. * The board info passed can safely be __initdata ... but be careful of
  789. * any embedded pointers (platform_data, etc), they're copied as-is.
  790. *
  791. * Return: zero on success, else a negative error code.
  792. */
  793. int spi_register_board_info(struct spi_board_info const *info, unsigned n)
  794. {
  795. struct boardinfo *bi;
  796. int i;
  797. if (!n)
  798. return 0;
  799. bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
  800. if (!bi)
  801. return -ENOMEM;
  802. for (i = 0; i < n; i++, bi++, info++) {
  803. struct spi_controller *ctlr;
  804. memcpy(&bi->board_info, info, sizeof(*info));
  805. mutex_lock(&board_lock);
  806. list_add_tail(&bi->list, &board_list);
  807. list_for_each_entry(ctlr, &spi_controller_list, list)
  808. spi_match_controller_to_boardinfo(ctlr,
  809. &bi->board_info);
  810. mutex_unlock(&board_lock);
  811. }
  812. return 0;
  813. }
  814. /*-------------------------------------------------------------------------*/
  815. /* Core methods for SPI resource management */
  816. /**
  817. * spi_res_alloc - allocate a spi resource that is life-cycle managed
  818. * during the processing of a spi_message while using
  819. * spi_transfer_one
  820. * @spi: the SPI device for which we allocate memory
  821. * @release: the release code to execute for this resource
  822. * @size: size to alloc and return
  823. * @gfp: GFP allocation flags
  824. *
  825. * Return: the pointer to the allocated data
  826. *
  827. * This may get enhanced in the future to allocate from a memory pool
  828. * of the @spi_device or @spi_controller to avoid repeated allocations.
  829. */
  830. static void *spi_res_alloc(struct spi_device *spi, spi_res_release_t release,
  831. size_t size, gfp_t gfp)
  832. {
  833. struct spi_res *sres;
  834. sres = kzalloc(sizeof(*sres) + size, gfp);
  835. if (!sres)
  836. return NULL;
  837. INIT_LIST_HEAD(&sres->entry);
  838. sres->release = release;
  839. return sres->data;
  840. }
  841. /**
  842. * spi_res_free - free an SPI resource
  843. * @res: pointer to the custom data of a resource
  844. */
  845. static void spi_res_free(void *res)
  846. {
  847. struct spi_res *sres = container_of(res, struct spi_res, data);
  848. if (!res)
  849. return;
  850. WARN_ON(!list_empty(&sres->entry));
  851. kfree(sres);
  852. }
  853. /**
  854. * spi_res_add - add a spi_res to the spi_message
  855. * @message: the SPI message
  856. * @res: the spi_resource
  857. */
  858. static void spi_res_add(struct spi_message *message, void *res)
  859. {
  860. struct spi_res *sres = container_of(res, struct spi_res, data);
  861. WARN_ON(!list_empty(&sres->entry));
  862. list_add_tail(&sres->entry, &message->resources);
  863. }
  864. /**
  865. * spi_res_release - release all SPI resources for this message
  866. * @ctlr: the @spi_controller
  867. * @message: the @spi_message
  868. */
  869. static void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
  870. {
  871. struct spi_res *res, *tmp;
  872. list_for_each_entry_safe_reverse(res, tmp, &message->resources, entry) {
  873. if (res->release)
  874. res->release(ctlr, message, res->data);
  875. list_del(&res->entry);
  876. kfree(res);
  877. }
  878. }
  879. /*-------------------------------------------------------------------------*/
  880. #define spi_for_each_valid_cs(spi, idx) \
  881. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++) \
  882. if (!(spi->cs_index_mask & BIT(idx))) {} else
  883. static inline bool spi_is_last_cs(struct spi_device *spi)
  884. {
  885. u8 idx;
  886. bool last = false;
  887. spi_for_each_valid_cs(spi, idx) {
  888. if (spi->controller->last_cs[idx] == spi_get_chipselect(spi, idx))
  889. last = true;
  890. }
  891. return last;
  892. }
  893. static void spi_toggle_csgpiod(struct spi_device *spi, u8 idx, bool enable, bool activate)
  894. {
  895. /*
  896. * Historically ACPI has no means of the GPIO polarity and
  897. * thus the SPISerialBus() resource defines it on the per-chip
  898. * basis. In order to avoid a chain of negations, the GPIO
  899. * polarity is considered being Active High. Even for the cases
  900. * when _DSD() is involved (in the updated versions of ACPI)
  901. * the GPIO CS polarity must be defined Active High to avoid
  902. * ambiguity. That's why we use enable, that takes SPI_CS_HIGH
  903. * into account.
  904. */
  905. if (has_acpi_companion(&spi->dev))
  906. gpiod_set_value_cansleep(spi_get_csgpiod(spi, idx), !enable);
  907. else
  908. /* Polarity handled by GPIO library */
  909. gpiod_set_value_cansleep(spi_get_csgpiod(spi, idx), activate);
  910. if (activate)
  911. spi_delay_exec(&spi->cs_setup, NULL);
  912. else
  913. spi_delay_exec(&spi->cs_inactive, NULL);
  914. }
  915. static void spi_set_cs(struct spi_device *spi, bool enable, bool force)
  916. {
  917. bool activate = enable;
  918. u8 idx;
  919. /*
  920. * Avoid calling into the driver (or doing delays) if the chip select
  921. * isn't actually changing from the last time this was called.
  922. */
  923. if (!force && ((enable && spi->controller->last_cs_index_mask == spi->cs_index_mask &&
  924. spi_is_last_cs(spi)) ||
  925. (!enable && spi->controller->last_cs_index_mask == spi->cs_index_mask &&
  926. !spi_is_last_cs(spi))) &&
  927. (spi->controller->last_cs_mode_high == (spi->mode & SPI_CS_HIGH)))
  928. return;
  929. trace_spi_set_cs(spi, activate);
  930. spi->controller->last_cs_index_mask = spi->cs_index_mask;
  931. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
  932. spi->controller->last_cs[idx] = enable ? spi_get_chipselect(spi, 0) : SPI_INVALID_CS;
  933. spi->controller->last_cs_mode_high = spi->mode & SPI_CS_HIGH;
  934. if (spi->mode & SPI_CS_HIGH)
  935. enable = !enable;
  936. /*
  937. * Handle chip select delays for GPIO based CS or controllers without
  938. * programmable chip select timing.
  939. */
  940. if ((spi_is_csgpiod(spi) || !spi->controller->set_cs_timing) && !activate)
  941. spi_delay_exec(&spi->cs_hold, NULL);
  942. if (spi_is_csgpiod(spi)) {
  943. if (!(spi->mode & SPI_NO_CS)) {
  944. spi_for_each_valid_cs(spi, idx) {
  945. if (spi_get_csgpiod(spi, idx))
  946. spi_toggle_csgpiod(spi, idx, enable, activate);
  947. }
  948. }
  949. /* Some SPI masters need both GPIO CS & slave_select */
  950. if ((spi->controller->flags & SPI_CONTROLLER_GPIO_SS) &&
  951. spi->controller->set_cs)
  952. spi->controller->set_cs(spi, !enable);
  953. } else if (spi->controller->set_cs) {
  954. spi->controller->set_cs(spi, !enable);
  955. }
  956. if (spi_is_csgpiod(spi) || !spi->controller->set_cs_timing) {
  957. if (activate)
  958. spi_delay_exec(&spi->cs_setup, NULL);
  959. else
  960. spi_delay_exec(&spi->cs_inactive, NULL);
  961. }
  962. }
  963. #ifdef CONFIG_HAS_DMA
  964. static int spi_map_buf_attrs(struct spi_controller *ctlr, struct device *dev,
  965. struct sg_table *sgt, void *buf, size_t len,
  966. enum dma_data_direction dir, unsigned long attrs)
  967. {
  968. const bool vmalloced_buf = is_vmalloc_addr(buf);
  969. unsigned int max_seg_size = dma_get_max_seg_size(dev);
  970. #ifdef CONFIG_HIGHMEM
  971. const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
  972. (unsigned long)buf < (PKMAP_BASE +
  973. (LAST_PKMAP * PAGE_SIZE)));
  974. #else
  975. const bool kmap_buf = false;
  976. #endif
  977. int desc_len;
  978. int sgs;
  979. struct page *vm_page;
  980. struct scatterlist *sg;
  981. void *sg_buf;
  982. size_t min;
  983. int i, ret;
  984. if (vmalloced_buf || kmap_buf) {
  985. desc_len = min_t(unsigned long, max_seg_size, PAGE_SIZE);
  986. sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
  987. } else if (virt_addr_valid(buf)) {
  988. desc_len = min_t(size_t, max_seg_size, ctlr->max_dma_len);
  989. sgs = DIV_ROUND_UP(len, desc_len);
  990. } else {
  991. return -EINVAL;
  992. }
  993. ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
  994. if (ret != 0)
  995. return ret;
  996. sg = &sgt->sgl[0];
  997. for (i = 0; i < sgs; i++) {
  998. if (vmalloced_buf || kmap_buf) {
  999. /*
  1000. * Next scatterlist entry size is the minimum between
  1001. * the desc_len and the remaining buffer length that
  1002. * fits in a page.
  1003. */
  1004. min = min_t(size_t, desc_len,
  1005. min_t(size_t, len,
  1006. PAGE_SIZE - offset_in_page(buf)));
  1007. if (vmalloced_buf)
  1008. vm_page = vmalloc_to_page(buf);
  1009. else
  1010. vm_page = kmap_to_page(buf);
  1011. if (!vm_page) {
  1012. sg_free_table(sgt);
  1013. return -ENOMEM;
  1014. }
  1015. sg_set_page(sg, vm_page,
  1016. min, offset_in_page(buf));
  1017. } else {
  1018. min = min_t(size_t, len, desc_len);
  1019. sg_buf = buf;
  1020. sg_set_buf(sg, sg_buf, min);
  1021. }
  1022. buf += min;
  1023. len -= min;
  1024. sg = sg_next(sg);
  1025. }
  1026. ret = dma_map_sgtable(dev, sgt, dir, attrs);
  1027. if (ret < 0) {
  1028. sg_free_table(sgt);
  1029. return ret;
  1030. }
  1031. return 0;
  1032. }
  1033. int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
  1034. struct sg_table *sgt, void *buf, size_t len,
  1035. enum dma_data_direction dir)
  1036. {
  1037. return spi_map_buf_attrs(ctlr, dev, sgt, buf, len, dir, 0);
  1038. }
  1039. static void spi_unmap_buf_attrs(struct spi_controller *ctlr,
  1040. struct device *dev, struct sg_table *sgt,
  1041. enum dma_data_direction dir,
  1042. unsigned long attrs)
  1043. {
  1044. dma_unmap_sgtable(dev, sgt, dir, attrs);
  1045. sg_free_table(sgt);
  1046. sgt->orig_nents = 0;
  1047. sgt->nents = 0;
  1048. }
  1049. void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
  1050. struct sg_table *sgt, enum dma_data_direction dir)
  1051. {
  1052. spi_unmap_buf_attrs(ctlr, dev, sgt, dir, 0);
  1053. }
  1054. static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
  1055. {
  1056. struct device *tx_dev, *rx_dev;
  1057. struct spi_transfer *xfer;
  1058. int ret;
  1059. if (!ctlr->can_dma)
  1060. return 0;
  1061. if (ctlr->dma_tx)
  1062. tx_dev = ctlr->dma_tx->device->dev;
  1063. else if (ctlr->dma_map_dev)
  1064. tx_dev = ctlr->dma_map_dev;
  1065. else
  1066. tx_dev = ctlr->dev.parent;
  1067. if (ctlr->dma_rx)
  1068. rx_dev = ctlr->dma_rx->device->dev;
  1069. else if (ctlr->dma_map_dev)
  1070. rx_dev = ctlr->dma_map_dev;
  1071. else
  1072. rx_dev = ctlr->dev.parent;
  1073. ret = -ENOMSG;
  1074. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  1075. /* The sync is done before each transfer. */
  1076. unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
  1077. if (!ctlr->can_dma(ctlr, msg->spi, xfer))
  1078. continue;
  1079. if (xfer->tx_buf != NULL) {
  1080. ret = spi_map_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
  1081. (void *)xfer->tx_buf,
  1082. xfer->len, DMA_TO_DEVICE,
  1083. attrs);
  1084. if (ret != 0)
  1085. return ret;
  1086. xfer->tx_sg_mapped = true;
  1087. }
  1088. if (xfer->rx_buf != NULL) {
  1089. ret = spi_map_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
  1090. xfer->rx_buf, xfer->len,
  1091. DMA_FROM_DEVICE, attrs);
  1092. if (ret != 0) {
  1093. spi_unmap_buf_attrs(ctlr, tx_dev,
  1094. &xfer->tx_sg, DMA_TO_DEVICE,
  1095. attrs);
  1096. return ret;
  1097. }
  1098. xfer->rx_sg_mapped = true;
  1099. }
  1100. }
  1101. /* No transfer has been mapped, bail out with success */
  1102. if (ret)
  1103. return 0;
  1104. ctlr->cur_rx_dma_dev = rx_dev;
  1105. ctlr->cur_tx_dma_dev = tx_dev;
  1106. return 0;
  1107. }
  1108. static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
  1109. {
  1110. struct device *rx_dev = ctlr->cur_rx_dma_dev;
  1111. struct device *tx_dev = ctlr->cur_tx_dma_dev;
  1112. struct spi_transfer *xfer;
  1113. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  1114. /* The sync has already been done after each transfer. */
  1115. unsigned long attrs = DMA_ATTR_SKIP_CPU_SYNC;
  1116. if (xfer->rx_sg_mapped)
  1117. spi_unmap_buf_attrs(ctlr, rx_dev, &xfer->rx_sg,
  1118. DMA_FROM_DEVICE, attrs);
  1119. xfer->rx_sg_mapped = false;
  1120. if (xfer->tx_sg_mapped)
  1121. spi_unmap_buf_attrs(ctlr, tx_dev, &xfer->tx_sg,
  1122. DMA_TO_DEVICE, attrs);
  1123. xfer->tx_sg_mapped = false;
  1124. }
  1125. return 0;
  1126. }
  1127. static void spi_dma_sync_for_device(struct spi_controller *ctlr,
  1128. struct spi_transfer *xfer)
  1129. {
  1130. struct device *rx_dev = ctlr->cur_rx_dma_dev;
  1131. struct device *tx_dev = ctlr->cur_tx_dma_dev;
  1132. if (xfer->tx_sg_mapped)
  1133. dma_sync_sgtable_for_device(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
  1134. if (xfer->rx_sg_mapped)
  1135. dma_sync_sgtable_for_device(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
  1136. }
  1137. static void spi_dma_sync_for_cpu(struct spi_controller *ctlr,
  1138. struct spi_transfer *xfer)
  1139. {
  1140. struct device *rx_dev = ctlr->cur_rx_dma_dev;
  1141. struct device *tx_dev = ctlr->cur_tx_dma_dev;
  1142. if (xfer->rx_sg_mapped)
  1143. dma_sync_sgtable_for_cpu(rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
  1144. if (xfer->tx_sg_mapped)
  1145. dma_sync_sgtable_for_cpu(tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
  1146. }
  1147. #else /* !CONFIG_HAS_DMA */
  1148. static inline int __spi_map_msg(struct spi_controller *ctlr,
  1149. struct spi_message *msg)
  1150. {
  1151. return 0;
  1152. }
  1153. static inline int __spi_unmap_msg(struct spi_controller *ctlr,
  1154. struct spi_message *msg)
  1155. {
  1156. return 0;
  1157. }
  1158. static void spi_dma_sync_for_device(struct spi_controller *ctrl,
  1159. struct spi_transfer *xfer)
  1160. {
  1161. }
  1162. static void spi_dma_sync_for_cpu(struct spi_controller *ctrl,
  1163. struct spi_transfer *xfer)
  1164. {
  1165. }
  1166. #endif /* !CONFIG_HAS_DMA */
  1167. static inline int spi_unmap_msg(struct spi_controller *ctlr,
  1168. struct spi_message *msg)
  1169. {
  1170. struct spi_transfer *xfer;
  1171. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  1172. /*
  1173. * Restore the original value of tx_buf or rx_buf if they are
  1174. * NULL.
  1175. */
  1176. if (xfer->tx_buf == ctlr->dummy_tx)
  1177. xfer->tx_buf = NULL;
  1178. if (xfer->rx_buf == ctlr->dummy_rx)
  1179. xfer->rx_buf = NULL;
  1180. }
  1181. return __spi_unmap_msg(ctlr, msg);
  1182. }
  1183. static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
  1184. {
  1185. struct spi_transfer *xfer;
  1186. void *tmp;
  1187. unsigned int max_tx, max_rx;
  1188. if ((ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX))
  1189. && !(msg->spi->mode & SPI_3WIRE)) {
  1190. max_tx = 0;
  1191. max_rx = 0;
  1192. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  1193. if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
  1194. !xfer->tx_buf)
  1195. max_tx = max(xfer->len, max_tx);
  1196. if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
  1197. !xfer->rx_buf)
  1198. max_rx = max(xfer->len, max_rx);
  1199. }
  1200. if (max_tx) {
  1201. tmp = krealloc(ctlr->dummy_tx, max_tx,
  1202. GFP_KERNEL | GFP_DMA | __GFP_ZERO);
  1203. if (!tmp)
  1204. return -ENOMEM;
  1205. ctlr->dummy_tx = tmp;
  1206. }
  1207. if (max_rx) {
  1208. tmp = krealloc(ctlr->dummy_rx, max_rx,
  1209. GFP_KERNEL | GFP_DMA);
  1210. if (!tmp)
  1211. return -ENOMEM;
  1212. ctlr->dummy_rx = tmp;
  1213. }
  1214. if (max_tx || max_rx) {
  1215. list_for_each_entry(xfer, &msg->transfers,
  1216. transfer_list) {
  1217. if (!xfer->len)
  1218. continue;
  1219. if (!xfer->tx_buf)
  1220. xfer->tx_buf = ctlr->dummy_tx;
  1221. if (!xfer->rx_buf)
  1222. xfer->rx_buf = ctlr->dummy_rx;
  1223. }
  1224. }
  1225. }
  1226. return __spi_map_msg(ctlr, msg);
  1227. }
  1228. static int spi_transfer_wait(struct spi_controller *ctlr,
  1229. struct spi_message *msg,
  1230. struct spi_transfer *xfer)
  1231. {
  1232. struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
  1233. struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
  1234. u32 speed_hz = xfer->speed_hz;
  1235. unsigned long long ms;
  1236. if (spi_controller_is_target(ctlr)) {
  1237. if (wait_for_completion_interruptible(&ctlr->xfer_completion)) {
  1238. dev_dbg(&msg->spi->dev, "SPI transfer interrupted\n");
  1239. return -EINTR;
  1240. }
  1241. } else {
  1242. if (!speed_hz)
  1243. speed_hz = 100000;
  1244. /*
  1245. * For each byte we wait for 8 cycles of the SPI clock.
  1246. * Since speed is defined in Hz and we want milliseconds,
  1247. * use respective multiplier, but before the division,
  1248. * otherwise we may get 0 for short transfers.
  1249. */
  1250. ms = 8LL * MSEC_PER_SEC * xfer->len;
  1251. do_div(ms, speed_hz);
  1252. /*
  1253. * Increase it twice and add 200 ms tolerance, use
  1254. * predefined maximum in case of overflow.
  1255. */
  1256. ms += ms + 200;
  1257. if (ms > UINT_MAX)
  1258. ms = UINT_MAX;
  1259. ms = wait_for_completion_timeout(&ctlr->xfer_completion,
  1260. msecs_to_jiffies(ms));
  1261. if (ms == 0) {
  1262. SPI_STATISTICS_INCREMENT_FIELD(statm, timedout);
  1263. SPI_STATISTICS_INCREMENT_FIELD(stats, timedout);
  1264. dev_err(&msg->spi->dev,
  1265. "SPI transfer timed out\n");
  1266. return -ETIMEDOUT;
  1267. }
  1268. if (xfer->error & SPI_TRANS_FAIL_IO)
  1269. return -EIO;
  1270. }
  1271. return 0;
  1272. }
  1273. static void _spi_transfer_delay_ns(u32 ns)
  1274. {
  1275. if (!ns)
  1276. return;
  1277. if (ns <= NSEC_PER_USEC) {
  1278. ndelay(ns);
  1279. } else {
  1280. u32 us = DIV_ROUND_UP(ns, NSEC_PER_USEC);
  1281. if (us <= 10)
  1282. udelay(us);
  1283. else
  1284. usleep_range(us, us + DIV_ROUND_UP(us, 10));
  1285. }
  1286. }
  1287. int spi_delay_to_ns(struct spi_delay *_delay, struct spi_transfer *xfer)
  1288. {
  1289. u32 delay = _delay->value;
  1290. u32 unit = _delay->unit;
  1291. u32 hz;
  1292. if (!delay)
  1293. return 0;
  1294. switch (unit) {
  1295. case SPI_DELAY_UNIT_USECS:
  1296. delay *= NSEC_PER_USEC;
  1297. break;
  1298. case SPI_DELAY_UNIT_NSECS:
  1299. /* Nothing to do here */
  1300. break;
  1301. case SPI_DELAY_UNIT_SCK:
  1302. /* Clock cycles need to be obtained from spi_transfer */
  1303. if (!xfer)
  1304. return -EINVAL;
  1305. /*
  1306. * If there is unknown effective speed, approximate it
  1307. * by underestimating with half of the requested Hz.
  1308. */
  1309. hz = xfer->effective_speed_hz ?: xfer->speed_hz / 2;
  1310. if (!hz)
  1311. return -EINVAL;
  1312. /* Convert delay to nanoseconds */
  1313. delay *= DIV_ROUND_UP(NSEC_PER_SEC, hz);
  1314. break;
  1315. default:
  1316. return -EINVAL;
  1317. }
  1318. return delay;
  1319. }
  1320. EXPORT_SYMBOL_GPL(spi_delay_to_ns);
  1321. int spi_delay_exec(struct spi_delay *_delay, struct spi_transfer *xfer)
  1322. {
  1323. int delay;
  1324. might_sleep();
  1325. if (!_delay)
  1326. return -EINVAL;
  1327. delay = spi_delay_to_ns(_delay, xfer);
  1328. if (delay < 0)
  1329. return delay;
  1330. _spi_transfer_delay_ns(delay);
  1331. return 0;
  1332. }
  1333. EXPORT_SYMBOL_GPL(spi_delay_exec);
  1334. static void _spi_transfer_cs_change_delay(struct spi_message *msg,
  1335. struct spi_transfer *xfer)
  1336. {
  1337. u32 default_delay_ns = 10 * NSEC_PER_USEC;
  1338. u32 delay = xfer->cs_change_delay.value;
  1339. u32 unit = xfer->cs_change_delay.unit;
  1340. int ret;
  1341. /* Return early on "fast" mode - for everything but USECS */
  1342. if (!delay) {
  1343. if (unit == SPI_DELAY_UNIT_USECS)
  1344. _spi_transfer_delay_ns(default_delay_ns);
  1345. return;
  1346. }
  1347. ret = spi_delay_exec(&xfer->cs_change_delay, xfer);
  1348. if (ret) {
  1349. dev_err_once(&msg->spi->dev,
  1350. "Use of unsupported delay unit %i, using default of %luus\n",
  1351. unit, default_delay_ns / NSEC_PER_USEC);
  1352. _spi_transfer_delay_ns(default_delay_ns);
  1353. }
  1354. }
  1355. void spi_transfer_cs_change_delay_exec(struct spi_message *msg,
  1356. struct spi_transfer *xfer)
  1357. {
  1358. _spi_transfer_cs_change_delay(msg, xfer);
  1359. }
  1360. EXPORT_SYMBOL_GPL(spi_transfer_cs_change_delay_exec);
  1361. /*
  1362. * spi_transfer_one_message - Default implementation of transfer_one_message()
  1363. *
  1364. * This is a standard implementation of transfer_one_message() for
  1365. * drivers which implement a transfer_one() operation. It provides
  1366. * standard handling of delays and chip select management.
  1367. */
  1368. static int spi_transfer_one_message(struct spi_controller *ctlr,
  1369. struct spi_message *msg)
  1370. {
  1371. struct spi_transfer *xfer;
  1372. bool keep_cs = false;
  1373. int ret = 0;
  1374. struct spi_statistics __percpu *statm = ctlr->pcpu_statistics;
  1375. struct spi_statistics __percpu *stats = msg->spi->pcpu_statistics;
  1376. xfer = list_first_entry(&msg->transfers, struct spi_transfer, transfer_list);
  1377. spi_set_cs(msg->spi, !xfer->cs_off, false);
  1378. SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
  1379. SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
  1380. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  1381. trace_spi_transfer_start(msg, xfer);
  1382. spi_statistics_add_transfer_stats(statm, xfer, msg);
  1383. spi_statistics_add_transfer_stats(stats, xfer, msg);
  1384. if (!ctlr->ptp_sts_supported) {
  1385. xfer->ptp_sts_word_pre = 0;
  1386. ptp_read_system_prets(xfer->ptp_sts);
  1387. }
  1388. if ((xfer->tx_buf || xfer->rx_buf) && xfer->len) {
  1389. reinit_completion(&ctlr->xfer_completion);
  1390. fallback_pio:
  1391. spi_dma_sync_for_device(ctlr, xfer);
  1392. ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
  1393. if (ret < 0) {
  1394. spi_dma_sync_for_cpu(ctlr, xfer);
  1395. if ((xfer->tx_sg_mapped || xfer->rx_sg_mapped) &&
  1396. (xfer->error & SPI_TRANS_FAIL_NO_START)) {
  1397. __spi_unmap_msg(ctlr, msg);
  1398. ctlr->fallback = true;
  1399. xfer->error &= ~SPI_TRANS_FAIL_NO_START;
  1400. goto fallback_pio;
  1401. }
  1402. SPI_STATISTICS_INCREMENT_FIELD(statm,
  1403. errors);
  1404. SPI_STATISTICS_INCREMENT_FIELD(stats,
  1405. errors);
  1406. dev_err(&msg->spi->dev,
  1407. "SPI transfer failed: %d\n", ret);
  1408. goto out;
  1409. }
  1410. if (ret > 0) {
  1411. ret = spi_transfer_wait(ctlr, msg, xfer);
  1412. if (ret < 0)
  1413. msg->status = ret;
  1414. }
  1415. spi_dma_sync_for_cpu(ctlr, xfer);
  1416. } else {
  1417. if (xfer->len)
  1418. dev_err(&msg->spi->dev,
  1419. "Bufferless transfer has length %u\n",
  1420. xfer->len);
  1421. }
  1422. if (!ctlr->ptp_sts_supported) {
  1423. ptp_read_system_postts(xfer->ptp_sts);
  1424. xfer->ptp_sts_word_post = xfer->len;
  1425. }
  1426. trace_spi_transfer_stop(msg, xfer);
  1427. if (msg->status != -EINPROGRESS)
  1428. goto out;
  1429. spi_transfer_delay_exec(xfer);
  1430. if (xfer->cs_change) {
  1431. if (list_is_last(&xfer->transfer_list,
  1432. &msg->transfers)) {
  1433. keep_cs = true;
  1434. } else {
  1435. if (!xfer->cs_off)
  1436. spi_set_cs(msg->spi, false, false);
  1437. _spi_transfer_cs_change_delay(msg, xfer);
  1438. if (!list_next_entry(xfer, transfer_list)->cs_off)
  1439. spi_set_cs(msg->spi, true, false);
  1440. }
  1441. } else if (!list_is_last(&xfer->transfer_list, &msg->transfers) &&
  1442. xfer->cs_off != list_next_entry(xfer, transfer_list)->cs_off) {
  1443. spi_set_cs(msg->spi, xfer->cs_off, false);
  1444. }
  1445. msg->actual_length += xfer->len;
  1446. }
  1447. out:
  1448. if (ret != 0 || !keep_cs)
  1449. spi_set_cs(msg->spi, false, false);
  1450. if (msg->status == -EINPROGRESS)
  1451. msg->status = ret;
  1452. if (msg->status && ctlr->handle_err)
  1453. ctlr->handle_err(ctlr, msg);
  1454. spi_finalize_current_message(ctlr);
  1455. return ret;
  1456. }
  1457. /**
  1458. * spi_finalize_current_transfer - report completion of a transfer
  1459. * @ctlr: the controller reporting completion
  1460. *
  1461. * Called by SPI drivers using the core transfer_one_message()
  1462. * implementation to notify it that the current interrupt driven
  1463. * transfer has finished and the next one may be scheduled.
  1464. */
  1465. void spi_finalize_current_transfer(struct spi_controller *ctlr)
  1466. {
  1467. complete(&ctlr->xfer_completion);
  1468. }
  1469. EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
  1470. static void spi_idle_runtime_pm(struct spi_controller *ctlr)
  1471. {
  1472. if (ctlr->auto_runtime_pm) {
  1473. pm_runtime_mark_last_busy(ctlr->dev.parent);
  1474. pm_runtime_put_autosuspend(ctlr->dev.parent);
  1475. }
  1476. }
  1477. static int __spi_pump_transfer_message(struct spi_controller *ctlr,
  1478. struct spi_message *msg, bool was_busy)
  1479. {
  1480. struct spi_transfer *xfer;
  1481. int ret;
  1482. if (!was_busy && ctlr->auto_runtime_pm) {
  1483. ret = pm_runtime_get_sync(ctlr->dev.parent);
  1484. if (ret < 0) {
  1485. pm_runtime_put_noidle(ctlr->dev.parent);
  1486. dev_err(&ctlr->dev, "Failed to power device: %d\n",
  1487. ret);
  1488. msg->status = ret;
  1489. spi_finalize_current_message(ctlr);
  1490. return ret;
  1491. }
  1492. }
  1493. if (!was_busy)
  1494. trace_spi_controller_busy(ctlr);
  1495. if (!was_busy && ctlr->prepare_transfer_hardware) {
  1496. ret = ctlr->prepare_transfer_hardware(ctlr);
  1497. if (ret) {
  1498. dev_err(&ctlr->dev,
  1499. "failed to prepare transfer hardware: %d\n",
  1500. ret);
  1501. if (ctlr->auto_runtime_pm)
  1502. pm_runtime_put(ctlr->dev.parent);
  1503. msg->status = ret;
  1504. spi_finalize_current_message(ctlr);
  1505. return ret;
  1506. }
  1507. }
  1508. trace_spi_message_start(msg);
  1509. if (ctlr->prepare_message) {
  1510. ret = ctlr->prepare_message(ctlr, msg);
  1511. if (ret) {
  1512. dev_err(&ctlr->dev, "failed to prepare message: %d\n",
  1513. ret);
  1514. msg->status = ret;
  1515. spi_finalize_current_message(ctlr);
  1516. return ret;
  1517. }
  1518. msg->prepared = true;
  1519. }
  1520. ret = spi_map_msg(ctlr, msg);
  1521. if (ret) {
  1522. msg->status = ret;
  1523. spi_finalize_current_message(ctlr);
  1524. return ret;
  1525. }
  1526. if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
  1527. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  1528. xfer->ptp_sts_word_pre = 0;
  1529. ptp_read_system_prets(xfer->ptp_sts);
  1530. }
  1531. }
  1532. /*
  1533. * Drivers implementation of transfer_one_message() must arrange for
  1534. * spi_finalize_current_message() to get called. Most drivers will do
  1535. * this in the calling context, but some don't. For those cases, a
  1536. * completion is used to guarantee that this function does not return
  1537. * until spi_finalize_current_message() is done accessing
  1538. * ctlr->cur_msg.
  1539. * Use of the following two flags enable to opportunistically skip the
  1540. * use of the completion since its use involves expensive spin locks.
  1541. * In case of a race with the context that calls
  1542. * spi_finalize_current_message() the completion will always be used,
  1543. * due to strict ordering of these flags using barriers.
  1544. */
  1545. WRITE_ONCE(ctlr->cur_msg_incomplete, true);
  1546. WRITE_ONCE(ctlr->cur_msg_need_completion, false);
  1547. reinit_completion(&ctlr->cur_msg_completion);
  1548. smp_wmb(); /* Make these available to spi_finalize_current_message() */
  1549. ret = ctlr->transfer_one_message(ctlr, msg);
  1550. if (ret) {
  1551. dev_err(&ctlr->dev,
  1552. "failed to transfer one message from queue\n");
  1553. return ret;
  1554. }
  1555. WRITE_ONCE(ctlr->cur_msg_need_completion, true);
  1556. smp_mb(); /* See spi_finalize_current_message()... */
  1557. if (READ_ONCE(ctlr->cur_msg_incomplete))
  1558. wait_for_completion(&ctlr->cur_msg_completion);
  1559. return 0;
  1560. }
  1561. /**
  1562. * __spi_pump_messages - function which processes SPI message queue
  1563. * @ctlr: controller to process queue for
  1564. * @in_kthread: true if we are in the context of the message pump thread
  1565. *
  1566. * This function checks if there is any SPI message in the queue that
  1567. * needs processing and if so call out to the driver to initialize hardware
  1568. * and transfer each message.
  1569. *
  1570. * Note that it is called both from the kthread itself and also from
  1571. * inside spi_sync(); the queue extraction handling at the top of the
  1572. * function should deal with this safely.
  1573. */
  1574. static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
  1575. {
  1576. struct spi_message *msg;
  1577. bool was_busy = false;
  1578. unsigned long flags;
  1579. int ret;
  1580. /* Take the I/O mutex */
  1581. mutex_lock(&ctlr->io_mutex);
  1582. /* Lock queue */
  1583. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1584. /* Make sure we are not already running a message */
  1585. if (ctlr->cur_msg)
  1586. goto out_unlock;
  1587. /* Check if the queue is idle */
  1588. if (list_empty(&ctlr->queue) || !ctlr->running) {
  1589. if (!ctlr->busy)
  1590. goto out_unlock;
  1591. /* Defer any non-atomic teardown to the thread */
  1592. if (!in_kthread) {
  1593. if (!ctlr->dummy_rx && !ctlr->dummy_tx &&
  1594. !ctlr->unprepare_transfer_hardware) {
  1595. spi_idle_runtime_pm(ctlr);
  1596. ctlr->busy = false;
  1597. ctlr->queue_empty = true;
  1598. trace_spi_controller_idle(ctlr);
  1599. } else {
  1600. kthread_queue_work(ctlr->kworker,
  1601. &ctlr->pump_messages);
  1602. }
  1603. goto out_unlock;
  1604. }
  1605. ctlr->busy = false;
  1606. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1607. kfree(ctlr->dummy_rx);
  1608. ctlr->dummy_rx = NULL;
  1609. kfree(ctlr->dummy_tx);
  1610. ctlr->dummy_tx = NULL;
  1611. if (ctlr->unprepare_transfer_hardware &&
  1612. ctlr->unprepare_transfer_hardware(ctlr))
  1613. dev_err(&ctlr->dev,
  1614. "failed to unprepare transfer hardware\n");
  1615. spi_idle_runtime_pm(ctlr);
  1616. trace_spi_controller_idle(ctlr);
  1617. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1618. ctlr->queue_empty = true;
  1619. goto out_unlock;
  1620. }
  1621. /* Extract head of queue */
  1622. msg = list_first_entry(&ctlr->queue, struct spi_message, queue);
  1623. ctlr->cur_msg = msg;
  1624. list_del_init(&msg->queue);
  1625. if (ctlr->busy)
  1626. was_busy = true;
  1627. else
  1628. ctlr->busy = true;
  1629. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1630. ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
  1631. kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
  1632. ctlr->cur_msg = NULL;
  1633. ctlr->fallback = false;
  1634. mutex_unlock(&ctlr->io_mutex);
  1635. /* Prod the scheduler in case transfer_one() was busy waiting */
  1636. if (!ret)
  1637. cond_resched();
  1638. return;
  1639. out_unlock:
  1640. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1641. mutex_unlock(&ctlr->io_mutex);
  1642. }
  1643. /**
  1644. * spi_pump_messages - kthread work function which processes spi message queue
  1645. * @work: pointer to kthread work struct contained in the controller struct
  1646. */
  1647. static void spi_pump_messages(struct kthread_work *work)
  1648. {
  1649. struct spi_controller *ctlr =
  1650. container_of(work, struct spi_controller, pump_messages);
  1651. __spi_pump_messages(ctlr, true);
  1652. }
  1653. /**
  1654. * spi_take_timestamp_pre - helper to collect the beginning of the TX timestamp
  1655. * @ctlr: Pointer to the spi_controller structure of the driver
  1656. * @xfer: Pointer to the transfer being timestamped
  1657. * @progress: How many words (not bytes) have been transferred so far
  1658. * @irqs_off: If true, will disable IRQs and preemption for the duration of the
  1659. * transfer, for less jitter in time measurement. Only compatible
  1660. * with PIO drivers. If true, must follow up with
  1661. * spi_take_timestamp_post or otherwise system will crash.
  1662. * WARNING: for fully predictable results, the CPU frequency must
  1663. * also be under control (governor).
  1664. *
  1665. * This is a helper for drivers to collect the beginning of the TX timestamp
  1666. * for the requested byte from the SPI transfer. The frequency with which this
  1667. * function must be called (once per word, once for the whole transfer, once
  1668. * per batch of words etc) is arbitrary as long as the @tx buffer offset is
  1669. * greater than or equal to the requested byte at the time of the call. The
  1670. * timestamp is only taken once, at the first such call. It is assumed that
  1671. * the driver advances its @tx buffer pointer monotonically.
  1672. */
  1673. void spi_take_timestamp_pre(struct spi_controller *ctlr,
  1674. struct spi_transfer *xfer,
  1675. size_t progress, bool irqs_off)
  1676. {
  1677. if (!xfer->ptp_sts)
  1678. return;
  1679. if (xfer->timestamped)
  1680. return;
  1681. if (progress > xfer->ptp_sts_word_pre)
  1682. return;
  1683. /* Capture the resolution of the timestamp */
  1684. xfer->ptp_sts_word_pre = progress;
  1685. if (irqs_off) {
  1686. local_irq_save(ctlr->irq_flags);
  1687. preempt_disable();
  1688. }
  1689. ptp_read_system_prets(xfer->ptp_sts);
  1690. }
  1691. EXPORT_SYMBOL_GPL(spi_take_timestamp_pre);
  1692. /**
  1693. * spi_take_timestamp_post - helper to collect the end of the TX timestamp
  1694. * @ctlr: Pointer to the spi_controller structure of the driver
  1695. * @xfer: Pointer to the transfer being timestamped
  1696. * @progress: How many words (not bytes) have been transferred so far
  1697. * @irqs_off: If true, will re-enable IRQs and preemption for the local CPU.
  1698. *
  1699. * This is a helper for drivers to collect the end of the TX timestamp for
  1700. * the requested byte from the SPI transfer. Can be called with an arbitrary
  1701. * frequency: only the first call where @tx exceeds or is equal to the
  1702. * requested word will be timestamped.
  1703. */
  1704. void spi_take_timestamp_post(struct spi_controller *ctlr,
  1705. struct spi_transfer *xfer,
  1706. size_t progress, bool irqs_off)
  1707. {
  1708. if (!xfer->ptp_sts)
  1709. return;
  1710. if (xfer->timestamped)
  1711. return;
  1712. if (progress < xfer->ptp_sts_word_post)
  1713. return;
  1714. ptp_read_system_postts(xfer->ptp_sts);
  1715. if (irqs_off) {
  1716. local_irq_restore(ctlr->irq_flags);
  1717. preempt_enable();
  1718. }
  1719. /* Capture the resolution of the timestamp */
  1720. xfer->ptp_sts_word_post = progress;
  1721. xfer->timestamped = 1;
  1722. }
  1723. EXPORT_SYMBOL_GPL(spi_take_timestamp_post);
  1724. /**
  1725. * spi_set_thread_rt - set the controller to pump at realtime priority
  1726. * @ctlr: controller to boost priority of
  1727. *
  1728. * This can be called because the controller requested realtime priority
  1729. * (by setting the ->rt value before calling spi_register_controller()) or
  1730. * because a device on the bus said that its transfers needed realtime
  1731. * priority.
  1732. *
  1733. * NOTE: at the moment if any device on a bus says it needs realtime then
  1734. * the thread will be at realtime priority for all transfers on that
  1735. * controller. If this eventually becomes a problem we may see if we can
  1736. * find a way to boost the priority only temporarily during relevant
  1737. * transfers.
  1738. */
  1739. static void spi_set_thread_rt(struct spi_controller *ctlr)
  1740. {
  1741. dev_info(&ctlr->dev,
  1742. "will run message pump with realtime priority\n");
  1743. sched_set_fifo(ctlr->kworker->task);
  1744. }
  1745. static int spi_init_queue(struct spi_controller *ctlr)
  1746. {
  1747. ctlr->running = false;
  1748. ctlr->busy = false;
  1749. ctlr->queue_empty = true;
  1750. ctlr->kworker = kthread_create_worker(0, dev_name(&ctlr->dev));
  1751. if (IS_ERR(ctlr->kworker)) {
  1752. dev_err(&ctlr->dev, "failed to create message pump kworker\n");
  1753. return PTR_ERR(ctlr->kworker);
  1754. }
  1755. kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
  1756. /*
  1757. * Controller config will indicate if this controller should run the
  1758. * message pump with high (realtime) priority to reduce the transfer
  1759. * latency on the bus by minimising the delay between a transfer
  1760. * request and the scheduling of the message pump thread. Without this
  1761. * setting the message pump thread will remain at default priority.
  1762. */
  1763. if (ctlr->rt)
  1764. spi_set_thread_rt(ctlr);
  1765. return 0;
  1766. }
  1767. /**
  1768. * spi_get_next_queued_message() - called by driver to check for queued
  1769. * messages
  1770. * @ctlr: the controller to check for queued messages
  1771. *
  1772. * If there are more messages in the queue, the next message is returned from
  1773. * this call.
  1774. *
  1775. * Return: the next message in the queue, else NULL if the queue is empty.
  1776. */
  1777. struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
  1778. {
  1779. struct spi_message *next;
  1780. unsigned long flags;
  1781. /* Get a pointer to the next message, if any */
  1782. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1783. next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
  1784. queue);
  1785. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1786. return next;
  1787. }
  1788. EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
  1789. /*
  1790. * __spi_unoptimize_message - shared implementation of spi_unoptimize_message()
  1791. * and spi_maybe_unoptimize_message()
  1792. * @msg: the message to unoptimize
  1793. *
  1794. * Peripheral drivers should use spi_unoptimize_message() and callers inside
  1795. * core should use spi_maybe_unoptimize_message() rather than calling this
  1796. * function directly.
  1797. *
  1798. * It is not valid to call this on a message that is not currently optimized.
  1799. */
  1800. static void __spi_unoptimize_message(struct spi_message *msg)
  1801. {
  1802. struct spi_controller *ctlr = msg->spi->controller;
  1803. if (ctlr->unoptimize_message)
  1804. ctlr->unoptimize_message(msg);
  1805. spi_res_release(ctlr, msg);
  1806. msg->optimized = false;
  1807. msg->opt_state = NULL;
  1808. }
  1809. /*
  1810. * spi_maybe_unoptimize_message - unoptimize msg not managed by a peripheral
  1811. * @msg: the message to unoptimize
  1812. *
  1813. * This function is used to unoptimize a message if and only if it was
  1814. * optimized by the core (via spi_maybe_optimize_message()).
  1815. */
  1816. static void spi_maybe_unoptimize_message(struct spi_message *msg)
  1817. {
  1818. if (!msg->pre_optimized && msg->optimized &&
  1819. !msg->spi->controller->defer_optimize_message)
  1820. __spi_unoptimize_message(msg);
  1821. }
  1822. /**
  1823. * spi_finalize_current_message() - the current message is complete
  1824. * @ctlr: the controller to return the message to
  1825. *
  1826. * Called by the driver to notify the core that the message in the front of the
  1827. * queue is complete and can be removed from the queue.
  1828. */
  1829. void spi_finalize_current_message(struct spi_controller *ctlr)
  1830. {
  1831. struct spi_transfer *xfer;
  1832. struct spi_message *mesg;
  1833. int ret;
  1834. mesg = ctlr->cur_msg;
  1835. if (!ctlr->ptp_sts_supported && !ctlr->transfer_one) {
  1836. list_for_each_entry(xfer, &mesg->transfers, transfer_list) {
  1837. ptp_read_system_postts(xfer->ptp_sts);
  1838. xfer->ptp_sts_word_post = xfer->len;
  1839. }
  1840. }
  1841. if (unlikely(ctlr->ptp_sts_supported))
  1842. list_for_each_entry(xfer, &mesg->transfers, transfer_list)
  1843. WARN_ON_ONCE(xfer->ptp_sts && !xfer->timestamped);
  1844. spi_unmap_msg(ctlr, mesg);
  1845. if (mesg->prepared && ctlr->unprepare_message) {
  1846. ret = ctlr->unprepare_message(ctlr, mesg);
  1847. if (ret) {
  1848. dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
  1849. ret);
  1850. }
  1851. }
  1852. mesg->prepared = false;
  1853. spi_maybe_unoptimize_message(mesg);
  1854. WRITE_ONCE(ctlr->cur_msg_incomplete, false);
  1855. smp_mb(); /* See __spi_pump_transfer_message()... */
  1856. if (READ_ONCE(ctlr->cur_msg_need_completion))
  1857. complete(&ctlr->cur_msg_completion);
  1858. trace_spi_message_done(mesg);
  1859. mesg->state = NULL;
  1860. if (mesg->complete)
  1861. mesg->complete(mesg->context);
  1862. }
  1863. EXPORT_SYMBOL_GPL(spi_finalize_current_message);
  1864. static int spi_start_queue(struct spi_controller *ctlr)
  1865. {
  1866. unsigned long flags;
  1867. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1868. if (ctlr->running || ctlr->busy) {
  1869. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1870. return -EBUSY;
  1871. }
  1872. ctlr->running = true;
  1873. ctlr->cur_msg = NULL;
  1874. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1875. kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
  1876. return 0;
  1877. }
  1878. static int spi_stop_queue(struct spi_controller *ctlr)
  1879. {
  1880. unsigned int limit = 500;
  1881. unsigned long flags;
  1882. /*
  1883. * This is a bit lame, but is optimized for the common execution path.
  1884. * A wait_queue on the ctlr->busy could be used, but then the common
  1885. * execution path (pump_messages) would be required to call wake_up or
  1886. * friends on every SPI message. Do this instead.
  1887. */
  1888. do {
  1889. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1890. if (list_empty(&ctlr->queue) && !ctlr->busy) {
  1891. ctlr->running = false;
  1892. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1893. return 0;
  1894. }
  1895. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1896. usleep_range(10000, 11000);
  1897. } while (--limit);
  1898. return -EBUSY;
  1899. }
  1900. static int spi_destroy_queue(struct spi_controller *ctlr)
  1901. {
  1902. int ret;
  1903. ret = spi_stop_queue(ctlr);
  1904. /*
  1905. * kthread_flush_worker will block until all work is done.
  1906. * If the reason that stop_queue timed out is that the work will never
  1907. * finish, then it does no good to call flush/stop thread, so
  1908. * return anyway.
  1909. */
  1910. if (ret) {
  1911. dev_err(&ctlr->dev, "problem destroying queue\n");
  1912. return ret;
  1913. }
  1914. kthread_destroy_worker(ctlr->kworker);
  1915. return 0;
  1916. }
  1917. static int __spi_queued_transfer(struct spi_device *spi,
  1918. struct spi_message *msg,
  1919. bool need_pump)
  1920. {
  1921. struct spi_controller *ctlr = spi->controller;
  1922. unsigned long flags;
  1923. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1924. if (!ctlr->running) {
  1925. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1926. return -ESHUTDOWN;
  1927. }
  1928. msg->actual_length = 0;
  1929. msg->status = -EINPROGRESS;
  1930. list_add_tail(&msg->queue, &ctlr->queue);
  1931. ctlr->queue_empty = false;
  1932. if (!ctlr->busy && need_pump)
  1933. kthread_queue_work(ctlr->kworker, &ctlr->pump_messages);
  1934. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1935. return 0;
  1936. }
  1937. /**
  1938. * spi_queued_transfer - transfer function for queued transfers
  1939. * @spi: SPI device which is requesting transfer
  1940. * @msg: SPI message which is to handled is queued to driver queue
  1941. *
  1942. * Return: zero on success, else a negative error code.
  1943. */
  1944. static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
  1945. {
  1946. return __spi_queued_transfer(spi, msg, true);
  1947. }
  1948. static int spi_controller_initialize_queue(struct spi_controller *ctlr)
  1949. {
  1950. int ret;
  1951. ctlr->transfer = spi_queued_transfer;
  1952. if (!ctlr->transfer_one_message)
  1953. ctlr->transfer_one_message = spi_transfer_one_message;
  1954. /* Initialize and start queue */
  1955. ret = spi_init_queue(ctlr);
  1956. if (ret) {
  1957. dev_err(&ctlr->dev, "problem initializing queue\n");
  1958. goto err_init_queue;
  1959. }
  1960. ctlr->queued = true;
  1961. ret = spi_start_queue(ctlr);
  1962. if (ret) {
  1963. dev_err(&ctlr->dev, "problem starting queue\n");
  1964. goto err_start_queue;
  1965. }
  1966. return 0;
  1967. err_start_queue:
  1968. spi_destroy_queue(ctlr);
  1969. err_init_queue:
  1970. return ret;
  1971. }
  1972. /**
  1973. * spi_flush_queue - Send all pending messages in the queue from the callers'
  1974. * context
  1975. * @ctlr: controller to process queue for
  1976. *
  1977. * This should be used when one wants to ensure all pending messages have been
  1978. * sent before doing something. Is used by the spi-mem code to make sure SPI
  1979. * memory operations do not preempt regular SPI transfers that have been queued
  1980. * before the spi-mem operation.
  1981. */
  1982. void spi_flush_queue(struct spi_controller *ctlr)
  1983. {
  1984. if (ctlr->transfer == spi_queued_transfer)
  1985. __spi_pump_messages(ctlr, false);
  1986. }
  1987. /*-------------------------------------------------------------------------*/
  1988. #if defined(CONFIG_OF)
  1989. static void of_spi_parse_dt_cs_delay(struct device_node *nc,
  1990. struct spi_delay *delay, const char *prop)
  1991. {
  1992. u32 value;
  1993. if (!of_property_read_u32(nc, prop, &value)) {
  1994. if (value > U16_MAX) {
  1995. delay->value = DIV_ROUND_UP(value, 1000);
  1996. delay->unit = SPI_DELAY_UNIT_USECS;
  1997. } else {
  1998. delay->value = value;
  1999. delay->unit = SPI_DELAY_UNIT_NSECS;
  2000. }
  2001. }
  2002. }
  2003. static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
  2004. struct device_node *nc)
  2005. {
  2006. u32 value, cs[SPI_CS_CNT_MAX];
  2007. int rc, idx;
  2008. /* Mode (clock phase/polarity/etc.) */
  2009. if (of_property_read_bool(nc, "spi-cpha"))
  2010. spi->mode |= SPI_CPHA;
  2011. if (of_property_read_bool(nc, "spi-cpol"))
  2012. spi->mode |= SPI_CPOL;
  2013. if (of_property_read_bool(nc, "spi-3wire"))
  2014. spi->mode |= SPI_3WIRE;
  2015. if (of_property_read_bool(nc, "spi-lsb-first"))
  2016. spi->mode |= SPI_LSB_FIRST;
  2017. if (of_property_read_bool(nc, "spi-cs-high"))
  2018. spi->mode |= SPI_CS_HIGH;
  2019. /* Device DUAL/QUAD mode */
  2020. if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
  2021. switch (value) {
  2022. case 0:
  2023. spi->mode |= SPI_NO_TX;
  2024. break;
  2025. case 1:
  2026. break;
  2027. case 2:
  2028. spi->mode |= SPI_TX_DUAL;
  2029. break;
  2030. case 4:
  2031. spi->mode |= SPI_TX_QUAD;
  2032. break;
  2033. case 8:
  2034. spi->mode |= SPI_TX_OCTAL;
  2035. break;
  2036. default:
  2037. dev_warn(&ctlr->dev,
  2038. "spi-tx-bus-width %d not supported\n",
  2039. value);
  2040. break;
  2041. }
  2042. }
  2043. if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
  2044. switch (value) {
  2045. case 0:
  2046. spi->mode |= SPI_NO_RX;
  2047. break;
  2048. case 1:
  2049. break;
  2050. case 2:
  2051. spi->mode |= SPI_RX_DUAL;
  2052. break;
  2053. case 4:
  2054. spi->mode |= SPI_RX_QUAD;
  2055. break;
  2056. case 8:
  2057. spi->mode |= SPI_RX_OCTAL;
  2058. break;
  2059. default:
  2060. dev_warn(&ctlr->dev,
  2061. "spi-rx-bus-width %d not supported\n",
  2062. value);
  2063. break;
  2064. }
  2065. }
  2066. if (spi_controller_is_target(ctlr)) {
  2067. if (!of_node_name_eq(nc, "slave")) {
  2068. dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
  2069. nc);
  2070. return -EINVAL;
  2071. }
  2072. return 0;
  2073. }
  2074. if (ctlr->num_chipselect > SPI_CS_CNT_MAX) {
  2075. dev_err(&ctlr->dev, "No. of CS is more than max. no. of supported CS\n");
  2076. return -EINVAL;
  2077. }
  2078. spi_set_all_cs_unused(spi);
  2079. /* Device address */
  2080. rc = of_property_read_variable_u32_array(nc, "reg", &cs[0], 1,
  2081. SPI_CS_CNT_MAX);
  2082. if (rc < 0) {
  2083. dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
  2084. nc, rc);
  2085. return rc;
  2086. }
  2087. if (rc > ctlr->num_chipselect) {
  2088. dev_err(&ctlr->dev, "%pOF has number of CS > ctlr->num_chipselect (%d)\n",
  2089. nc, rc);
  2090. return -EINVAL;
  2091. }
  2092. if ((of_property_read_bool(nc, "parallel-memories")) &&
  2093. (!(ctlr->flags & SPI_CONTROLLER_MULTI_CS))) {
  2094. dev_err(&ctlr->dev, "SPI controller doesn't support multi CS\n");
  2095. return -EINVAL;
  2096. }
  2097. for (idx = 0; idx < rc; idx++)
  2098. spi_set_chipselect(spi, idx, cs[idx]);
  2099. /*
  2100. * By default spi->chip_select[0] will hold the physical CS number,
  2101. * so set bit 0 in spi->cs_index_mask.
  2102. */
  2103. spi->cs_index_mask = BIT(0);
  2104. /* Device speed */
  2105. if (!of_property_read_u32(nc, "spi-max-frequency", &value))
  2106. spi->max_speed_hz = value;
  2107. /* Device CS delays */
  2108. of_spi_parse_dt_cs_delay(nc, &spi->cs_setup, "spi-cs-setup-delay-ns");
  2109. of_spi_parse_dt_cs_delay(nc, &spi->cs_hold, "spi-cs-hold-delay-ns");
  2110. of_spi_parse_dt_cs_delay(nc, &spi->cs_inactive, "spi-cs-inactive-delay-ns");
  2111. return 0;
  2112. }
  2113. static struct spi_device *
  2114. of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
  2115. {
  2116. struct spi_device *spi;
  2117. int rc;
  2118. /* Alloc an spi_device */
  2119. spi = spi_alloc_device(ctlr);
  2120. if (!spi) {
  2121. dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
  2122. rc = -ENOMEM;
  2123. goto err_out;
  2124. }
  2125. /* Select device driver */
  2126. rc = of_alias_from_compatible(nc, spi->modalias,
  2127. sizeof(spi->modalias));
  2128. if (rc < 0) {
  2129. dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
  2130. goto err_out;
  2131. }
  2132. rc = of_spi_parse_dt(ctlr, spi, nc);
  2133. if (rc)
  2134. goto err_out;
  2135. /* Store a pointer to the node in the device structure */
  2136. of_node_get(nc);
  2137. device_set_node(&spi->dev, of_fwnode_handle(nc));
  2138. /* Register the new device */
  2139. rc = spi_add_device(spi);
  2140. if (rc) {
  2141. dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
  2142. goto err_of_node_put;
  2143. }
  2144. return spi;
  2145. err_of_node_put:
  2146. of_node_put(nc);
  2147. err_out:
  2148. spi_dev_put(spi);
  2149. return ERR_PTR(rc);
  2150. }
  2151. /**
  2152. * of_register_spi_devices() - Register child devices onto the SPI bus
  2153. * @ctlr: Pointer to spi_controller device
  2154. *
  2155. * Registers an spi_device for each child node of controller node which
  2156. * represents a valid SPI slave.
  2157. */
  2158. static void of_register_spi_devices(struct spi_controller *ctlr)
  2159. {
  2160. struct spi_device *spi;
  2161. struct device_node *nc;
  2162. for_each_available_child_of_node(ctlr->dev.of_node, nc) {
  2163. if (of_node_test_and_set_flag(nc, OF_POPULATED))
  2164. continue;
  2165. spi = of_register_spi_device(ctlr, nc);
  2166. if (IS_ERR(spi)) {
  2167. dev_warn(&ctlr->dev,
  2168. "Failed to create SPI device for %pOF\n", nc);
  2169. of_node_clear_flag(nc, OF_POPULATED);
  2170. }
  2171. }
  2172. }
  2173. #else
  2174. static void of_register_spi_devices(struct spi_controller *ctlr) { }
  2175. #endif
  2176. /**
  2177. * spi_new_ancillary_device() - Register ancillary SPI device
  2178. * @spi: Pointer to the main SPI device registering the ancillary device
  2179. * @chip_select: Chip Select of the ancillary device
  2180. *
  2181. * Register an ancillary SPI device; for example some chips have a chip-select
  2182. * for normal device usage and another one for setup/firmware upload.
  2183. *
  2184. * This may only be called from main SPI device's probe routine.
  2185. *
  2186. * Return: 0 on success; negative errno on failure
  2187. */
  2188. struct spi_device *spi_new_ancillary_device(struct spi_device *spi,
  2189. u8 chip_select)
  2190. {
  2191. struct spi_controller *ctlr = spi->controller;
  2192. struct spi_device *ancillary;
  2193. int rc;
  2194. /* Alloc an spi_device */
  2195. ancillary = spi_alloc_device(ctlr);
  2196. if (!ancillary) {
  2197. rc = -ENOMEM;
  2198. goto err_out;
  2199. }
  2200. strscpy(ancillary->modalias, "dummy", sizeof(ancillary->modalias));
  2201. /* Use provided chip-select for ancillary device */
  2202. spi_set_all_cs_unused(ancillary);
  2203. spi_set_chipselect(ancillary, 0, chip_select);
  2204. /* Take over SPI mode/speed from SPI main device */
  2205. ancillary->max_speed_hz = spi->max_speed_hz;
  2206. ancillary->mode = spi->mode;
  2207. /*
  2208. * By default spi->chip_select[0] will hold the physical CS number,
  2209. * so set bit 0 in spi->cs_index_mask.
  2210. */
  2211. ancillary->cs_index_mask = BIT(0);
  2212. WARN_ON(!mutex_is_locked(&ctlr->add_lock));
  2213. /* Register the new device */
  2214. rc = __spi_add_device(ancillary);
  2215. if (rc) {
  2216. dev_err(&spi->dev, "failed to register ancillary device\n");
  2217. goto err_out;
  2218. }
  2219. return ancillary;
  2220. err_out:
  2221. spi_dev_put(ancillary);
  2222. return ERR_PTR(rc);
  2223. }
  2224. EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
  2225. #ifdef CONFIG_ACPI
  2226. struct acpi_spi_lookup {
  2227. struct spi_controller *ctlr;
  2228. u32 max_speed_hz;
  2229. u32 mode;
  2230. int irq;
  2231. u8 bits_per_word;
  2232. u8 chip_select;
  2233. int n;
  2234. int index;
  2235. };
  2236. static int acpi_spi_count(struct acpi_resource *ares, void *data)
  2237. {
  2238. struct acpi_resource_spi_serialbus *sb;
  2239. int *count = data;
  2240. if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  2241. return 1;
  2242. sb = &ares->data.spi_serial_bus;
  2243. if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_SPI)
  2244. return 1;
  2245. *count = *count + 1;
  2246. return 1;
  2247. }
  2248. /**
  2249. * acpi_spi_count_resources - Count the number of SpiSerialBus resources
  2250. * @adev: ACPI device
  2251. *
  2252. * Return: the number of SpiSerialBus resources in the ACPI-device's
  2253. * resource-list; or a negative error code.
  2254. */
  2255. int acpi_spi_count_resources(struct acpi_device *adev)
  2256. {
  2257. LIST_HEAD(r);
  2258. int count = 0;
  2259. int ret;
  2260. ret = acpi_dev_get_resources(adev, &r, acpi_spi_count, &count);
  2261. if (ret < 0)
  2262. return ret;
  2263. acpi_dev_free_resource_list(&r);
  2264. return count;
  2265. }
  2266. EXPORT_SYMBOL_GPL(acpi_spi_count_resources);
  2267. static void acpi_spi_parse_apple_properties(struct acpi_device *dev,
  2268. struct acpi_spi_lookup *lookup)
  2269. {
  2270. const union acpi_object *obj;
  2271. if (!x86_apple_machine)
  2272. return;
  2273. if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
  2274. && obj->buffer.length >= 4)
  2275. lookup->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
  2276. if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
  2277. && obj->buffer.length == 8)
  2278. lookup->bits_per_word = *(u64 *)obj->buffer.pointer;
  2279. if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
  2280. && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
  2281. lookup->mode |= SPI_LSB_FIRST;
  2282. if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
  2283. && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
  2284. lookup->mode |= SPI_CPOL;
  2285. if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
  2286. && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
  2287. lookup->mode |= SPI_CPHA;
  2288. }
  2289. static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
  2290. {
  2291. struct acpi_spi_lookup *lookup = data;
  2292. struct spi_controller *ctlr = lookup->ctlr;
  2293. if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
  2294. struct acpi_resource_spi_serialbus *sb;
  2295. acpi_handle parent_handle;
  2296. acpi_status status;
  2297. sb = &ares->data.spi_serial_bus;
  2298. if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
  2299. if (lookup->index != -1 && lookup->n++ != lookup->index)
  2300. return 1;
  2301. status = acpi_get_handle(NULL,
  2302. sb->resource_source.string_ptr,
  2303. &parent_handle);
  2304. if (ACPI_FAILURE(status))
  2305. return -ENODEV;
  2306. if (ctlr) {
  2307. if (!device_match_acpi_handle(ctlr->dev.parent, parent_handle))
  2308. return -ENODEV;
  2309. } else {
  2310. struct acpi_device *adev;
  2311. adev = acpi_fetch_acpi_dev(parent_handle);
  2312. if (!adev)
  2313. return -ENODEV;
  2314. ctlr = acpi_spi_find_controller_by_adev(adev);
  2315. if (!ctlr)
  2316. return -EPROBE_DEFER;
  2317. lookup->ctlr = ctlr;
  2318. }
  2319. /*
  2320. * ACPI DeviceSelection numbering is handled by the
  2321. * host controller driver in Windows and can vary
  2322. * from driver to driver. In Linux we always expect
  2323. * 0 .. max - 1 so we need to ask the driver to
  2324. * translate between the two schemes.
  2325. */
  2326. if (ctlr->fw_translate_cs) {
  2327. int cs = ctlr->fw_translate_cs(ctlr,
  2328. sb->device_selection);
  2329. if (cs < 0)
  2330. return cs;
  2331. lookup->chip_select = cs;
  2332. } else {
  2333. lookup->chip_select = sb->device_selection;
  2334. }
  2335. lookup->max_speed_hz = sb->connection_speed;
  2336. lookup->bits_per_word = sb->data_bit_length;
  2337. if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
  2338. lookup->mode |= SPI_CPHA;
  2339. if (sb->clock_polarity == ACPI_SPI_START_HIGH)
  2340. lookup->mode |= SPI_CPOL;
  2341. if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
  2342. lookup->mode |= SPI_CS_HIGH;
  2343. }
  2344. } else if (lookup->irq < 0) {
  2345. struct resource r;
  2346. if (acpi_dev_resource_interrupt(ares, 0, &r))
  2347. lookup->irq = r.start;
  2348. }
  2349. /* Always tell the ACPI core to skip this resource */
  2350. return 1;
  2351. }
  2352. /**
  2353. * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
  2354. * @ctlr: controller to which the spi device belongs
  2355. * @adev: ACPI Device for the spi device
  2356. * @index: Index of the spi resource inside the ACPI Node
  2357. *
  2358. * This should be used to allocate a new SPI device from and ACPI Device node.
  2359. * The caller is responsible for calling spi_add_device to register the SPI device.
  2360. *
  2361. * If ctlr is set to NULL, the Controller for the SPI device will be looked up
  2362. * using the resource.
  2363. * If index is set to -1, index is not used.
  2364. * Note: If index is -1, ctlr must be set.
  2365. *
  2366. * Return: a pointer to the new device, or ERR_PTR on error.
  2367. */
  2368. struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
  2369. struct acpi_device *adev,
  2370. int index)
  2371. {
  2372. acpi_handle parent_handle = NULL;
  2373. struct list_head resource_list;
  2374. struct acpi_spi_lookup lookup = {};
  2375. struct spi_device *spi;
  2376. int ret;
  2377. if (!ctlr && index == -1)
  2378. return ERR_PTR(-EINVAL);
  2379. lookup.ctlr = ctlr;
  2380. lookup.irq = -1;
  2381. lookup.index = index;
  2382. lookup.n = 0;
  2383. INIT_LIST_HEAD(&resource_list);
  2384. ret = acpi_dev_get_resources(adev, &resource_list,
  2385. acpi_spi_add_resource, &lookup);
  2386. acpi_dev_free_resource_list(&resource_list);
  2387. if (ret < 0)
  2388. /* Found SPI in _CRS but it points to another controller */
  2389. return ERR_PTR(ret);
  2390. if (!lookup.max_speed_hz &&
  2391. ACPI_SUCCESS(acpi_get_parent(adev->handle, &parent_handle)) &&
  2392. device_match_acpi_handle(lookup.ctlr->dev.parent, parent_handle)) {
  2393. /* Apple does not use _CRS but nested devices for SPI slaves */
  2394. acpi_spi_parse_apple_properties(adev, &lookup);
  2395. }
  2396. if (!lookup.max_speed_hz)
  2397. return ERR_PTR(-ENODEV);
  2398. spi = spi_alloc_device(lookup.ctlr);
  2399. if (!spi) {
  2400. dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
  2401. dev_name(&adev->dev));
  2402. return ERR_PTR(-ENOMEM);
  2403. }
  2404. spi_set_all_cs_unused(spi);
  2405. spi_set_chipselect(spi, 0, lookup.chip_select);
  2406. ACPI_COMPANION_SET(&spi->dev, adev);
  2407. spi->max_speed_hz = lookup.max_speed_hz;
  2408. spi->mode |= lookup.mode;
  2409. spi->irq = lookup.irq;
  2410. spi->bits_per_word = lookup.bits_per_word;
  2411. /*
  2412. * By default spi->chip_select[0] will hold the physical CS number,
  2413. * so set bit 0 in spi->cs_index_mask.
  2414. */
  2415. spi->cs_index_mask = BIT(0);
  2416. return spi;
  2417. }
  2418. EXPORT_SYMBOL_GPL(acpi_spi_device_alloc);
  2419. static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
  2420. struct acpi_device *adev)
  2421. {
  2422. struct spi_device *spi;
  2423. if (acpi_bus_get_status(adev) || !adev->status.present ||
  2424. acpi_device_enumerated(adev))
  2425. return AE_OK;
  2426. spi = acpi_spi_device_alloc(ctlr, adev, -1);
  2427. if (IS_ERR(spi)) {
  2428. if (PTR_ERR(spi) == -ENOMEM)
  2429. return AE_NO_MEMORY;
  2430. else
  2431. return AE_OK;
  2432. }
  2433. acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
  2434. sizeof(spi->modalias));
  2435. acpi_device_set_enumerated(adev);
  2436. adev->power.flags.ignore_parent = true;
  2437. if (spi_add_device(spi)) {
  2438. adev->power.flags.ignore_parent = false;
  2439. dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
  2440. dev_name(&adev->dev));
  2441. spi_dev_put(spi);
  2442. }
  2443. return AE_OK;
  2444. }
  2445. static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
  2446. void *data, void **return_value)
  2447. {
  2448. struct acpi_device *adev = acpi_fetch_acpi_dev(handle);
  2449. struct spi_controller *ctlr = data;
  2450. if (!adev)
  2451. return AE_OK;
  2452. return acpi_register_spi_device(ctlr, adev);
  2453. }
  2454. #define SPI_ACPI_ENUMERATE_MAX_DEPTH 32
  2455. static void acpi_register_spi_devices(struct spi_controller *ctlr)
  2456. {
  2457. acpi_status status;
  2458. acpi_handle handle;
  2459. handle = ACPI_HANDLE(ctlr->dev.parent);
  2460. if (!handle)
  2461. return;
  2462. status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
  2463. SPI_ACPI_ENUMERATE_MAX_DEPTH,
  2464. acpi_spi_add_device, NULL, ctlr, NULL);
  2465. if (ACPI_FAILURE(status))
  2466. dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
  2467. }
  2468. #else
  2469. static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
  2470. #endif /* CONFIG_ACPI */
  2471. static void spi_controller_release(struct device *dev)
  2472. {
  2473. struct spi_controller *ctlr;
  2474. ctlr = container_of(dev, struct spi_controller, dev);
  2475. kfree(ctlr);
  2476. }
  2477. static struct class spi_master_class = {
  2478. .name = "spi_master",
  2479. .dev_release = spi_controller_release,
  2480. .dev_groups = spi_master_groups,
  2481. };
  2482. #ifdef CONFIG_SPI_SLAVE
  2483. /**
  2484. * spi_target_abort - abort the ongoing transfer request on an SPI slave
  2485. * controller
  2486. * @spi: device used for the current transfer
  2487. */
  2488. int spi_target_abort(struct spi_device *spi)
  2489. {
  2490. struct spi_controller *ctlr = spi->controller;
  2491. if (spi_controller_is_target(ctlr) && ctlr->target_abort)
  2492. return ctlr->target_abort(ctlr);
  2493. return -ENOTSUPP;
  2494. }
  2495. EXPORT_SYMBOL_GPL(spi_target_abort);
  2496. static ssize_t slave_show(struct device *dev, struct device_attribute *attr,
  2497. char *buf)
  2498. {
  2499. struct spi_controller *ctlr = container_of(dev, struct spi_controller,
  2500. dev);
  2501. struct device *child;
  2502. child = device_find_any_child(&ctlr->dev);
  2503. return sysfs_emit(buf, "%s\n", child ? to_spi_device(child)->modalias : NULL);
  2504. }
  2505. static ssize_t slave_store(struct device *dev, struct device_attribute *attr,
  2506. const char *buf, size_t count)
  2507. {
  2508. struct spi_controller *ctlr = container_of(dev, struct spi_controller,
  2509. dev);
  2510. struct spi_device *spi;
  2511. struct device *child;
  2512. char name[32];
  2513. int rc;
  2514. rc = sscanf(buf, "%31s", name);
  2515. if (rc != 1 || !name[0])
  2516. return -EINVAL;
  2517. child = device_find_any_child(&ctlr->dev);
  2518. if (child) {
  2519. /* Remove registered slave */
  2520. device_unregister(child);
  2521. put_device(child);
  2522. }
  2523. if (strcmp(name, "(null)")) {
  2524. /* Register new slave */
  2525. spi = spi_alloc_device(ctlr);
  2526. if (!spi)
  2527. return -ENOMEM;
  2528. strscpy(spi->modalias, name, sizeof(spi->modalias));
  2529. rc = spi_add_device(spi);
  2530. if (rc) {
  2531. spi_dev_put(spi);
  2532. return rc;
  2533. }
  2534. }
  2535. return count;
  2536. }
  2537. static DEVICE_ATTR_RW(slave);
  2538. static struct attribute *spi_slave_attrs[] = {
  2539. &dev_attr_slave.attr,
  2540. NULL,
  2541. };
  2542. static const struct attribute_group spi_slave_group = {
  2543. .attrs = spi_slave_attrs,
  2544. };
  2545. static const struct attribute_group *spi_slave_groups[] = {
  2546. &spi_controller_statistics_group,
  2547. &spi_slave_group,
  2548. NULL,
  2549. };
  2550. static struct class spi_slave_class = {
  2551. .name = "spi_slave",
  2552. .dev_release = spi_controller_release,
  2553. .dev_groups = spi_slave_groups,
  2554. };
  2555. #else
  2556. extern struct class spi_slave_class; /* dummy */
  2557. #endif
  2558. /**
  2559. * __spi_alloc_controller - allocate an SPI master or slave controller
  2560. * @dev: the controller, possibly using the platform_bus
  2561. * @size: how much zeroed driver-private data to allocate; the pointer to this
  2562. * memory is in the driver_data field of the returned device, accessible
  2563. * with spi_controller_get_devdata(); the memory is cacheline aligned;
  2564. * drivers granting DMA access to portions of their private data need to
  2565. * round up @size using ALIGN(size, dma_get_cache_alignment()).
  2566. * @slave: flag indicating whether to allocate an SPI master (false) or SPI
  2567. * slave (true) controller
  2568. * Context: can sleep
  2569. *
  2570. * This call is used only by SPI controller drivers, which are the
  2571. * only ones directly touching chip registers. It's how they allocate
  2572. * an spi_controller structure, prior to calling spi_register_controller().
  2573. *
  2574. * This must be called from context that can sleep.
  2575. *
  2576. * The caller is responsible for assigning the bus number and initializing the
  2577. * controller's methods before calling spi_register_controller(); and (after
  2578. * errors adding the device) calling spi_controller_put() to prevent a memory
  2579. * leak.
  2580. *
  2581. * Return: the SPI controller structure on success, else NULL.
  2582. */
  2583. struct spi_controller *__spi_alloc_controller(struct device *dev,
  2584. unsigned int size, bool slave)
  2585. {
  2586. struct spi_controller *ctlr;
  2587. size_t ctlr_size = ALIGN(sizeof(*ctlr), dma_get_cache_alignment());
  2588. if (!dev)
  2589. return NULL;
  2590. ctlr = kzalloc(size + ctlr_size, GFP_KERNEL);
  2591. if (!ctlr)
  2592. return NULL;
  2593. device_initialize(&ctlr->dev);
  2594. INIT_LIST_HEAD(&ctlr->queue);
  2595. spin_lock_init(&ctlr->queue_lock);
  2596. spin_lock_init(&ctlr->bus_lock_spinlock);
  2597. mutex_init(&ctlr->bus_lock_mutex);
  2598. mutex_init(&ctlr->io_mutex);
  2599. mutex_init(&ctlr->add_lock);
  2600. ctlr->bus_num = -1;
  2601. ctlr->num_chipselect = 1;
  2602. ctlr->slave = slave;
  2603. if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
  2604. ctlr->dev.class = &spi_slave_class;
  2605. else
  2606. ctlr->dev.class = &spi_master_class;
  2607. ctlr->dev.parent = dev;
  2608. pm_suspend_ignore_children(&ctlr->dev, true);
  2609. spi_controller_set_devdata(ctlr, (void *)ctlr + ctlr_size);
  2610. return ctlr;
  2611. }
  2612. EXPORT_SYMBOL_GPL(__spi_alloc_controller);
  2613. static void devm_spi_release_controller(struct device *dev, void *ctlr)
  2614. {
  2615. spi_controller_put(*(struct spi_controller **)ctlr);
  2616. }
  2617. /**
  2618. * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
  2619. * @dev: physical device of SPI controller
  2620. * @size: how much zeroed driver-private data to allocate
  2621. * @slave: whether to allocate an SPI master (false) or SPI slave (true)
  2622. * Context: can sleep
  2623. *
  2624. * Allocate an SPI controller and automatically release a reference on it
  2625. * when @dev is unbound from its driver. Drivers are thus relieved from
  2626. * having to call spi_controller_put().
  2627. *
  2628. * The arguments to this function are identical to __spi_alloc_controller().
  2629. *
  2630. * Return: the SPI controller structure on success, else NULL.
  2631. */
  2632. struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
  2633. unsigned int size,
  2634. bool slave)
  2635. {
  2636. struct spi_controller **ptr, *ctlr;
  2637. ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
  2638. GFP_KERNEL);
  2639. if (!ptr)
  2640. return NULL;
  2641. ctlr = __spi_alloc_controller(dev, size, slave);
  2642. if (ctlr) {
  2643. ctlr->devm_allocated = true;
  2644. *ptr = ctlr;
  2645. devres_add(dev, ptr);
  2646. } else {
  2647. devres_free(ptr);
  2648. }
  2649. return ctlr;
  2650. }
  2651. EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
  2652. /**
  2653. * spi_get_gpio_descs() - grab chip select GPIOs for the master
  2654. * @ctlr: The SPI master to grab GPIO descriptors for
  2655. */
  2656. static int spi_get_gpio_descs(struct spi_controller *ctlr)
  2657. {
  2658. int nb, i;
  2659. struct gpio_desc **cs;
  2660. struct device *dev = &ctlr->dev;
  2661. unsigned long native_cs_mask = 0;
  2662. unsigned int num_cs_gpios = 0;
  2663. nb = gpiod_count(dev, "cs");
  2664. if (nb < 0) {
  2665. /* No GPIOs at all is fine, else return the error */
  2666. if (nb == -ENOENT)
  2667. return 0;
  2668. return nb;
  2669. }
  2670. ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
  2671. cs = devm_kcalloc(dev, ctlr->num_chipselect, sizeof(*cs),
  2672. GFP_KERNEL);
  2673. if (!cs)
  2674. return -ENOMEM;
  2675. ctlr->cs_gpiods = cs;
  2676. for (i = 0; i < nb; i++) {
  2677. /*
  2678. * Most chipselects are active low, the inverted
  2679. * semantics are handled by special quirks in gpiolib,
  2680. * so initializing them GPIOD_OUT_LOW here means
  2681. * "unasserted", in most cases this will drive the physical
  2682. * line high.
  2683. */
  2684. cs[i] = devm_gpiod_get_index_optional(dev, "cs", i,
  2685. GPIOD_OUT_LOW);
  2686. if (IS_ERR(cs[i]))
  2687. return PTR_ERR(cs[i]);
  2688. if (cs[i]) {
  2689. /*
  2690. * If we find a CS GPIO, name it after the device and
  2691. * chip select line.
  2692. */
  2693. char *gpioname;
  2694. gpioname = devm_kasprintf(dev, GFP_KERNEL, "%s CS%d",
  2695. dev_name(dev), i);
  2696. if (!gpioname)
  2697. return -ENOMEM;
  2698. gpiod_set_consumer_name(cs[i], gpioname);
  2699. num_cs_gpios++;
  2700. continue;
  2701. }
  2702. if (ctlr->max_native_cs && i >= ctlr->max_native_cs) {
  2703. dev_err(dev, "Invalid native chip select %d\n", i);
  2704. return -EINVAL;
  2705. }
  2706. native_cs_mask |= BIT(i);
  2707. }
  2708. ctlr->unused_native_cs = ffs(~native_cs_mask) - 1;
  2709. if ((ctlr->flags & SPI_CONTROLLER_GPIO_SS) && num_cs_gpios &&
  2710. ctlr->max_native_cs && ctlr->unused_native_cs >= ctlr->max_native_cs) {
  2711. dev_err(dev, "No unused native chip select available\n");
  2712. return -EINVAL;
  2713. }
  2714. return 0;
  2715. }
  2716. static int spi_controller_check_ops(struct spi_controller *ctlr)
  2717. {
  2718. /*
  2719. * The controller may implement only the high-level SPI-memory like
  2720. * operations if it does not support regular SPI transfers, and this is
  2721. * valid use case.
  2722. * If ->mem_ops or ->mem_ops->exec_op is NULL, we request that at least
  2723. * one of the ->transfer_xxx() method be implemented.
  2724. */
  2725. if (!ctlr->mem_ops || !ctlr->mem_ops->exec_op) {
  2726. if (!ctlr->transfer && !ctlr->transfer_one &&
  2727. !ctlr->transfer_one_message) {
  2728. return -EINVAL;
  2729. }
  2730. }
  2731. return 0;
  2732. }
  2733. /* Allocate dynamic bus number using Linux idr */
  2734. static int spi_controller_id_alloc(struct spi_controller *ctlr, int start, int end)
  2735. {
  2736. int id;
  2737. mutex_lock(&board_lock);
  2738. id = idr_alloc(&spi_master_idr, ctlr, start, end, GFP_KERNEL);
  2739. mutex_unlock(&board_lock);
  2740. if (WARN(id < 0, "couldn't get idr"))
  2741. return id == -ENOSPC ? -EBUSY : id;
  2742. ctlr->bus_num = id;
  2743. return 0;
  2744. }
  2745. /**
  2746. * spi_register_controller - register SPI master or slave controller
  2747. * @ctlr: initialized master, originally from spi_alloc_master() or
  2748. * spi_alloc_slave()
  2749. * Context: can sleep
  2750. *
  2751. * SPI controllers connect to their drivers using some non-SPI bus,
  2752. * such as the platform bus. The final stage of probe() in that code
  2753. * includes calling spi_register_controller() to hook up to this SPI bus glue.
  2754. *
  2755. * SPI controllers use board specific (often SOC specific) bus numbers,
  2756. * and board-specific addressing for SPI devices combines those numbers
  2757. * with chip select numbers. Since SPI does not directly support dynamic
  2758. * device identification, boards need configuration tables telling which
  2759. * chip is at which address.
  2760. *
  2761. * This must be called from context that can sleep. It returns zero on
  2762. * success, else a negative error code (dropping the controller's refcount).
  2763. * After a successful return, the caller is responsible for calling
  2764. * spi_unregister_controller().
  2765. *
  2766. * Return: zero on success, else a negative error code.
  2767. */
  2768. int spi_register_controller(struct spi_controller *ctlr)
  2769. {
  2770. struct device *dev = ctlr->dev.parent;
  2771. struct boardinfo *bi;
  2772. int first_dynamic;
  2773. int status;
  2774. int idx;
  2775. if (!dev)
  2776. return -ENODEV;
  2777. /*
  2778. * Make sure all necessary hooks are implemented before registering
  2779. * the SPI controller.
  2780. */
  2781. status = spi_controller_check_ops(ctlr);
  2782. if (status)
  2783. return status;
  2784. if (ctlr->bus_num < 0)
  2785. ctlr->bus_num = of_alias_get_id(ctlr->dev.of_node, "spi");
  2786. if (ctlr->bus_num >= 0) {
  2787. /* Devices with a fixed bus num must check-in with the num */
  2788. status = spi_controller_id_alloc(ctlr, ctlr->bus_num, ctlr->bus_num + 1);
  2789. if (status)
  2790. return status;
  2791. }
  2792. if (ctlr->bus_num < 0) {
  2793. first_dynamic = of_alias_get_highest_id("spi");
  2794. if (first_dynamic < 0)
  2795. first_dynamic = 0;
  2796. else
  2797. first_dynamic++;
  2798. status = spi_controller_id_alloc(ctlr, first_dynamic, 0);
  2799. if (status)
  2800. return status;
  2801. }
  2802. ctlr->bus_lock_flag = 0;
  2803. init_completion(&ctlr->xfer_completion);
  2804. init_completion(&ctlr->cur_msg_completion);
  2805. if (!ctlr->max_dma_len)
  2806. ctlr->max_dma_len = INT_MAX;
  2807. /*
  2808. * Register the device, then userspace will see it.
  2809. * Registration fails if the bus ID is in use.
  2810. */
  2811. dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
  2812. if (!spi_controller_is_target(ctlr) && ctlr->use_gpio_descriptors) {
  2813. status = spi_get_gpio_descs(ctlr);
  2814. if (status)
  2815. goto free_bus_id;
  2816. /*
  2817. * A controller using GPIO descriptors always
  2818. * supports SPI_CS_HIGH if need be.
  2819. */
  2820. ctlr->mode_bits |= SPI_CS_HIGH;
  2821. }
  2822. /*
  2823. * Even if it's just one always-selected device, there must
  2824. * be at least one chipselect.
  2825. */
  2826. if (!ctlr->num_chipselect) {
  2827. status = -EINVAL;
  2828. goto free_bus_id;
  2829. }
  2830. /* Setting last_cs to SPI_INVALID_CS means no chip selected */
  2831. for (idx = 0; idx < SPI_CS_CNT_MAX; idx++)
  2832. ctlr->last_cs[idx] = SPI_INVALID_CS;
  2833. status = device_add(&ctlr->dev);
  2834. if (status < 0)
  2835. goto free_bus_id;
  2836. dev_dbg(dev, "registered %s %s\n",
  2837. spi_controller_is_target(ctlr) ? "target" : "host",
  2838. dev_name(&ctlr->dev));
  2839. /*
  2840. * If we're using a queued driver, start the queue. Note that we don't
  2841. * need the queueing logic if the driver is only supporting high-level
  2842. * memory operations.
  2843. */
  2844. if (ctlr->transfer) {
  2845. dev_info(dev, "controller is unqueued, this is deprecated\n");
  2846. } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
  2847. status = spi_controller_initialize_queue(ctlr);
  2848. if (status) {
  2849. device_del(&ctlr->dev);
  2850. goto free_bus_id;
  2851. }
  2852. }
  2853. /* Add statistics */
  2854. ctlr->pcpu_statistics = spi_alloc_pcpu_stats(dev);
  2855. if (!ctlr->pcpu_statistics) {
  2856. dev_err(dev, "Error allocating per-cpu statistics\n");
  2857. status = -ENOMEM;
  2858. goto destroy_queue;
  2859. }
  2860. mutex_lock(&board_lock);
  2861. list_add_tail(&ctlr->list, &spi_controller_list);
  2862. list_for_each_entry(bi, &board_list, list)
  2863. spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
  2864. mutex_unlock(&board_lock);
  2865. /* Register devices from the device tree and ACPI */
  2866. of_register_spi_devices(ctlr);
  2867. acpi_register_spi_devices(ctlr);
  2868. return status;
  2869. destroy_queue:
  2870. spi_destroy_queue(ctlr);
  2871. free_bus_id:
  2872. mutex_lock(&board_lock);
  2873. idr_remove(&spi_master_idr, ctlr->bus_num);
  2874. mutex_unlock(&board_lock);
  2875. return status;
  2876. }
  2877. EXPORT_SYMBOL_GPL(spi_register_controller);
  2878. static void devm_spi_unregister(struct device *dev, void *res)
  2879. {
  2880. spi_unregister_controller(*(struct spi_controller **)res);
  2881. }
  2882. /**
  2883. * devm_spi_register_controller - register managed SPI master or slave
  2884. * controller
  2885. * @dev: device managing SPI controller
  2886. * @ctlr: initialized controller, originally from spi_alloc_master() or
  2887. * spi_alloc_slave()
  2888. * Context: can sleep
  2889. *
  2890. * Register a SPI device as with spi_register_controller() which will
  2891. * automatically be unregistered and freed.
  2892. *
  2893. * Return: zero on success, else a negative error code.
  2894. */
  2895. int devm_spi_register_controller(struct device *dev,
  2896. struct spi_controller *ctlr)
  2897. {
  2898. struct spi_controller **ptr;
  2899. int ret;
  2900. ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
  2901. if (!ptr)
  2902. return -ENOMEM;
  2903. ret = spi_register_controller(ctlr);
  2904. if (!ret) {
  2905. *ptr = ctlr;
  2906. devres_add(dev, ptr);
  2907. } else {
  2908. devres_free(ptr);
  2909. }
  2910. return ret;
  2911. }
  2912. EXPORT_SYMBOL_GPL(devm_spi_register_controller);
  2913. static int __unregister(struct device *dev, void *null)
  2914. {
  2915. spi_unregister_device(to_spi_device(dev));
  2916. return 0;
  2917. }
  2918. /**
  2919. * spi_unregister_controller - unregister SPI master or slave controller
  2920. * @ctlr: the controller being unregistered
  2921. * Context: can sleep
  2922. *
  2923. * This call is used only by SPI controller drivers, which are the
  2924. * only ones directly touching chip registers.
  2925. *
  2926. * This must be called from context that can sleep.
  2927. *
  2928. * Note that this function also drops a reference to the controller.
  2929. */
  2930. void spi_unregister_controller(struct spi_controller *ctlr)
  2931. {
  2932. struct spi_controller *found;
  2933. int id = ctlr->bus_num;
  2934. /* Prevent addition of new devices, unregister existing ones */
  2935. if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
  2936. mutex_lock(&ctlr->add_lock);
  2937. device_for_each_child(&ctlr->dev, NULL, __unregister);
  2938. /* First make sure that this controller was ever added */
  2939. mutex_lock(&board_lock);
  2940. found = idr_find(&spi_master_idr, id);
  2941. mutex_unlock(&board_lock);
  2942. if (ctlr->queued) {
  2943. if (spi_destroy_queue(ctlr))
  2944. dev_err(&ctlr->dev, "queue remove failed\n");
  2945. }
  2946. mutex_lock(&board_lock);
  2947. list_del(&ctlr->list);
  2948. mutex_unlock(&board_lock);
  2949. device_del(&ctlr->dev);
  2950. /* Free bus id */
  2951. mutex_lock(&board_lock);
  2952. if (found == ctlr)
  2953. idr_remove(&spi_master_idr, id);
  2954. mutex_unlock(&board_lock);
  2955. if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
  2956. mutex_unlock(&ctlr->add_lock);
  2957. /*
  2958. * Release the last reference on the controller if its driver
  2959. * has not yet been converted to devm_spi_alloc_master/slave().
  2960. */
  2961. if (!ctlr->devm_allocated)
  2962. put_device(&ctlr->dev);
  2963. }
  2964. EXPORT_SYMBOL_GPL(spi_unregister_controller);
  2965. static inline int __spi_check_suspended(const struct spi_controller *ctlr)
  2966. {
  2967. return ctlr->flags & SPI_CONTROLLER_SUSPENDED ? -ESHUTDOWN : 0;
  2968. }
  2969. static inline void __spi_mark_suspended(struct spi_controller *ctlr)
  2970. {
  2971. mutex_lock(&ctlr->bus_lock_mutex);
  2972. ctlr->flags |= SPI_CONTROLLER_SUSPENDED;
  2973. mutex_unlock(&ctlr->bus_lock_mutex);
  2974. }
  2975. static inline void __spi_mark_resumed(struct spi_controller *ctlr)
  2976. {
  2977. mutex_lock(&ctlr->bus_lock_mutex);
  2978. ctlr->flags &= ~SPI_CONTROLLER_SUSPENDED;
  2979. mutex_unlock(&ctlr->bus_lock_mutex);
  2980. }
  2981. int spi_controller_suspend(struct spi_controller *ctlr)
  2982. {
  2983. int ret = 0;
  2984. /* Basically no-ops for non-queued controllers */
  2985. if (ctlr->queued) {
  2986. ret = spi_stop_queue(ctlr);
  2987. if (ret)
  2988. dev_err(&ctlr->dev, "queue stop failed\n");
  2989. }
  2990. __spi_mark_suspended(ctlr);
  2991. return ret;
  2992. }
  2993. EXPORT_SYMBOL_GPL(spi_controller_suspend);
  2994. int spi_controller_resume(struct spi_controller *ctlr)
  2995. {
  2996. int ret = 0;
  2997. __spi_mark_resumed(ctlr);
  2998. if (ctlr->queued) {
  2999. ret = spi_start_queue(ctlr);
  3000. if (ret)
  3001. dev_err(&ctlr->dev, "queue restart failed\n");
  3002. }
  3003. return ret;
  3004. }
  3005. EXPORT_SYMBOL_GPL(spi_controller_resume);
  3006. /*-------------------------------------------------------------------------*/
  3007. /* Core methods for spi_message alterations */
  3008. static void __spi_replace_transfers_release(struct spi_controller *ctlr,
  3009. struct spi_message *msg,
  3010. void *res)
  3011. {
  3012. struct spi_replaced_transfers *rxfer = res;
  3013. size_t i;
  3014. /* Call extra callback if requested */
  3015. if (rxfer->release)
  3016. rxfer->release(ctlr, msg, res);
  3017. /* Insert replaced transfers back into the message */
  3018. list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
  3019. /* Remove the formerly inserted entries */
  3020. for (i = 0; i < rxfer->inserted; i++)
  3021. list_del(&rxfer->inserted_transfers[i].transfer_list);
  3022. }
  3023. /**
  3024. * spi_replace_transfers - replace transfers with several transfers
  3025. * and register change with spi_message.resources
  3026. * @msg: the spi_message we work upon
  3027. * @xfer_first: the first spi_transfer we want to replace
  3028. * @remove: number of transfers to remove
  3029. * @insert: the number of transfers we want to insert instead
  3030. * @release: extra release code necessary in some circumstances
  3031. * @extradatasize: extra data to allocate (with alignment guarantees
  3032. * of struct @spi_transfer)
  3033. * @gfp: gfp flags
  3034. *
  3035. * Returns: pointer to @spi_replaced_transfers,
  3036. * PTR_ERR(...) in case of errors.
  3037. */
  3038. static struct spi_replaced_transfers *spi_replace_transfers(
  3039. struct spi_message *msg,
  3040. struct spi_transfer *xfer_first,
  3041. size_t remove,
  3042. size_t insert,
  3043. spi_replaced_release_t release,
  3044. size_t extradatasize,
  3045. gfp_t gfp)
  3046. {
  3047. struct spi_replaced_transfers *rxfer;
  3048. struct spi_transfer *xfer;
  3049. size_t i;
  3050. /* Allocate the structure using spi_res */
  3051. rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
  3052. struct_size(rxfer, inserted_transfers, insert)
  3053. + extradatasize,
  3054. gfp);
  3055. if (!rxfer)
  3056. return ERR_PTR(-ENOMEM);
  3057. /* The release code to invoke before running the generic release */
  3058. rxfer->release = release;
  3059. /* Assign extradata */
  3060. if (extradatasize)
  3061. rxfer->extradata =
  3062. &rxfer->inserted_transfers[insert];
  3063. /* Init the replaced_transfers list */
  3064. INIT_LIST_HEAD(&rxfer->replaced_transfers);
  3065. /*
  3066. * Assign the list_entry after which we should reinsert
  3067. * the @replaced_transfers - it may be spi_message.messages!
  3068. */
  3069. rxfer->replaced_after = xfer_first->transfer_list.prev;
  3070. /* Remove the requested number of transfers */
  3071. for (i = 0; i < remove; i++) {
  3072. /*
  3073. * If the entry after replaced_after it is msg->transfers
  3074. * then we have been requested to remove more transfers
  3075. * than are in the list.
  3076. */
  3077. if (rxfer->replaced_after->next == &msg->transfers) {
  3078. dev_err(&msg->spi->dev,
  3079. "requested to remove more spi_transfers than are available\n");
  3080. /* Insert replaced transfers back into the message */
  3081. list_splice(&rxfer->replaced_transfers,
  3082. rxfer->replaced_after);
  3083. /* Free the spi_replace_transfer structure... */
  3084. spi_res_free(rxfer);
  3085. /* ...and return with an error */
  3086. return ERR_PTR(-EINVAL);
  3087. }
  3088. /*
  3089. * Remove the entry after replaced_after from list of
  3090. * transfers and add it to list of replaced_transfers.
  3091. */
  3092. list_move_tail(rxfer->replaced_after->next,
  3093. &rxfer->replaced_transfers);
  3094. }
  3095. /*
  3096. * Create copy of the given xfer with identical settings
  3097. * based on the first transfer to get removed.
  3098. */
  3099. for (i = 0; i < insert; i++) {
  3100. /* We need to run in reverse order */
  3101. xfer = &rxfer->inserted_transfers[insert - 1 - i];
  3102. /* Copy all spi_transfer data */
  3103. memcpy(xfer, xfer_first, sizeof(*xfer));
  3104. /* Add to list */
  3105. list_add(&xfer->transfer_list, rxfer->replaced_after);
  3106. /* Clear cs_change and delay for all but the last */
  3107. if (i) {
  3108. xfer->cs_change = false;
  3109. xfer->delay.value = 0;
  3110. }
  3111. }
  3112. /* Set up inserted... */
  3113. rxfer->inserted = insert;
  3114. /* ...and register it with spi_res/spi_message */
  3115. spi_res_add(msg, rxfer);
  3116. return rxfer;
  3117. }
  3118. static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
  3119. struct spi_message *msg,
  3120. struct spi_transfer **xferp,
  3121. size_t maxsize)
  3122. {
  3123. struct spi_transfer *xfer = *xferp, *xfers;
  3124. struct spi_replaced_transfers *srt;
  3125. size_t offset;
  3126. size_t count, i;
  3127. /* Calculate how many we have to replace */
  3128. count = DIV_ROUND_UP(xfer->len, maxsize);
  3129. /* Create replacement */
  3130. srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, GFP_KERNEL);
  3131. if (IS_ERR(srt))
  3132. return PTR_ERR(srt);
  3133. xfers = srt->inserted_transfers;
  3134. /*
  3135. * Now handle each of those newly inserted spi_transfers.
  3136. * Note that the replacements spi_transfers all are preset
  3137. * to the same values as *xferp, so tx_buf, rx_buf and len
  3138. * are all identical (as well as most others)
  3139. * so we just have to fix up len and the pointers.
  3140. */
  3141. /*
  3142. * The first transfer just needs the length modified, so we
  3143. * run it outside the loop.
  3144. */
  3145. xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
  3146. /* All the others need rx_buf/tx_buf also set */
  3147. for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
  3148. /* Update rx_buf, tx_buf and DMA */
  3149. if (xfers[i].rx_buf)
  3150. xfers[i].rx_buf += offset;
  3151. if (xfers[i].tx_buf)
  3152. xfers[i].tx_buf += offset;
  3153. /* Update length */
  3154. xfers[i].len = min(maxsize, xfers[i].len - offset);
  3155. }
  3156. /*
  3157. * We set up xferp to the last entry we have inserted,
  3158. * so that we skip those already split transfers.
  3159. */
  3160. *xferp = &xfers[count - 1];
  3161. /* Increment statistics counters */
  3162. SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics,
  3163. transfers_split_maxsize);
  3164. SPI_STATISTICS_INCREMENT_FIELD(msg->spi->pcpu_statistics,
  3165. transfers_split_maxsize);
  3166. return 0;
  3167. }
  3168. /**
  3169. * spi_split_transfers_maxsize - split spi transfers into multiple transfers
  3170. * when an individual transfer exceeds a
  3171. * certain size
  3172. * @ctlr: the @spi_controller for this transfer
  3173. * @msg: the @spi_message to transform
  3174. * @maxsize: the maximum when to apply this
  3175. *
  3176. * This function allocates resources that are automatically freed during the
  3177. * spi message unoptimize phase so this function should only be called from
  3178. * optimize_message callbacks.
  3179. *
  3180. * Return: status of transformation
  3181. */
  3182. int spi_split_transfers_maxsize(struct spi_controller *ctlr,
  3183. struct spi_message *msg,
  3184. size_t maxsize)
  3185. {
  3186. struct spi_transfer *xfer;
  3187. int ret;
  3188. /*
  3189. * Iterate over the transfer_list,
  3190. * but note that xfer is advanced to the last transfer inserted
  3191. * to avoid checking sizes again unnecessarily (also xfer does
  3192. * potentially belong to a different list by the time the
  3193. * replacement has happened).
  3194. */
  3195. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  3196. if (xfer->len > maxsize) {
  3197. ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
  3198. maxsize);
  3199. if (ret)
  3200. return ret;
  3201. }
  3202. }
  3203. return 0;
  3204. }
  3205. EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
  3206. /**
  3207. * spi_split_transfers_maxwords - split SPI transfers into multiple transfers
  3208. * when an individual transfer exceeds a
  3209. * certain number of SPI words
  3210. * @ctlr: the @spi_controller for this transfer
  3211. * @msg: the @spi_message to transform
  3212. * @maxwords: the number of words to limit each transfer to
  3213. *
  3214. * This function allocates resources that are automatically freed during the
  3215. * spi message unoptimize phase so this function should only be called from
  3216. * optimize_message callbacks.
  3217. *
  3218. * Return: status of transformation
  3219. */
  3220. int spi_split_transfers_maxwords(struct spi_controller *ctlr,
  3221. struct spi_message *msg,
  3222. size_t maxwords)
  3223. {
  3224. struct spi_transfer *xfer;
  3225. /*
  3226. * Iterate over the transfer_list,
  3227. * but note that xfer is advanced to the last transfer inserted
  3228. * to avoid checking sizes again unnecessarily (also xfer does
  3229. * potentially belong to a different list by the time the
  3230. * replacement has happened).
  3231. */
  3232. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  3233. size_t maxsize;
  3234. int ret;
  3235. maxsize = maxwords * roundup_pow_of_two(BITS_TO_BYTES(xfer->bits_per_word));
  3236. if (xfer->len > maxsize) {
  3237. ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
  3238. maxsize);
  3239. if (ret)
  3240. return ret;
  3241. }
  3242. }
  3243. return 0;
  3244. }
  3245. EXPORT_SYMBOL_GPL(spi_split_transfers_maxwords);
  3246. /*-------------------------------------------------------------------------*/
  3247. /*
  3248. * Core methods for SPI controller protocol drivers. Some of the
  3249. * other core methods are currently defined as inline functions.
  3250. */
  3251. static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
  3252. u8 bits_per_word)
  3253. {
  3254. if (ctlr->bits_per_word_mask) {
  3255. /* Only 32 bits fit in the mask */
  3256. if (bits_per_word > 32)
  3257. return -EINVAL;
  3258. if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
  3259. return -EINVAL;
  3260. }
  3261. return 0;
  3262. }
  3263. /**
  3264. * spi_set_cs_timing - configure CS setup, hold, and inactive delays
  3265. * @spi: the device that requires specific CS timing configuration
  3266. *
  3267. * Return: zero on success, else a negative error code.
  3268. */
  3269. static int spi_set_cs_timing(struct spi_device *spi)
  3270. {
  3271. struct device *parent = spi->controller->dev.parent;
  3272. int status = 0;
  3273. if (spi->controller->set_cs_timing && !spi_get_csgpiod(spi, 0)) {
  3274. if (spi->controller->auto_runtime_pm) {
  3275. status = pm_runtime_get_sync(parent);
  3276. if (status < 0) {
  3277. pm_runtime_put_noidle(parent);
  3278. dev_err(&spi->controller->dev, "Failed to power device: %d\n",
  3279. status);
  3280. return status;
  3281. }
  3282. status = spi->controller->set_cs_timing(spi);
  3283. pm_runtime_mark_last_busy(parent);
  3284. pm_runtime_put_autosuspend(parent);
  3285. } else {
  3286. status = spi->controller->set_cs_timing(spi);
  3287. }
  3288. }
  3289. return status;
  3290. }
  3291. /**
  3292. * spi_setup - setup SPI mode and clock rate
  3293. * @spi: the device whose settings are being modified
  3294. * Context: can sleep, and no requests are queued to the device
  3295. *
  3296. * SPI protocol drivers may need to update the transfer mode if the
  3297. * device doesn't work with its default. They may likewise need
  3298. * to update clock rates or word sizes from initial values. This function
  3299. * changes those settings, and must be called from a context that can sleep.
  3300. * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
  3301. * effect the next time the device is selected and data is transferred to
  3302. * or from it. When this function returns, the SPI device is deselected.
  3303. *
  3304. * Note that this call will fail if the protocol driver specifies an option
  3305. * that the underlying controller or its driver does not support. For
  3306. * example, not all hardware supports wire transfers using nine bit words,
  3307. * LSB-first wire encoding, or active-high chipselects.
  3308. *
  3309. * Return: zero on success, else a negative error code.
  3310. */
  3311. int spi_setup(struct spi_device *spi)
  3312. {
  3313. unsigned bad_bits, ugly_bits;
  3314. int status;
  3315. /*
  3316. * Check mode to prevent that any two of DUAL, QUAD and NO_MOSI/MISO
  3317. * are set at the same time.
  3318. */
  3319. if ((hweight_long(spi->mode &
  3320. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_NO_TX)) > 1) ||
  3321. (hweight_long(spi->mode &
  3322. (SPI_RX_DUAL | SPI_RX_QUAD | SPI_NO_RX)) > 1)) {
  3323. dev_err(&spi->dev,
  3324. "setup: can not select any two of dual, quad and no-rx/tx at the same time\n");
  3325. return -EINVAL;
  3326. }
  3327. /* If it is SPI_3WIRE mode, DUAL and QUAD should be forbidden */
  3328. if ((spi->mode & SPI_3WIRE) && (spi->mode &
  3329. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
  3330. SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
  3331. return -EINVAL;
  3332. /* Check against conflicting MOSI idle configuration */
  3333. if ((spi->mode & SPI_MOSI_IDLE_LOW) && (spi->mode & SPI_MOSI_IDLE_HIGH)) {
  3334. dev_err(&spi->dev,
  3335. "setup: MOSI configured to idle low and high at the same time.\n");
  3336. return -EINVAL;
  3337. }
  3338. /*
  3339. * Help drivers fail *cleanly* when they need options
  3340. * that aren't supported with their current controller.
  3341. * SPI_CS_WORD has a fallback software implementation,
  3342. * so it is ignored here.
  3343. */
  3344. bad_bits = spi->mode & ~(spi->controller->mode_bits | SPI_CS_WORD |
  3345. SPI_NO_TX | SPI_NO_RX);
  3346. ugly_bits = bad_bits &
  3347. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL |
  3348. SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL);
  3349. if (ugly_bits) {
  3350. dev_warn(&spi->dev,
  3351. "setup: ignoring unsupported mode bits %x\n",
  3352. ugly_bits);
  3353. spi->mode &= ~ugly_bits;
  3354. bad_bits &= ~ugly_bits;
  3355. }
  3356. if (bad_bits) {
  3357. dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
  3358. bad_bits);
  3359. return -EINVAL;
  3360. }
  3361. if (!spi->bits_per_word) {
  3362. spi->bits_per_word = 8;
  3363. } else {
  3364. /*
  3365. * Some controllers may not support the default 8 bits-per-word
  3366. * so only perform the check when this is explicitly provided.
  3367. */
  3368. status = __spi_validate_bits_per_word(spi->controller,
  3369. spi->bits_per_word);
  3370. if (status)
  3371. return status;
  3372. }
  3373. if (spi->controller->max_speed_hz &&
  3374. (!spi->max_speed_hz ||
  3375. spi->max_speed_hz > spi->controller->max_speed_hz))
  3376. spi->max_speed_hz = spi->controller->max_speed_hz;
  3377. mutex_lock(&spi->controller->io_mutex);
  3378. if (spi->controller->setup) {
  3379. status = spi->controller->setup(spi);
  3380. if (status) {
  3381. mutex_unlock(&spi->controller->io_mutex);
  3382. dev_err(&spi->controller->dev, "Failed to setup device: %d\n",
  3383. status);
  3384. return status;
  3385. }
  3386. }
  3387. status = spi_set_cs_timing(spi);
  3388. if (status) {
  3389. mutex_unlock(&spi->controller->io_mutex);
  3390. return status;
  3391. }
  3392. if (spi->controller->auto_runtime_pm && spi->controller->set_cs) {
  3393. status = pm_runtime_resume_and_get(spi->controller->dev.parent);
  3394. if (status < 0) {
  3395. mutex_unlock(&spi->controller->io_mutex);
  3396. dev_err(&spi->controller->dev, "Failed to power device: %d\n",
  3397. status);
  3398. return status;
  3399. }
  3400. /*
  3401. * We do not want to return positive value from pm_runtime_get,
  3402. * there are many instances of devices calling spi_setup() and
  3403. * checking for a non-zero return value instead of a negative
  3404. * return value.
  3405. */
  3406. status = 0;
  3407. spi_set_cs(spi, false, true);
  3408. pm_runtime_mark_last_busy(spi->controller->dev.parent);
  3409. pm_runtime_put_autosuspend(spi->controller->dev.parent);
  3410. } else {
  3411. spi_set_cs(spi, false, true);
  3412. }
  3413. mutex_unlock(&spi->controller->io_mutex);
  3414. if (spi->rt && !spi->controller->rt) {
  3415. spi->controller->rt = true;
  3416. spi_set_thread_rt(spi->controller);
  3417. }
  3418. trace_spi_setup(spi, status);
  3419. dev_dbg(&spi->dev, "setup mode %lu, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
  3420. spi->mode & SPI_MODE_X_MASK,
  3421. (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
  3422. (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
  3423. (spi->mode & SPI_3WIRE) ? "3wire, " : "",
  3424. (spi->mode & SPI_LOOP) ? "loopback, " : "",
  3425. spi->bits_per_word, spi->max_speed_hz,
  3426. status);
  3427. return status;
  3428. }
  3429. EXPORT_SYMBOL_GPL(spi_setup);
  3430. static int _spi_xfer_word_delay_update(struct spi_transfer *xfer,
  3431. struct spi_device *spi)
  3432. {
  3433. int delay1, delay2;
  3434. delay1 = spi_delay_to_ns(&xfer->word_delay, xfer);
  3435. if (delay1 < 0)
  3436. return delay1;
  3437. delay2 = spi_delay_to_ns(&spi->word_delay, xfer);
  3438. if (delay2 < 0)
  3439. return delay2;
  3440. if (delay1 < delay2)
  3441. memcpy(&xfer->word_delay, &spi->word_delay,
  3442. sizeof(xfer->word_delay));
  3443. return 0;
  3444. }
  3445. static int __spi_validate(struct spi_device *spi, struct spi_message *message)
  3446. {
  3447. struct spi_controller *ctlr = spi->controller;
  3448. struct spi_transfer *xfer;
  3449. int w_size;
  3450. if (list_empty(&message->transfers))
  3451. return -EINVAL;
  3452. message->spi = spi;
  3453. /*
  3454. * Half-duplex links include original MicroWire, and ones with
  3455. * only one data pin like SPI_3WIRE (switches direction) or where
  3456. * either MOSI or MISO is missing. They can also be caused by
  3457. * software limitations.
  3458. */
  3459. if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
  3460. (spi->mode & SPI_3WIRE)) {
  3461. unsigned flags = ctlr->flags;
  3462. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  3463. if (xfer->rx_buf && xfer->tx_buf)
  3464. return -EINVAL;
  3465. if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
  3466. return -EINVAL;
  3467. if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
  3468. return -EINVAL;
  3469. }
  3470. }
  3471. /*
  3472. * Set transfer bits_per_word and max speed as spi device default if
  3473. * it is not set for this transfer.
  3474. * Set transfer tx_nbits and rx_nbits as single transfer default
  3475. * (SPI_NBITS_SINGLE) if it is not set for this transfer.
  3476. * Ensure transfer word_delay is at least as long as that required by
  3477. * device itself.
  3478. */
  3479. message->frame_length = 0;
  3480. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  3481. xfer->effective_speed_hz = 0;
  3482. message->frame_length += xfer->len;
  3483. if (!xfer->bits_per_word)
  3484. xfer->bits_per_word = spi->bits_per_word;
  3485. if (!xfer->speed_hz)
  3486. xfer->speed_hz = spi->max_speed_hz;
  3487. if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
  3488. xfer->speed_hz = ctlr->max_speed_hz;
  3489. if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
  3490. return -EINVAL;
  3491. /*
  3492. * SPI transfer length should be multiple of SPI word size
  3493. * where SPI word size should be power-of-two multiple.
  3494. */
  3495. if (xfer->bits_per_word <= 8)
  3496. w_size = 1;
  3497. else if (xfer->bits_per_word <= 16)
  3498. w_size = 2;
  3499. else
  3500. w_size = 4;
  3501. /* No partial transfers accepted */
  3502. if (xfer->len % w_size)
  3503. return -EINVAL;
  3504. if (xfer->speed_hz && ctlr->min_speed_hz &&
  3505. xfer->speed_hz < ctlr->min_speed_hz)
  3506. return -EINVAL;
  3507. if (xfer->tx_buf && !xfer->tx_nbits)
  3508. xfer->tx_nbits = SPI_NBITS_SINGLE;
  3509. if (xfer->rx_buf && !xfer->rx_nbits)
  3510. xfer->rx_nbits = SPI_NBITS_SINGLE;
  3511. /*
  3512. * Check transfer tx/rx_nbits:
  3513. * 1. check the value matches one of single, dual and quad
  3514. * 2. check tx/rx_nbits match the mode in spi_device
  3515. */
  3516. if (xfer->tx_buf) {
  3517. if (spi->mode & SPI_NO_TX)
  3518. return -EINVAL;
  3519. if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
  3520. xfer->tx_nbits != SPI_NBITS_DUAL &&
  3521. xfer->tx_nbits != SPI_NBITS_QUAD &&
  3522. xfer->tx_nbits != SPI_NBITS_OCTAL)
  3523. return -EINVAL;
  3524. if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
  3525. !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD | SPI_TX_OCTAL)))
  3526. return -EINVAL;
  3527. if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
  3528. !(spi->mode & (SPI_TX_QUAD | SPI_TX_OCTAL)))
  3529. return -EINVAL;
  3530. if ((xfer->tx_nbits == SPI_NBITS_OCTAL) &&
  3531. !(spi->mode & SPI_TX_OCTAL))
  3532. return -EINVAL;
  3533. }
  3534. /* Check transfer rx_nbits */
  3535. if (xfer->rx_buf) {
  3536. if (spi->mode & SPI_NO_RX)
  3537. return -EINVAL;
  3538. if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
  3539. xfer->rx_nbits != SPI_NBITS_DUAL &&
  3540. xfer->rx_nbits != SPI_NBITS_QUAD &&
  3541. xfer->rx_nbits != SPI_NBITS_OCTAL)
  3542. return -EINVAL;
  3543. if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
  3544. !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD | SPI_RX_OCTAL)))
  3545. return -EINVAL;
  3546. if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
  3547. !(spi->mode & (SPI_RX_QUAD | SPI_RX_OCTAL)))
  3548. return -EINVAL;
  3549. if ((xfer->rx_nbits == SPI_NBITS_OCTAL) &&
  3550. !(spi->mode & SPI_RX_OCTAL))
  3551. return -EINVAL;
  3552. }
  3553. if (_spi_xfer_word_delay_update(xfer, spi))
  3554. return -EINVAL;
  3555. }
  3556. message->status = -EINPROGRESS;
  3557. return 0;
  3558. }
  3559. /*
  3560. * spi_split_transfers - generic handling of transfer splitting
  3561. * @msg: the message to split
  3562. *
  3563. * Under certain conditions, a SPI controller may not support arbitrary
  3564. * transfer sizes or other features required by a peripheral. This function
  3565. * will split the transfers in the message into smaller transfers that are
  3566. * supported by the controller.
  3567. *
  3568. * Controllers with special requirements not covered here can also split
  3569. * transfers in the optimize_message() callback.
  3570. *
  3571. * Context: can sleep
  3572. * Return: zero on success, else a negative error code
  3573. */
  3574. static int spi_split_transfers(struct spi_message *msg)
  3575. {
  3576. struct spi_controller *ctlr = msg->spi->controller;
  3577. struct spi_transfer *xfer;
  3578. int ret;
  3579. /*
  3580. * If an SPI controller does not support toggling the CS line on each
  3581. * transfer (indicated by the SPI_CS_WORD flag) or we are using a GPIO
  3582. * for the CS line, we can emulate the CS-per-word hardware function by
  3583. * splitting transfers into one-word transfers and ensuring that
  3584. * cs_change is set for each transfer.
  3585. */
  3586. if ((msg->spi->mode & SPI_CS_WORD) &&
  3587. (!(ctlr->mode_bits & SPI_CS_WORD) || spi_is_csgpiod(msg->spi))) {
  3588. ret = spi_split_transfers_maxwords(ctlr, msg, 1);
  3589. if (ret)
  3590. return ret;
  3591. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  3592. /* Don't change cs_change on the last entry in the list */
  3593. if (list_is_last(&xfer->transfer_list, &msg->transfers))
  3594. break;
  3595. xfer->cs_change = 1;
  3596. }
  3597. } else {
  3598. ret = spi_split_transfers_maxsize(ctlr, msg,
  3599. spi_max_transfer_size(msg->spi));
  3600. if (ret)
  3601. return ret;
  3602. }
  3603. return 0;
  3604. }
  3605. /*
  3606. * __spi_optimize_message - shared implementation for spi_optimize_message()
  3607. * and spi_maybe_optimize_message()
  3608. * @spi: the device that will be used for the message
  3609. * @msg: the message to optimize
  3610. *
  3611. * Peripheral drivers will call spi_optimize_message() and the spi core will
  3612. * call spi_maybe_optimize_message() instead of calling this directly.
  3613. *
  3614. * It is not valid to call this on a message that has already been optimized.
  3615. *
  3616. * Return: zero on success, else a negative error code
  3617. */
  3618. static int __spi_optimize_message(struct spi_device *spi,
  3619. struct spi_message *msg)
  3620. {
  3621. struct spi_controller *ctlr = spi->controller;
  3622. int ret;
  3623. ret = __spi_validate(spi, msg);
  3624. if (ret)
  3625. return ret;
  3626. ret = spi_split_transfers(msg);
  3627. if (ret)
  3628. return ret;
  3629. if (ctlr->optimize_message) {
  3630. ret = ctlr->optimize_message(msg);
  3631. if (ret) {
  3632. spi_res_release(ctlr, msg);
  3633. return ret;
  3634. }
  3635. }
  3636. msg->optimized = true;
  3637. return 0;
  3638. }
  3639. /*
  3640. * spi_maybe_optimize_message - optimize message if it isn't already pre-optimized
  3641. * @spi: the device that will be used for the message
  3642. * @msg: the message to optimize
  3643. * Return: zero on success, else a negative error code
  3644. */
  3645. static int spi_maybe_optimize_message(struct spi_device *spi,
  3646. struct spi_message *msg)
  3647. {
  3648. if (spi->controller->defer_optimize_message) {
  3649. msg->spi = spi;
  3650. return 0;
  3651. }
  3652. if (msg->pre_optimized)
  3653. return 0;
  3654. return __spi_optimize_message(spi, msg);
  3655. }
  3656. /**
  3657. * spi_optimize_message - do any one-time validation and setup for a SPI message
  3658. * @spi: the device that will be used for the message
  3659. * @msg: the message to optimize
  3660. *
  3661. * Peripheral drivers that reuse the same message repeatedly may call this to
  3662. * perform as much message prep as possible once, rather than repeating it each
  3663. * time a message transfer is performed to improve throughput and reduce CPU
  3664. * usage.
  3665. *
  3666. * Once a message has been optimized, it cannot be modified with the exception
  3667. * of updating the contents of any xfer->tx_buf (the pointer can't be changed,
  3668. * only the data in the memory it points to).
  3669. *
  3670. * Calls to this function must be balanced with calls to spi_unoptimize_message()
  3671. * to avoid leaking resources.
  3672. *
  3673. * Context: can sleep
  3674. * Return: zero on success, else a negative error code
  3675. */
  3676. int spi_optimize_message(struct spi_device *spi, struct spi_message *msg)
  3677. {
  3678. int ret;
  3679. /*
  3680. * Pre-optimization is not supported and optimization is deferred e.g.
  3681. * when using spi-mux.
  3682. */
  3683. if (spi->controller->defer_optimize_message)
  3684. return 0;
  3685. ret = __spi_optimize_message(spi, msg);
  3686. if (ret)
  3687. return ret;
  3688. /*
  3689. * This flag indicates that the peripheral driver called spi_optimize_message()
  3690. * and therefore we shouldn't unoptimize message automatically when finalizing
  3691. * the message but rather wait until spi_unoptimize_message() is called
  3692. * by the peripheral driver.
  3693. */
  3694. msg->pre_optimized = true;
  3695. return 0;
  3696. }
  3697. EXPORT_SYMBOL_GPL(spi_optimize_message);
  3698. /**
  3699. * spi_unoptimize_message - releases any resources allocated by spi_optimize_message()
  3700. * @msg: the message to unoptimize
  3701. *
  3702. * Calls to this function must be balanced with calls to spi_optimize_message().
  3703. *
  3704. * Context: can sleep
  3705. */
  3706. void spi_unoptimize_message(struct spi_message *msg)
  3707. {
  3708. if (msg->spi->controller->defer_optimize_message)
  3709. return;
  3710. __spi_unoptimize_message(msg);
  3711. msg->pre_optimized = false;
  3712. }
  3713. EXPORT_SYMBOL_GPL(spi_unoptimize_message);
  3714. static int __spi_async(struct spi_device *spi, struct spi_message *message)
  3715. {
  3716. struct spi_controller *ctlr = spi->controller;
  3717. struct spi_transfer *xfer;
  3718. /*
  3719. * Some controllers do not support doing regular SPI transfers. Return
  3720. * ENOTSUPP when this is the case.
  3721. */
  3722. if (!ctlr->transfer)
  3723. return -ENOTSUPP;
  3724. SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_async);
  3725. SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_async);
  3726. trace_spi_message_submit(message);
  3727. if (!ctlr->ptp_sts_supported) {
  3728. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  3729. xfer->ptp_sts_word_pre = 0;
  3730. ptp_read_system_prets(xfer->ptp_sts);
  3731. }
  3732. }
  3733. return ctlr->transfer(spi, message);
  3734. }
  3735. static void devm_spi_unoptimize_message(void *msg)
  3736. {
  3737. spi_unoptimize_message(msg);
  3738. }
  3739. /**
  3740. * devm_spi_optimize_message - managed version of spi_optimize_message()
  3741. * @dev: the device that manages @msg (usually @spi->dev)
  3742. * @spi: the device that will be used for the message
  3743. * @msg: the message to optimize
  3744. * Return: zero on success, else a negative error code
  3745. *
  3746. * spi_unoptimize_message() will automatically be called when the device is
  3747. * removed.
  3748. */
  3749. int devm_spi_optimize_message(struct device *dev, struct spi_device *spi,
  3750. struct spi_message *msg)
  3751. {
  3752. int ret;
  3753. ret = spi_optimize_message(spi, msg);
  3754. if (ret)
  3755. return ret;
  3756. return devm_add_action_or_reset(dev, devm_spi_unoptimize_message, msg);
  3757. }
  3758. EXPORT_SYMBOL_GPL(devm_spi_optimize_message);
  3759. /**
  3760. * spi_async - asynchronous SPI transfer
  3761. * @spi: device with which data will be exchanged
  3762. * @message: describes the data transfers, including completion callback
  3763. * Context: any (IRQs may be blocked, etc)
  3764. *
  3765. * This call may be used in_irq and other contexts which can't sleep,
  3766. * as well as from task contexts which can sleep.
  3767. *
  3768. * The completion callback is invoked in a context which can't sleep.
  3769. * Before that invocation, the value of message->status is undefined.
  3770. * When the callback is issued, message->status holds either zero (to
  3771. * indicate complete success) or a negative error code. After that
  3772. * callback returns, the driver which issued the transfer request may
  3773. * deallocate the associated memory; it's no longer in use by any SPI
  3774. * core or controller driver code.
  3775. *
  3776. * Note that although all messages to a spi_device are handled in
  3777. * FIFO order, messages may go to different devices in other orders.
  3778. * Some device might be higher priority, or have various "hard" access
  3779. * time requirements, for example.
  3780. *
  3781. * On detection of any fault during the transfer, processing of
  3782. * the entire message is aborted, and the device is deselected.
  3783. * Until returning from the associated message completion callback,
  3784. * no other spi_message queued to that device will be processed.
  3785. * (This rule applies equally to all the synchronous transfer calls,
  3786. * which are wrappers around this core asynchronous primitive.)
  3787. *
  3788. * Return: zero on success, else a negative error code.
  3789. */
  3790. int spi_async(struct spi_device *spi, struct spi_message *message)
  3791. {
  3792. struct spi_controller *ctlr = spi->controller;
  3793. int ret;
  3794. unsigned long flags;
  3795. ret = spi_maybe_optimize_message(spi, message);
  3796. if (ret)
  3797. return ret;
  3798. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  3799. if (ctlr->bus_lock_flag)
  3800. ret = -EBUSY;
  3801. else
  3802. ret = __spi_async(spi, message);
  3803. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  3804. return ret;
  3805. }
  3806. EXPORT_SYMBOL_GPL(spi_async);
  3807. static void __spi_transfer_message_noqueue(struct spi_controller *ctlr, struct spi_message *msg)
  3808. {
  3809. bool was_busy;
  3810. int ret;
  3811. mutex_lock(&ctlr->io_mutex);
  3812. was_busy = ctlr->busy;
  3813. ctlr->cur_msg = msg;
  3814. ret = __spi_pump_transfer_message(ctlr, msg, was_busy);
  3815. if (ret)
  3816. dev_err(&ctlr->dev, "noqueue transfer failed\n");
  3817. ctlr->cur_msg = NULL;
  3818. ctlr->fallback = false;
  3819. if (!was_busy) {
  3820. kfree(ctlr->dummy_rx);
  3821. ctlr->dummy_rx = NULL;
  3822. kfree(ctlr->dummy_tx);
  3823. ctlr->dummy_tx = NULL;
  3824. if (ctlr->unprepare_transfer_hardware &&
  3825. ctlr->unprepare_transfer_hardware(ctlr))
  3826. dev_err(&ctlr->dev,
  3827. "failed to unprepare transfer hardware\n");
  3828. spi_idle_runtime_pm(ctlr);
  3829. }
  3830. mutex_unlock(&ctlr->io_mutex);
  3831. }
  3832. /*-------------------------------------------------------------------------*/
  3833. /*
  3834. * Utility methods for SPI protocol drivers, layered on
  3835. * top of the core. Some other utility methods are defined as
  3836. * inline functions.
  3837. */
  3838. static void spi_complete(void *arg)
  3839. {
  3840. complete(arg);
  3841. }
  3842. static int __spi_sync(struct spi_device *spi, struct spi_message *message)
  3843. {
  3844. DECLARE_COMPLETION_ONSTACK(done);
  3845. unsigned long flags;
  3846. int status;
  3847. struct spi_controller *ctlr = spi->controller;
  3848. if (__spi_check_suspended(ctlr)) {
  3849. dev_warn_once(&spi->dev, "Attempted to sync while suspend\n");
  3850. return -ESHUTDOWN;
  3851. }
  3852. status = spi_maybe_optimize_message(spi, message);
  3853. if (status)
  3854. return status;
  3855. SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync);
  3856. SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync);
  3857. /*
  3858. * Checking queue_empty here only guarantees async/sync message
  3859. * ordering when coming from the same context. It does not need to
  3860. * guard against reentrancy from a different context. The io_mutex
  3861. * will catch those cases.
  3862. */
  3863. if (READ_ONCE(ctlr->queue_empty) && !ctlr->must_async) {
  3864. message->actual_length = 0;
  3865. message->status = -EINPROGRESS;
  3866. trace_spi_message_submit(message);
  3867. SPI_STATISTICS_INCREMENT_FIELD(ctlr->pcpu_statistics, spi_sync_immediate);
  3868. SPI_STATISTICS_INCREMENT_FIELD(spi->pcpu_statistics, spi_sync_immediate);
  3869. __spi_transfer_message_noqueue(ctlr, message);
  3870. return message->status;
  3871. }
  3872. /*
  3873. * There are messages in the async queue that could have originated
  3874. * from the same context, so we need to preserve ordering.
  3875. * Therefor we send the message to the async queue and wait until they
  3876. * are completed.
  3877. */
  3878. message->complete = spi_complete;
  3879. message->context = &done;
  3880. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  3881. status = __spi_async(spi, message);
  3882. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  3883. if (status == 0) {
  3884. wait_for_completion(&done);
  3885. status = message->status;
  3886. }
  3887. message->complete = NULL;
  3888. message->context = NULL;
  3889. return status;
  3890. }
  3891. /**
  3892. * spi_sync - blocking/synchronous SPI data transfers
  3893. * @spi: device with which data will be exchanged
  3894. * @message: describes the data transfers
  3895. * Context: can sleep
  3896. *
  3897. * This call may only be used from a context that may sleep. The sleep
  3898. * is non-interruptible, and has no timeout. Low-overhead controller
  3899. * drivers may DMA directly into and out of the message buffers.
  3900. *
  3901. * Note that the SPI device's chip select is active during the message,
  3902. * and then is normally disabled between messages. Drivers for some
  3903. * frequently-used devices may want to minimize costs of selecting a chip,
  3904. * by leaving it selected in anticipation that the next message will go
  3905. * to the same chip. (That may increase power usage.)
  3906. *
  3907. * Also, the caller is guaranteeing that the memory associated with the
  3908. * message will not be freed before this call returns.
  3909. *
  3910. * Return: zero on success, else a negative error code.
  3911. */
  3912. int spi_sync(struct spi_device *spi, struct spi_message *message)
  3913. {
  3914. int ret;
  3915. mutex_lock(&spi->controller->bus_lock_mutex);
  3916. ret = __spi_sync(spi, message);
  3917. mutex_unlock(&spi->controller->bus_lock_mutex);
  3918. return ret;
  3919. }
  3920. EXPORT_SYMBOL_GPL(spi_sync);
  3921. /**
  3922. * spi_sync_locked - version of spi_sync with exclusive bus usage
  3923. * @spi: device with which data will be exchanged
  3924. * @message: describes the data transfers
  3925. * Context: can sleep
  3926. *
  3927. * This call may only be used from a context that may sleep. The sleep
  3928. * is non-interruptible, and has no timeout. Low-overhead controller
  3929. * drivers may DMA directly into and out of the message buffers.
  3930. *
  3931. * This call should be used by drivers that require exclusive access to the
  3932. * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
  3933. * be released by a spi_bus_unlock call when the exclusive access is over.
  3934. *
  3935. * Return: zero on success, else a negative error code.
  3936. */
  3937. int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
  3938. {
  3939. return __spi_sync(spi, message);
  3940. }
  3941. EXPORT_SYMBOL_GPL(spi_sync_locked);
  3942. /**
  3943. * spi_bus_lock - obtain a lock for exclusive SPI bus usage
  3944. * @ctlr: SPI bus master that should be locked for exclusive bus access
  3945. * Context: can sleep
  3946. *
  3947. * This call may only be used from a context that may sleep. The sleep
  3948. * is non-interruptible, and has no timeout.
  3949. *
  3950. * This call should be used by drivers that require exclusive access to the
  3951. * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
  3952. * exclusive access is over. Data transfer must be done by spi_sync_locked
  3953. * and spi_async_locked calls when the SPI bus lock is held.
  3954. *
  3955. * Return: always zero.
  3956. */
  3957. int spi_bus_lock(struct spi_controller *ctlr)
  3958. {
  3959. unsigned long flags;
  3960. mutex_lock(&ctlr->bus_lock_mutex);
  3961. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  3962. ctlr->bus_lock_flag = 1;
  3963. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  3964. /* Mutex remains locked until spi_bus_unlock() is called */
  3965. return 0;
  3966. }
  3967. EXPORT_SYMBOL_GPL(spi_bus_lock);
  3968. /**
  3969. * spi_bus_unlock - release the lock for exclusive SPI bus usage
  3970. * @ctlr: SPI bus master that was locked for exclusive bus access
  3971. * Context: can sleep
  3972. *
  3973. * This call may only be used from a context that may sleep. The sleep
  3974. * is non-interruptible, and has no timeout.
  3975. *
  3976. * This call releases an SPI bus lock previously obtained by an spi_bus_lock
  3977. * call.
  3978. *
  3979. * Return: always zero.
  3980. */
  3981. int spi_bus_unlock(struct spi_controller *ctlr)
  3982. {
  3983. ctlr->bus_lock_flag = 0;
  3984. mutex_unlock(&ctlr->bus_lock_mutex);
  3985. return 0;
  3986. }
  3987. EXPORT_SYMBOL_GPL(spi_bus_unlock);
  3988. /* Portable code must never pass more than 32 bytes */
  3989. #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
  3990. static u8 *buf;
  3991. /**
  3992. * spi_write_then_read - SPI synchronous write followed by read
  3993. * @spi: device with which data will be exchanged
  3994. * @txbuf: data to be written (need not be DMA-safe)
  3995. * @n_tx: size of txbuf, in bytes
  3996. * @rxbuf: buffer into which data will be read (need not be DMA-safe)
  3997. * @n_rx: size of rxbuf, in bytes
  3998. * Context: can sleep
  3999. *
  4000. * This performs a half duplex MicroWire style transaction with the
  4001. * device, sending txbuf and then reading rxbuf. The return value
  4002. * is zero for success, else a negative errno status code.
  4003. * This call may only be used from a context that may sleep.
  4004. *
  4005. * Parameters to this routine are always copied using a small buffer.
  4006. * Performance-sensitive or bulk transfer code should instead use
  4007. * spi_{async,sync}() calls with DMA-safe buffers.
  4008. *
  4009. * Return: zero on success, else a negative error code.
  4010. */
  4011. int spi_write_then_read(struct spi_device *spi,
  4012. const void *txbuf, unsigned n_tx,
  4013. void *rxbuf, unsigned n_rx)
  4014. {
  4015. static DEFINE_MUTEX(lock);
  4016. int status;
  4017. struct spi_message message;
  4018. struct spi_transfer x[2];
  4019. u8 *local_buf;
  4020. /*
  4021. * Use preallocated DMA-safe buffer if we can. We can't avoid
  4022. * copying here, (as a pure convenience thing), but we can
  4023. * keep heap costs out of the hot path unless someone else is
  4024. * using the pre-allocated buffer or the transfer is too large.
  4025. */
  4026. if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
  4027. local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
  4028. GFP_KERNEL | GFP_DMA);
  4029. if (!local_buf)
  4030. return -ENOMEM;
  4031. } else {
  4032. local_buf = buf;
  4033. }
  4034. spi_message_init(&message);
  4035. memset(x, 0, sizeof(x));
  4036. if (n_tx) {
  4037. x[0].len = n_tx;
  4038. spi_message_add_tail(&x[0], &message);
  4039. }
  4040. if (n_rx) {
  4041. x[1].len = n_rx;
  4042. spi_message_add_tail(&x[1], &message);
  4043. }
  4044. memcpy(local_buf, txbuf, n_tx);
  4045. x[0].tx_buf = local_buf;
  4046. x[1].rx_buf = local_buf + n_tx;
  4047. /* Do the I/O */
  4048. status = spi_sync(spi, &message);
  4049. if (status == 0)
  4050. memcpy(rxbuf, x[1].rx_buf, n_rx);
  4051. if (x[0].tx_buf == buf)
  4052. mutex_unlock(&lock);
  4053. else
  4054. kfree(local_buf);
  4055. return status;
  4056. }
  4057. EXPORT_SYMBOL_GPL(spi_write_then_read);
  4058. /*-------------------------------------------------------------------------*/
  4059. #if IS_ENABLED(CONFIG_OF_DYNAMIC)
  4060. /* Must call put_device() when done with returned spi_device device */
  4061. static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
  4062. {
  4063. struct device *dev = bus_find_device_by_of_node(&spi_bus_type, node);
  4064. return dev ? to_spi_device(dev) : NULL;
  4065. }
  4066. /* The spi controllers are not using spi_bus, so we find it with another way */
  4067. static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
  4068. {
  4069. struct device *dev;
  4070. dev = class_find_device_by_of_node(&spi_master_class, node);
  4071. if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
  4072. dev = class_find_device_by_of_node(&spi_slave_class, node);
  4073. if (!dev)
  4074. return NULL;
  4075. /* Reference got in class_find_device */
  4076. return container_of(dev, struct spi_controller, dev);
  4077. }
  4078. static int of_spi_notify(struct notifier_block *nb, unsigned long action,
  4079. void *arg)
  4080. {
  4081. struct of_reconfig_data *rd = arg;
  4082. struct spi_controller *ctlr;
  4083. struct spi_device *spi;
  4084. switch (of_reconfig_get_state_change(action, arg)) {
  4085. case OF_RECONFIG_CHANGE_ADD:
  4086. ctlr = of_find_spi_controller_by_node(rd->dn->parent);
  4087. if (ctlr == NULL)
  4088. return NOTIFY_OK; /* Not for us */
  4089. if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
  4090. put_device(&ctlr->dev);
  4091. return NOTIFY_OK;
  4092. }
  4093. /*
  4094. * Clear the flag before adding the device so that fw_devlink
  4095. * doesn't skip adding consumers to this device.
  4096. */
  4097. rd->dn->fwnode.flags &= ~FWNODE_FLAG_NOT_DEVICE;
  4098. spi = of_register_spi_device(ctlr, rd->dn);
  4099. put_device(&ctlr->dev);
  4100. if (IS_ERR(spi)) {
  4101. pr_err("%s: failed to create for '%pOF'\n",
  4102. __func__, rd->dn);
  4103. of_node_clear_flag(rd->dn, OF_POPULATED);
  4104. return notifier_from_errno(PTR_ERR(spi));
  4105. }
  4106. break;
  4107. case OF_RECONFIG_CHANGE_REMOVE:
  4108. /* Already depopulated? */
  4109. if (!of_node_check_flag(rd->dn, OF_POPULATED))
  4110. return NOTIFY_OK;
  4111. /* Find our device by node */
  4112. spi = of_find_spi_device_by_node(rd->dn);
  4113. if (spi == NULL)
  4114. return NOTIFY_OK; /* No? not meant for us */
  4115. /* Unregister takes one ref away */
  4116. spi_unregister_device(spi);
  4117. /* And put the reference of the find */
  4118. put_device(&spi->dev);
  4119. break;
  4120. }
  4121. return NOTIFY_OK;
  4122. }
  4123. static struct notifier_block spi_of_notifier = {
  4124. .notifier_call = of_spi_notify,
  4125. };
  4126. #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  4127. extern struct notifier_block spi_of_notifier;
  4128. #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  4129. #if IS_ENABLED(CONFIG_ACPI)
  4130. static int spi_acpi_controller_match(struct device *dev, const void *data)
  4131. {
  4132. return ACPI_COMPANION(dev->parent) == data;
  4133. }
  4134. struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
  4135. {
  4136. struct device *dev;
  4137. dev = class_find_device(&spi_master_class, NULL, adev,
  4138. spi_acpi_controller_match);
  4139. if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
  4140. dev = class_find_device(&spi_slave_class, NULL, adev,
  4141. spi_acpi_controller_match);
  4142. if (!dev)
  4143. return NULL;
  4144. return container_of(dev, struct spi_controller, dev);
  4145. }
  4146. EXPORT_SYMBOL_GPL(acpi_spi_find_controller_by_adev);
  4147. static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
  4148. {
  4149. struct device *dev;
  4150. dev = bus_find_device_by_acpi_dev(&spi_bus_type, adev);
  4151. return to_spi_device(dev);
  4152. }
  4153. static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
  4154. void *arg)
  4155. {
  4156. struct acpi_device *adev = arg;
  4157. struct spi_controller *ctlr;
  4158. struct spi_device *spi;
  4159. switch (value) {
  4160. case ACPI_RECONFIG_DEVICE_ADD:
  4161. ctlr = acpi_spi_find_controller_by_adev(acpi_dev_parent(adev));
  4162. if (!ctlr)
  4163. break;
  4164. acpi_register_spi_device(ctlr, adev);
  4165. put_device(&ctlr->dev);
  4166. break;
  4167. case ACPI_RECONFIG_DEVICE_REMOVE:
  4168. if (!acpi_device_enumerated(adev))
  4169. break;
  4170. spi = acpi_spi_find_device_by_adev(adev);
  4171. if (!spi)
  4172. break;
  4173. spi_unregister_device(spi);
  4174. put_device(&spi->dev);
  4175. break;
  4176. }
  4177. return NOTIFY_OK;
  4178. }
  4179. static struct notifier_block spi_acpi_notifier = {
  4180. .notifier_call = acpi_spi_notify,
  4181. };
  4182. #else
  4183. extern struct notifier_block spi_acpi_notifier;
  4184. #endif
  4185. static int __init spi_init(void)
  4186. {
  4187. int status;
  4188. buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
  4189. if (!buf) {
  4190. status = -ENOMEM;
  4191. goto err0;
  4192. }
  4193. status = bus_register(&spi_bus_type);
  4194. if (status < 0)
  4195. goto err1;
  4196. status = class_register(&spi_master_class);
  4197. if (status < 0)
  4198. goto err2;
  4199. if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
  4200. status = class_register(&spi_slave_class);
  4201. if (status < 0)
  4202. goto err3;
  4203. }
  4204. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  4205. WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
  4206. if (IS_ENABLED(CONFIG_ACPI))
  4207. WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
  4208. return 0;
  4209. err3:
  4210. class_unregister(&spi_master_class);
  4211. err2:
  4212. bus_unregister(&spi_bus_type);
  4213. err1:
  4214. kfree(buf);
  4215. buf = NULL;
  4216. err0:
  4217. return status;
  4218. }
  4219. /*
  4220. * A board_info is normally registered in arch_initcall(),
  4221. * but even essential drivers wait till later.
  4222. *
  4223. * REVISIT only boardinfo really needs static linking. The rest (device and
  4224. * driver registration) _could_ be dynamically linked (modular) ... Costs
  4225. * include needing to have boardinfo data structures be much more public.
  4226. */
  4227. postcore_initcall(spi_init);