f_fs.c 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * f_fs.c -- user mode file system API for USB composite function controllers
  4. *
  5. * Copyright (C) 2010 Samsung Electronics
  6. * Author: Michal Nazarewicz <mina86@mina86.com>
  7. *
  8. * Based on inode.c (GadgetFS) which was:
  9. * Copyright (C) 2003-2004 David Brownell
  10. * Copyright (C) 2003 Agilent Technologies
  11. */
  12. /* #define DEBUG */
  13. /* #define VERBOSE_DEBUG */
  14. #include <linux/blkdev.h>
  15. #include <linux/dma-buf.h>
  16. #include <linux/dma-fence.h>
  17. #include <linux/dma-resv.h>
  18. #include <linux/pagemap.h>
  19. #include <linux/export.h>
  20. #include <linux/fs_parser.h>
  21. #include <linux/hid.h>
  22. #include <linux/mm.h>
  23. #include <linux/module.h>
  24. #include <linux/scatterlist.h>
  25. #include <linux/sched/signal.h>
  26. #include <linux/uio.h>
  27. #include <linux/vmalloc.h>
  28. #include <linux/unaligned.h>
  29. #include <linux/usb/ccid.h>
  30. #include <linux/usb/composite.h>
  31. #include <linux/usb/functionfs.h>
  32. #include <linux/usb/func_utils.h>
  33. #include <linux/aio.h>
  34. #include <linux/kthread.h>
  35. #include <linux/poll.h>
  36. #include <linux/eventfd.h>
  37. #include "u_fs.h"
  38. #include "u_os_desc.h"
  39. #include "configfs.h"
  40. #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
  41. #define MAX_ALT_SETTINGS 2 /* Allow up to 2 alt settings to be set. */
  42. #define DMABUF_ENQUEUE_TIMEOUT_MS 5000
  43. MODULE_IMPORT_NS(DMA_BUF);
  44. /* Reference counter handling */
  45. static void ffs_data_get(struct ffs_data *ffs);
  46. static void ffs_data_put(struct ffs_data *ffs);
  47. /* Creates new ffs_data object. */
  48. static struct ffs_data *__must_check ffs_data_new(const char *dev_name)
  49. __attribute__((malloc));
  50. /* Opened counter handling. */
  51. static void ffs_data_opened(struct ffs_data *ffs);
  52. static void ffs_data_closed(struct ffs_data *ffs);
  53. /* Called with ffs->mutex held; take over ownership of data. */
  54. static int __must_check
  55. __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
  56. static int __must_check
  57. __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
  58. /* The function structure ***************************************************/
  59. struct ffs_ep;
  60. struct ffs_function {
  61. struct usb_configuration *conf;
  62. struct usb_gadget *gadget;
  63. struct ffs_data *ffs;
  64. struct ffs_ep *eps;
  65. u8 eps_revmap[16];
  66. short *interfaces_nums;
  67. struct usb_function function;
  68. int cur_alt[MAX_CONFIG_INTERFACES];
  69. };
  70. static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
  71. {
  72. return container_of(f, struct ffs_function, function);
  73. }
  74. static inline enum ffs_setup_state
  75. ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
  76. {
  77. return (enum ffs_setup_state)
  78. cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
  79. }
  80. static void ffs_func_eps_disable(struct ffs_function *func);
  81. static int __must_check ffs_func_eps_enable(struct ffs_function *func);
  82. static int ffs_func_bind(struct usb_configuration *,
  83. struct usb_function *);
  84. static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
  85. static int ffs_func_get_alt(struct usb_function *f, unsigned int intf);
  86. static void ffs_func_disable(struct usb_function *);
  87. static int ffs_func_setup(struct usb_function *,
  88. const struct usb_ctrlrequest *);
  89. static bool ffs_func_req_match(struct usb_function *,
  90. const struct usb_ctrlrequest *,
  91. bool config0);
  92. static void ffs_func_suspend(struct usb_function *);
  93. static void ffs_func_resume(struct usb_function *);
  94. static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
  95. static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
  96. /* The endpoints structures *************************************************/
  97. struct ffs_ep {
  98. struct usb_ep *ep; /* P: ffs->eps_lock */
  99. struct usb_request *req; /* P: epfile->mutex */
  100. /* [0]: full speed, [1]: high speed, [2]: super speed */
  101. struct usb_endpoint_descriptor *descs[3];
  102. u8 num;
  103. };
  104. struct ffs_dmabuf_priv {
  105. struct list_head entry;
  106. struct kref ref;
  107. struct ffs_data *ffs;
  108. struct dma_buf_attachment *attach;
  109. struct sg_table *sgt;
  110. enum dma_data_direction dir;
  111. spinlock_t lock;
  112. u64 context;
  113. struct usb_request *req; /* P: ffs->eps_lock */
  114. struct usb_ep *ep; /* P: ffs->eps_lock */
  115. };
  116. struct ffs_dma_fence {
  117. struct dma_fence base;
  118. struct ffs_dmabuf_priv *priv;
  119. struct work_struct work;
  120. };
  121. struct ffs_epfile {
  122. /* Protects ep->ep and ep->req. */
  123. struct mutex mutex;
  124. struct ffs_data *ffs;
  125. struct ffs_ep *ep; /* P: ffs->eps_lock */
  126. struct dentry *dentry;
  127. /*
  128. * Buffer for holding data from partial reads which may happen since
  129. * we’re rounding user read requests to a multiple of a max packet size.
  130. *
  131. * The pointer is initialised with NULL value and may be set by
  132. * __ffs_epfile_read_data function to point to a temporary buffer.
  133. *
  134. * In normal operation, calls to __ffs_epfile_read_buffered will consume
  135. * data from said buffer and eventually free it. Importantly, while the
  136. * function is using the buffer, it sets the pointer to NULL. This is
  137. * all right since __ffs_epfile_read_data and __ffs_epfile_read_buffered
  138. * can never run concurrently (they are synchronised by epfile->mutex)
  139. * so the latter will not assign a new value to the pointer.
  140. *
  141. * Meanwhile ffs_func_eps_disable frees the buffer (if the pointer is
  142. * valid) and sets the pointer to READ_BUFFER_DROP value. This special
  143. * value is crux of the synchronisation between ffs_func_eps_disable and
  144. * __ffs_epfile_read_data.
  145. *
  146. * Once __ffs_epfile_read_data is about to finish it will try to set the
  147. * pointer back to its old value (as described above), but seeing as the
  148. * pointer is not-NULL (namely READ_BUFFER_DROP) it will instead free
  149. * the buffer.
  150. *
  151. * == State transitions ==
  152. *
  153. * • ptr == NULL: (initial state)
  154. * ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP
  155. * ◦ __ffs_epfile_read_buffered: nop
  156. * ◦ __ffs_epfile_read_data allocates temp buffer: go to ptr == buf
  157. * ◦ reading finishes: n/a, not in ‘and reading’ state
  158. * • ptr == DROP:
  159. * ◦ __ffs_epfile_read_buffer_free: nop
  160. * ◦ __ffs_epfile_read_buffered: go to ptr == NULL
  161. * ◦ __ffs_epfile_read_data allocates temp buffer: free buf, nop
  162. * ◦ reading finishes: n/a, not in ‘and reading’ state
  163. * • ptr == buf:
  164. * ◦ __ffs_epfile_read_buffer_free: free buf, go to ptr == DROP
  165. * ◦ __ffs_epfile_read_buffered: go to ptr == NULL and reading
  166. * ◦ __ffs_epfile_read_data: n/a, __ffs_epfile_read_buffered
  167. * is always called first
  168. * ◦ reading finishes: n/a, not in ‘and reading’ state
  169. * • ptr == NULL and reading:
  170. * ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP and reading
  171. * ◦ __ffs_epfile_read_buffered: n/a, mutex is held
  172. * ◦ __ffs_epfile_read_data: n/a, mutex is held
  173. * ◦ reading finishes and …
  174. * … all data read: free buf, go to ptr == NULL
  175. * … otherwise: go to ptr == buf and reading
  176. * • ptr == DROP and reading:
  177. * ◦ __ffs_epfile_read_buffer_free: nop
  178. * ◦ __ffs_epfile_read_buffered: n/a, mutex is held
  179. * ◦ __ffs_epfile_read_data: n/a, mutex is held
  180. * ◦ reading finishes: free buf, go to ptr == DROP
  181. */
  182. struct ffs_buffer *read_buffer;
  183. #define READ_BUFFER_DROP ((struct ffs_buffer *)ERR_PTR(-ESHUTDOWN))
  184. char name[5];
  185. unsigned char in; /* P: ffs->eps_lock */
  186. unsigned char isoc; /* P: ffs->eps_lock */
  187. unsigned char _pad;
  188. /* Protects dmabufs */
  189. struct mutex dmabufs_mutex;
  190. struct list_head dmabufs; /* P: dmabufs_mutex */
  191. atomic_t seqno;
  192. };
  193. struct ffs_buffer {
  194. size_t length;
  195. char *data;
  196. char storage[] __counted_by(length);
  197. };
  198. /* ffs_io_data structure ***************************************************/
  199. struct ffs_io_data {
  200. bool aio;
  201. bool read;
  202. struct kiocb *kiocb;
  203. struct iov_iter data;
  204. const void *to_free;
  205. char *buf;
  206. struct mm_struct *mm;
  207. struct work_struct work;
  208. struct usb_ep *ep;
  209. struct usb_request *req;
  210. struct sg_table sgt;
  211. bool use_sg;
  212. struct ffs_data *ffs;
  213. int status;
  214. struct completion done;
  215. };
  216. struct ffs_desc_helper {
  217. struct ffs_data *ffs;
  218. unsigned interfaces_count;
  219. unsigned eps_count;
  220. };
  221. static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
  222. static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
  223. static struct dentry *
  224. ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
  225. const struct file_operations *fops);
  226. /* Devices management *******************************************************/
  227. DEFINE_MUTEX(ffs_lock);
  228. EXPORT_SYMBOL_GPL(ffs_lock);
  229. static struct ffs_dev *_ffs_find_dev(const char *name);
  230. static struct ffs_dev *_ffs_alloc_dev(void);
  231. static void _ffs_free_dev(struct ffs_dev *dev);
  232. static int ffs_acquire_dev(const char *dev_name, struct ffs_data *ffs_data);
  233. static void ffs_release_dev(struct ffs_dev *ffs_dev);
  234. static int ffs_ready(struct ffs_data *ffs);
  235. static void ffs_closed(struct ffs_data *ffs);
  236. /* Misc helper functions ****************************************************/
  237. static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
  238. __attribute__((warn_unused_result, nonnull));
  239. static char *ffs_prepare_buffer(const char __user *buf, size_t len)
  240. __attribute__((warn_unused_result, nonnull));
  241. /* Control file aka ep0 *****************************************************/
  242. static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
  243. {
  244. struct ffs_data *ffs = req->context;
  245. complete(&ffs->ep0req_completion);
  246. }
  247. static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
  248. __releases(&ffs->ev.waitq.lock)
  249. {
  250. struct usb_request *req = ffs->ep0req;
  251. int ret;
  252. if (!req) {
  253. spin_unlock_irq(&ffs->ev.waitq.lock);
  254. return -EINVAL;
  255. }
  256. req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
  257. spin_unlock_irq(&ffs->ev.waitq.lock);
  258. req->buf = data;
  259. req->length = len;
  260. /*
  261. * UDC layer requires to provide a buffer even for ZLP, but should
  262. * not use it at all. Let's provide some poisoned pointer to catch
  263. * possible bug in the driver.
  264. */
  265. if (req->buf == NULL)
  266. req->buf = (void *)0xDEADBABE;
  267. reinit_completion(&ffs->ep0req_completion);
  268. ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
  269. if (ret < 0)
  270. return ret;
  271. ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
  272. if (ret) {
  273. usb_ep_dequeue(ffs->gadget->ep0, req);
  274. return -EINTR;
  275. }
  276. ffs->setup_state = FFS_NO_SETUP;
  277. return req->status ? req->status : req->actual;
  278. }
  279. static int __ffs_ep0_stall(struct ffs_data *ffs)
  280. {
  281. if (ffs->ev.can_stall) {
  282. pr_vdebug("ep0 stall\n");
  283. usb_ep_set_halt(ffs->gadget->ep0);
  284. ffs->setup_state = FFS_NO_SETUP;
  285. return -EL2HLT;
  286. } else {
  287. pr_debug("bogus ep0 stall!\n");
  288. return -ESRCH;
  289. }
  290. }
  291. static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
  292. size_t len, loff_t *ptr)
  293. {
  294. struct ffs_data *ffs = file->private_data;
  295. ssize_t ret;
  296. char *data;
  297. /* Fast check if setup was canceled */
  298. if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
  299. return -EIDRM;
  300. /* Acquire mutex */
  301. ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
  302. if (ret < 0)
  303. return ret;
  304. /* Check state */
  305. switch (ffs->state) {
  306. case FFS_READ_DESCRIPTORS:
  307. case FFS_READ_STRINGS:
  308. /* Copy data */
  309. if (len < 16) {
  310. ret = -EINVAL;
  311. break;
  312. }
  313. data = ffs_prepare_buffer(buf, len);
  314. if (IS_ERR(data)) {
  315. ret = PTR_ERR(data);
  316. break;
  317. }
  318. /* Handle data */
  319. if (ffs->state == FFS_READ_DESCRIPTORS) {
  320. pr_info("read descriptors\n");
  321. ret = __ffs_data_got_descs(ffs, data, len);
  322. if (ret < 0)
  323. break;
  324. ffs->state = FFS_READ_STRINGS;
  325. ret = len;
  326. } else {
  327. pr_info("read strings\n");
  328. ret = __ffs_data_got_strings(ffs, data, len);
  329. if (ret < 0)
  330. break;
  331. ret = ffs_epfiles_create(ffs);
  332. if (ret) {
  333. ffs->state = FFS_CLOSING;
  334. break;
  335. }
  336. ffs->state = FFS_ACTIVE;
  337. mutex_unlock(&ffs->mutex);
  338. ret = ffs_ready(ffs);
  339. if (ret < 0) {
  340. ffs->state = FFS_CLOSING;
  341. return ret;
  342. }
  343. return len;
  344. }
  345. break;
  346. case FFS_ACTIVE:
  347. data = NULL;
  348. /*
  349. * We're called from user space, we can use _irq
  350. * rather then _irqsave
  351. */
  352. spin_lock_irq(&ffs->ev.waitq.lock);
  353. switch (ffs_setup_state_clear_cancelled(ffs)) {
  354. case FFS_SETUP_CANCELLED:
  355. ret = -EIDRM;
  356. goto done_spin;
  357. case FFS_NO_SETUP:
  358. ret = -ESRCH;
  359. goto done_spin;
  360. case FFS_SETUP_PENDING:
  361. break;
  362. }
  363. /* FFS_SETUP_PENDING */
  364. if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
  365. spin_unlock_irq(&ffs->ev.waitq.lock);
  366. ret = __ffs_ep0_stall(ffs);
  367. break;
  368. }
  369. /* FFS_SETUP_PENDING and not stall */
  370. len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
  371. spin_unlock_irq(&ffs->ev.waitq.lock);
  372. data = ffs_prepare_buffer(buf, len);
  373. if (IS_ERR(data)) {
  374. ret = PTR_ERR(data);
  375. break;
  376. }
  377. spin_lock_irq(&ffs->ev.waitq.lock);
  378. /*
  379. * We are guaranteed to be still in FFS_ACTIVE state
  380. * but the state of setup could have changed from
  381. * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
  382. * to check for that. If that happened we copied data
  383. * from user space in vain but it's unlikely.
  384. *
  385. * For sure we are not in FFS_NO_SETUP since this is
  386. * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
  387. * transition can be performed and it's protected by
  388. * mutex.
  389. */
  390. if (ffs_setup_state_clear_cancelled(ffs) ==
  391. FFS_SETUP_CANCELLED) {
  392. ret = -EIDRM;
  393. done_spin:
  394. spin_unlock_irq(&ffs->ev.waitq.lock);
  395. } else {
  396. /* unlocks spinlock */
  397. ret = __ffs_ep0_queue_wait(ffs, data, len);
  398. }
  399. kfree(data);
  400. break;
  401. default:
  402. ret = -EBADFD;
  403. break;
  404. }
  405. mutex_unlock(&ffs->mutex);
  406. return ret;
  407. }
  408. /* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
  409. static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
  410. size_t n)
  411. __releases(&ffs->ev.waitq.lock)
  412. {
  413. /*
  414. * n cannot be bigger than ffs->ev.count, which cannot be bigger than
  415. * size of ffs->ev.types array (which is four) so that's how much space
  416. * we reserve.
  417. */
  418. struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
  419. const size_t size = n * sizeof *events;
  420. unsigned i = 0;
  421. memset(events, 0, size);
  422. do {
  423. events[i].type = ffs->ev.types[i];
  424. if (events[i].type == FUNCTIONFS_SETUP) {
  425. events[i].u.setup = ffs->ev.setup;
  426. ffs->setup_state = FFS_SETUP_PENDING;
  427. }
  428. } while (++i < n);
  429. ffs->ev.count -= n;
  430. if (ffs->ev.count)
  431. memmove(ffs->ev.types, ffs->ev.types + n,
  432. ffs->ev.count * sizeof *ffs->ev.types);
  433. spin_unlock_irq(&ffs->ev.waitq.lock);
  434. mutex_unlock(&ffs->mutex);
  435. return copy_to_user(buf, events, size) ? -EFAULT : size;
  436. }
  437. static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
  438. size_t len, loff_t *ptr)
  439. {
  440. struct ffs_data *ffs = file->private_data;
  441. char *data = NULL;
  442. size_t n;
  443. int ret;
  444. /* Fast check if setup was canceled */
  445. if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
  446. return -EIDRM;
  447. /* Acquire mutex */
  448. ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
  449. if (ret < 0)
  450. return ret;
  451. /* Check state */
  452. if (ffs->state != FFS_ACTIVE) {
  453. ret = -EBADFD;
  454. goto done_mutex;
  455. }
  456. /*
  457. * We're called from user space, we can use _irq rather then
  458. * _irqsave
  459. */
  460. spin_lock_irq(&ffs->ev.waitq.lock);
  461. switch (ffs_setup_state_clear_cancelled(ffs)) {
  462. case FFS_SETUP_CANCELLED:
  463. ret = -EIDRM;
  464. break;
  465. case FFS_NO_SETUP:
  466. n = len / sizeof(struct usb_functionfs_event);
  467. if (!n) {
  468. ret = -EINVAL;
  469. break;
  470. }
  471. if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
  472. ret = -EAGAIN;
  473. break;
  474. }
  475. if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
  476. ffs->ev.count)) {
  477. ret = -EINTR;
  478. break;
  479. }
  480. /* unlocks spinlock */
  481. return __ffs_ep0_read_events(ffs, buf,
  482. min(n, (size_t)ffs->ev.count));
  483. case FFS_SETUP_PENDING:
  484. if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
  485. spin_unlock_irq(&ffs->ev.waitq.lock);
  486. ret = __ffs_ep0_stall(ffs);
  487. goto done_mutex;
  488. }
  489. len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
  490. spin_unlock_irq(&ffs->ev.waitq.lock);
  491. if (len) {
  492. data = kmalloc(len, GFP_KERNEL);
  493. if (!data) {
  494. ret = -ENOMEM;
  495. goto done_mutex;
  496. }
  497. }
  498. spin_lock_irq(&ffs->ev.waitq.lock);
  499. /* See ffs_ep0_write() */
  500. if (ffs_setup_state_clear_cancelled(ffs) ==
  501. FFS_SETUP_CANCELLED) {
  502. ret = -EIDRM;
  503. break;
  504. }
  505. /* unlocks spinlock */
  506. ret = __ffs_ep0_queue_wait(ffs, data, len);
  507. if ((ret > 0) && (copy_to_user(buf, data, len)))
  508. ret = -EFAULT;
  509. goto done_mutex;
  510. default:
  511. ret = -EBADFD;
  512. break;
  513. }
  514. spin_unlock_irq(&ffs->ev.waitq.lock);
  515. done_mutex:
  516. mutex_unlock(&ffs->mutex);
  517. kfree(data);
  518. return ret;
  519. }
  520. static int ffs_ep0_open(struct inode *inode, struct file *file)
  521. {
  522. struct ffs_data *ffs = inode->i_private;
  523. if (ffs->state == FFS_CLOSING)
  524. return -EBUSY;
  525. file->private_data = ffs;
  526. ffs_data_opened(ffs);
  527. return stream_open(inode, file);
  528. }
  529. static int ffs_ep0_release(struct inode *inode, struct file *file)
  530. {
  531. struct ffs_data *ffs = file->private_data;
  532. ffs_data_closed(ffs);
  533. return 0;
  534. }
  535. static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
  536. {
  537. struct ffs_data *ffs = file->private_data;
  538. struct usb_gadget *gadget = ffs->gadget;
  539. long ret;
  540. if (code == FUNCTIONFS_INTERFACE_REVMAP) {
  541. struct ffs_function *func = ffs->func;
  542. ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
  543. } else if (gadget && gadget->ops->ioctl) {
  544. ret = gadget->ops->ioctl(gadget, code, value);
  545. } else {
  546. ret = -ENOTTY;
  547. }
  548. return ret;
  549. }
  550. static __poll_t ffs_ep0_poll(struct file *file, poll_table *wait)
  551. {
  552. struct ffs_data *ffs = file->private_data;
  553. __poll_t mask = EPOLLWRNORM;
  554. int ret;
  555. poll_wait(file, &ffs->ev.waitq, wait);
  556. ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
  557. if (ret < 0)
  558. return mask;
  559. switch (ffs->state) {
  560. case FFS_READ_DESCRIPTORS:
  561. case FFS_READ_STRINGS:
  562. mask |= EPOLLOUT;
  563. break;
  564. case FFS_ACTIVE:
  565. switch (ffs->setup_state) {
  566. case FFS_NO_SETUP:
  567. if (ffs->ev.count)
  568. mask |= EPOLLIN;
  569. break;
  570. case FFS_SETUP_PENDING:
  571. case FFS_SETUP_CANCELLED:
  572. mask |= (EPOLLIN | EPOLLOUT);
  573. break;
  574. }
  575. break;
  576. case FFS_CLOSING:
  577. break;
  578. case FFS_DEACTIVATED:
  579. break;
  580. }
  581. mutex_unlock(&ffs->mutex);
  582. return mask;
  583. }
  584. static const struct file_operations ffs_ep0_operations = {
  585. .open = ffs_ep0_open,
  586. .write = ffs_ep0_write,
  587. .read = ffs_ep0_read,
  588. .release = ffs_ep0_release,
  589. .unlocked_ioctl = ffs_ep0_ioctl,
  590. .poll = ffs_ep0_poll,
  591. };
  592. /* "Normal" endpoints operations ********************************************/
  593. static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
  594. {
  595. struct ffs_io_data *io_data = req->context;
  596. if (req->status)
  597. io_data->status = req->status;
  598. else
  599. io_data->status = req->actual;
  600. complete(&io_data->done);
  601. }
  602. static ssize_t ffs_copy_to_iter(void *data, int data_len, struct iov_iter *iter)
  603. {
  604. ssize_t ret = copy_to_iter(data, data_len, iter);
  605. if (ret == data_len)
  606. return ret;
  607. if (iov_iter_count(iter))
  608. return -EFAULT;
  609. /*
  610. * Dear user space developer!
  611. *
  612. * TL;DR: To stop getting below error message in your kernel log, change
  613. * user space code using functionfs to align read buffers to a max
  614. * packet size.
  615. *
  616. * Some UDCs (e.g. dwc3) require request sizes to be a multiple of a max
  617. * packet size. When unaligned buffer is passed to functionfs, it
  618. * internally uses a larger, aligned buffer so that such UDCs are happy.
  619. *
  620. * Unfortunately, this means that host may send more data than was
  621. * requested in read(2) system call. f_fs doesn’t know what to do with
  622. * that excess data so it simply drops it.
  623. *
  624. * Was the buffer aligned in the first place, no such problem would
  625. * happen.
  626. *
  627. * Data may be dropped only in AIO reads. Synchronous reads are handled
  628. * by splitting a request into multiple parts. This splitting may still
  629. * be a problem though so it’s likely best to align the buffer
  630. * regardless of it being AIO or not..
  631. *
  632. * This only affects OUT endpoints, i.e. reading data with a read(2),
  633. * aio_read(2) etc. system calls. Writing data to an IN endpoint is not
  634. * affected.
  635. */
  636. pr_err("functionfs read size %d > requested size %zd, dropping excess data. "
  637. "Align read buffer size to max packet size to avoid the problem.\n",
  638. data_len, ret);
  639. return ret;
  640. }
  641. /*
  642. * allocate a virtually contiguous buffer and create a scatterlist describing it
  643. * @sg_table - pointer to a place to be filled with sg_table contents
  644. * @size - required buffer size
  645. */
  646. static void *ffs_build_sg_list(struct sg_table *sgt, size_t sz)
  647. {
  648. struct page **pages;
  649. void *vaddr, *ptr;
  650. unsigned int n_pages;
  651. int i;
  652. vaddr = vmalloc(sz);
  653. if (!vaddr)
  654. return NULL;
  655. n_pages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
  656. pages = kvmalloc_array(n_pages, sizeof(struct page *), GFP_KERNEL);
  657. if (!pages) {
  658. vfree(vaddr);
  659. return NULL;
  660. }
  661. for (i = 0, ptr = vaddr; i < n_pages; ++i, ptr += PAGE_SIZE)
  662. pages[i] = vmalloc_to_page(ptr);
  663. if (sg_alloc_table_from_pages(sgt, pages, n_pages, 0, sz, GFP_KERNEL)) {
  664. kvfree(pages);
  665. vfree(vaddr);
  666. return NULL;
  667. }
  668. kvfree(pages);
  669. return vaddr;
  670. }
  671. static inline void *ffs_alloc_buffer(struct ffs_io_data *io_data,
  672. size_t data_len)
  673. {
  674. if (io_data->use_sg)
  675. return ffs_build_sg_list(&io_data->sgt, data_len);
  676. return kmalloc(data_len, GFP_KERNEL);
  677. }
  678. static inline void ffs_free_buffer(struct ffs_io_data *io_data)
  679. {
  680. if (!io_data->buf)
  681. return;
  682. if (io_data->use_sg) {
  683. sg_free_table(&io_data->sgt);
  684. vfree(io_data->buf);
  685. } else {
  686. kfree(io_data->buf);
  687. }
  688. }
  689. static void ffs_user_copy_worker(struct work_struct *work)
  690. {
  691. struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
  692. work);
  693. int ret = io_data->status;
  694. bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;
  695. unsigned long flags;
  696. if (io_data->read && ret > 0) {
  697. kthread_use_mm(io_data->mm);
  698. ret = ffs_copy_to_iter(io_data->buf, ret, &io_data->data);
  699. kthread_unuse_mm(io_data->mm);
  700. }
  701. io_data->kiocb->ki_complete(io_data->kiocb, ret);
  702. if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)
  703. eventfd_signal(io_data->ffs->ffs_eventfd);
  704. spin_lock_irqsave(&io_data->ffs->eps_lock, flags);
  705. usb_ep_free_request(io_data->ep, io_data->req);
  706. io_data->req = NULL;
  707. spin_unlock_irqrestore(&io_data->ffs->eps_lock, flags);
  708. if (io_data->read)
  709. kfree(io_data->to_free);
  710. ffs_free_buffer(io_data);
  711. kfree(io_data);
  712. }
  713. static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
  714. struct usb_request *req)
  715. {
  716. struct ffs_io_data *io_data = req->context;
  717. struct ffs_data *ffs = io_data->ffs;
  718. io_data->status = req->status ? req->status : req->actual;
  719. INIT_WORK(&io_data->work, ffs_user_copy_worker);
  720. queue_work(ffs->io_completion_wq, &io_data->work);
  721. }
  722. static void __ffs_epfile_read_buffer_free(struct ffs_epfile *epfile)
  723. {
  724. /*
  725. * See comment in struct ffs_epfile for full read_buffer pointer
  726. * synchronisation story.
  727. */
  728. struct ffs_buffer *buf = xchg(&epfile->read_buffer, READ_BUFFER_DROP);
  729. if (buf && buf != READ_BUFFER_DROP)
  730. kfree(buf);
  731. }
  732. /* Assumes epfile->mutex is held. */
  733. static ssize_t __ffs_epfile_read_buffered(struct ffs_epfile *epfile,
  734. struct iov_iter *iter)
  735. {
  736. /*
  737. * Null out epfile->read_buffer so ffs_func_eps_disable does not free
  738. * the buffer while we are using it. See comment in struct ffs_epfile
  739. * for full read_buffer pointer synchronisation story.
  740. */
  741. struct ffs_buffer *buf = xchg(&epfile->read_buffer, NULL);
  742. ssize_t ret;
  743. if (!buf || buf == READ_BUFFER_DROP)
  744. return 0;
  745. ret = copy_to_iter(buf->data, buf->length, iter);
  746. if (buf->length == ret) {
  747. kfree(buf);
  748. return ret;
  749. }
  750. if (iov_iter_count(iter)) {
  751. ret = -EFAULT;
  752. } else {
  753. buf->length -= ret;
  754. buf->data += ret;
  755. }
  756. if (cmpxchg(&epfile->read_buffer, NULL, buf))
  757. kfree(buf);
  758. return ret;
  759. }
  760. /* Assumes epfile->mutex is held. */
  761. static ssize_t __ffs_epfile_read_data(struct ffs_epfile *epfile,
  762. void *data, int data_len,
  763. struct iov_iter *iter)
  764. {
  765. struct ffs_buffer *buf;
  766. ssize_t ret = copy_to_iter(data, data_len, iter);
  767. if (data_len == ret)
  768. return ret;
  769. if (iov_iter_count(iter))
  770. return -EFAULT;
  771. /* See ffs_copy_to_iter for more context. */
  772. pr_warn("functionfs read size %d > requested size %zd, splitting request into multiple reads.",
  773. data_len, ret);
  774. data_len -= ret;
  775. buf = kmalloc(struct_size(buf, storage, data_len), GFP_KERNEL);
  776. if (!buf)
  777. return -ENOMEM;
  778. buf->length = data_len;
  779. buf->data = buf->storage;
  780. memcpy(buf->storage, data + ret, flex_array_size(buf, storage, data_len));
  781. /*
  782. * At this point read_buffer is NULL or READ_BUFFER_DROP (if
  783. * ffs_func_eps_disable has been called in the meanwhile). See comment
  784. * in struct ffs_epfile for full read_buffer pointer synchronisation
  785. * story.
  786. */
  787. if (cmpxchg(&epfile->read_buffer, NULL, buf))
  788. kfree(buf);
  789. return ret;
  790. }
  791. static struct ffs_ep *ffs_epfile_wait_ep(struct file *file)
  792. {
  793. struct ffs_epfile *epfile = file->private_data;
  794. struct ffs_ep *ep;
  795. int ret;
  796. /* Wait for endpoint to be enabled */
  797. ep = epfile->ep;
  798. if (!ep) {
  799. if (file->f_flags & O_NONBLOCK)
  800. return ERR_PTR(-EAGAIN);
  801. ret = wait_event_interruptible(
  802. epfile->ffs->wait, (ep = epfile->ep));
  803. if (ret)
  804. return ERR_PTR(-EINTR);
  805. }
  806. return ep;
  807. }
  808. static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
  809. {
  810. struct ffs_epfile *epfile = file->private_data;
  811. struct usb_request *req;
  812. struct ffs_ep *ep;
  813. char *data = NULL;
  814. ssize_t ret, data_len = -EINVAL;
  815. int halt;
  816. /* Are we still active? */
  817. if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
  818. return -ENODEV;
  819. ep = ffs_epfile_wait_ep(file);
  820. if (IS_ERR(ep))
  821. return PTR_ERR(ep);
  822. /* Do we halt? */
  823. halt = (!io_data->read == !epfile->in);
  824. if (halt && epfile->isoc)
  825. return -EINVAL;
  826. /* We will be using request and read_buffer */
  827. ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
  828. if (ret)
  829. goto error;
  830. /* Allocate & copy */
  831. if (!halt) {
  832. struct usb_gadget *gadget;
  833. /*
  834. * Do we have buffered data from previous partial read? Check
  835. * that for synchronous case only because we do not have
  836. * facility to ‘wake up’ a pending asynchronous read and push
  837. * buffered data to it which we would need to make things behave
  838. * consistently.
  839. */
  840. if (!io_data->aio && io_data->read) {
  841. ret = __ffs_epfile_read_buffered(epfile, &io_data->data);
  842. if (ret)
  843. goto error_mutex;
  844. }
  845. /*
  846. * if we _do_ wait above, the epfile->ffs->gadget might be NULL
  847. * before the waiting completes, so do not assign to 'gadget'
  848. * earlier
  849. */
  850. gadget = epfile->ffs->gadget;
  851. spin_lock_irq(&epfile->ffs->eps_lock);
  852. /* In the meantime, endpoint got disabled or changed. */
  853. if (epfile->ep != ep) {
  854. ret = -ESHUTDOWN;
  855. goto error_lock;
  856. }
  857. data_len = iov_iter_count(&io_data->data);
  858. /*
  859. * Controller may require buffer size to be aligned to
  860. * maxpacketsize of an out endpoint.
  861. */
  862. if (io_data->read)
  863. data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
  864. io_data->use_sg = gadget->sg_supported && data_len > PAGE_SIZE;
  865. spin_unlock_irq(&epfile->ffs->eps_lock);
  866. data = ffs_alloc_buffer(io_data, data_len);
  867. if (!data) {
  868. ret = -ENOMEM;
  869. goto error_mutex;
  870. }
  871. if (!io_data->read &&
  872. !copy_from_iter_full(data, data_len, &io_data->data)) {
  873. ret = -EFAULT;
  874. goto error_mutex;
  875. }
  876. }
  877. spin_lock_irq(&epfile->ffs->eps_lock);
  878. if (epfile->ep != ep) {
  879. /* In the meantime, endpoint got disabled or changed. */
  880. ret = -ESHUTDOWN;
  881. } else if (halt) {
  882. ret = usb_ep_set_halt(ep->ep);
  883. if (!ret)
  884. ret = -EBADMSG;
  885. } else if (data_len == -EINVAL) {
  886. /*
  887. * Sanity Check: even though data_len can't be used
  888. * uninitialized at the time I write this comment, some
  889. * compilers complain about this situation.
  890. * In order to keep the code clean from warnings, data_len is
  891. * being initialized to -EINVAL during its declaration, which
  892. * means we can't rely on compiler anymore to warn no future
  893. * changes won't result in data_len being used uninitialized.
  894. * For such reason, we're adding this redundant sanity check
  895. * here.
  896. */
  897. WARN(1, "%s: data_len == -EINVAL\n", __func__);
  898. ret = -EINVAL;
  899. } else if (!io_data->aio) {
  900. bool interrupted = false;
  901. req = ep->req;
  902. if (io_data->use_sg) {
  903. req->buf = NULL;
  904. req->sg = io_data->sgt.sgl;
  905. req->num_sgs = io_data->sgt.nents;
  906. } else {
  907. req->buf = data;
  908. req->num_sgs = 0;
  909. }
  910. req->length = data_len;
  911. io_data->buf = data;
  912. init_completion(&io_data->done);
  913. req->context = io_data;
  914. req->complete = ffs_epfile_io_complete;
  915. ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
  916. if (ret < 0)
  917. goto error_lock;
  918. spin_unlock_irq(&epfile->ffs->eps_lock);
  919. if (wait_for_completion_interruptible(&io_data->done)) {
  920. spin_lock_irq(&epfile->ffs->eps_lock);
  921. if (epfile->ep != ep) {
  922. ret = -ESHUTDOWN;
  923. goto error_lock;
  924. }
  925. /*
  926. * To avoid race condition with ffs_epfile_io_complete,
  927. * dequeue the request first then check
  928. * status. usb_ep_dequeue API should guarantee no race
  929. * condition with req->complete callback.
  930. */
  931. usb_ep_dequeue(ep->ep, req);
  932. spin_unlock_irq(&epfile->ffs->eps_lock);
  933. wait_for_completion(&io_data->done);
  934. interrupted = io_data->status < 0;
  935. }
  936. if (interrupted)
  937. ret = -EINTR;
  938. else if (io_data->read && io_data->status > 0)
  939. ret = __ffs_epfile_read_data(epfile, data, io_data->status,
  940. &io_data->data);
  941. else
  942. ret = io_data->status;
  943. goto error_mutex;
  944. } else if (!(req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC))) {
  945. ret = -ENOMEM;
  946. } else {
  947. if (io_data->use_sg) {
  948. req->buf = NULL;
  949. req->sg = io_data->sgt.sgl;
  950. req->num_sgs = io_data->sgt.nents;
  951. } else {
  952. req->buf = data;
  953. req->num_sgs = 0;
  954. }
  955. req->length = data_len;
  956. io_data->buf = data;
  957. io_data->ep = ep->ep;
  958. io_data->req = req;
  959. io_data->ffs = epfile->ffs;
  960. req->context = io_data;
  961. req->complete = ffs_epfile_async_io_complete;
  962. ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
  963. if (ret) {
  964. io_data->req = NULL;
  965. usb_ep_free_request(ep->ep, req);
  966. goto error_lock;
  967. }
  968. ret = -EIOCBQUEUED;
  969. /*
  970. * Do not kfree the buffer in this function. It will be freed
  971. * by ffs_user_copy_worker.
  972. */
  973. data = NULL;
  974. }
  975. error_lock:
  976. spin_unlock_irq(&epfile->ffs->eps_lock);
  977. error_mutex:
  978. mutex_unlock(&epfile->mutex);
  979. error:
  980. if (ret != -EIOCBQUEUED) /* don't free if there is iocb queued */
  981. ffs_free_buffer(io_data);
  982. return ret;
  983. }
  984. static int
  985. ffs_epfile_open(struct inode *inode, struct file *file)
  986. {
  987. struct ffs_epfile *epfile = inode->i_private;
  988. if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
  989. return -ENODEV;
  990. file->private_data = epfile;
  991. ffs_data_opened(epfile->ffs);
  992. return stream_open(inode, file);
  993. }
  994. static int ffs_aio_cancel(struct kiocb *kiocb)
  995. {
  996. struct ffs_io_data *io_data = kiocb->private;
  997. struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
  998. unsigned long flags;
  999. int value;
  1000. spin_lock_irqsave(&epfile->ffs->eps_lock, flags);
  1001. if (io_data && io_data->ep && io_data->req)
  1002. value = usb_ep_dequeue(io_data->ep, io_data->req);
  1003. else
  1004. value = -EINVAL;
  1005. spin_unlock_irqrestore(&epfile->ffs->eps_lock, flags);
  1006. return value;
  1007. }
  1008. static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
  1009. {
  1010. struct ffs_io_data io_data, *p = &io_data;
  1011. ssize_t res;
  1012. if (!is_sync_kiocb(kiocb)) {
  1013. p = kzalloc(sizeof(io_data), GFP_KERNEL);
  1014. if (!p)
  1015. return -ENOMEM;
  1016. p->aio = true;
  1017. } else {
  1018. memset(p, 0, sizeof(*p));
  1019. p->aio = false;
  1020. }
  1021. p->read = false;
  1022. p->kiocb = kiocb;
  1023. p->data = *from;
  1024. p->mm = current->mm;
  1025. kiocb->private = p;
  1026. if (p->aio)
  1027. kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
  1028. res = ffs_epfile_io(kiocb->ki_filp, p);
  1029. if (res == -EIOCBQUEUED)
  1030. return res;
  1031. if (p->aio)
  1032. kfree(p);
  1033. else
  1034. *from = p->data;
  1035. return res;
  1036. }
  1037. static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
  1038. {
  1039. struct ffs_io_data io_data, *p = &io_data;
  1040. ssize_t res;
  1041. if (!is_sync_kiocb(kiocb)) {
  1042. p = kzalloc(sizeof(io_data), GFP_KERNEL);
  1043. if (!p)
  1044. return -ENOMEM;
  1045. p->aio = true;
  1046. } else {
  1047. memset(p, 0, sizeof(*p));
  1048. p->aio = false;
  1049. }
  1050. p->read = true;
  1051. p->kiocb = kiocb;
  1052. if (p->aio) {
  1053. p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
  1054. if (!iter_is_ubuf(&p->data) && !p->to_free) {
  1055. kfree(p);
  1056. return -ENOMEM;
  1057. }
  1058. } else {
  1059. p->data = *to;
  1060. p->to_free = NULL;
  1061. }
  1062. p->mm = current->mm;
  1063. kiocb->private = p;
  1064. if (p->aio)
  1065. kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
  1066. res = ffs_epfile_io(kiocb->ki_filp, p);
  1067. if (res == -EIOCBQUEUED)
  1068. return res;
  1069. if (p->aio) {
  1070. kfree(p->to_free);
  1071. kfree(p);
  1072. } else {
  1073. *to = p->data;
  1074. }
  1075. return res;
  1076. }
  1077. static void ffs_dmabuf_release(struct kref *ref)
  1078. {
  1079. struct ffs_dmabuf_priv *priv = container_of(ref, struct ffs_dmabuf_priv, ref);
  1080. struct dma_buf_attachment *attach = priv->attach;
  1081. struct dma_buf *dmabuf = attach->dmabuf;
  1082. pr_vdebug("FFS DMABUF release\n");
  1083. dma_resv_lock(dmabuf->resv, NULL);
  1084. dma_buf_unmap_attachment(attach, priv->sgt, priv->dir);
  1085. dma_resv_unlock(dmabuf->resv);
  1086. dma_buf_detach(attach->dmabuf, attach);
  1087. dma_buf_put(dmabuf);
  1088. kfree(priv);
  1089. }
  1090. static void ffs_dmabuf_get(struct dma_buf_attachment *attach)
  1091. {
  1092. struct ffs_dmabuf_priv *priv = attach->importer_priv;
  1093. kref_get(&priv->ref);
  1094. }
  1095. static void ffs_dmabuf_put(struct dma_buf_attachment *attach)
  1096. {
  1097. struct ffs_dmabuf_priv *priv = attach->importer_priv;
  1098. kref_put(&priv->ref, ffs_dmabuf_release);
  1099. }
  1100. static int
  1101. ffs_epfile_release(struct inode *inode, struct file *file)
  1102. {
  1103. struct ffs_epfile *epfile = inode->i_private;
  1104. struct ffs_dmabuf_priv *priv, *tmp;
  1105. struct ffs_data *ffs = epfile->ffs;
  1106. mutex_lock(&epfile->dmabufs_mutex);
  1107. /* Close all attached DMABUFs */
  1108. list_for_each_entry_safe(priv, tmp, &epfile->dmabufs, entry) {
  1109. /* Cancel any pending transfer */
  1110. spin_lock_irq(&ffs->eps_lock);
  1111. if (priv->ep && priv->req)
  1112. usb_ep_dequeue(priv->ep, priv->req);
  1113. spin_unlock_irq(&ffs->eps_lock);
  1114. list_del(&priv->entry);
  1115. ffs_dmabuf_put(priv->attach);
  1116. }
  1117. mutex_unlock(&epfile->dmabufs_mutex);
  1118. __ffs_epfile_read_buffer_free(epfile);
  1119. ffs_data_closed(epfile->ffs);
  1120. return 0;
  1121. }
  1122. static void ffs_dmabuf_cleanup(struct work_struct *work)
  1123. {
  1124. struct ffs_dma_fence *dma_fence =
  1125. container_of(work, struct ffs_dma_fence, work);
  1126. struct ffs_dmabuf_priv *priv = dma_fence->priv;
  1127. struct dma_buf_attachment *attach = priv->attach;
  1128. struct dma_fence *fence = &dma_fence->base;
  1129. ffs_dmabuf_put(attach);
  1130. dma_fence_put(fence);
  1131. }
  1132. static void ffs_dmabuf_signal_done(struct ffs_dma_fence *dma_fence, int ret)
  1133. {
  1134. struct ffs_dmabuf_priv *priv = dma_fence->priv;
  1135. struct dma_fence *fence = &dma_fence->base;
  1136. bool cookie = dma_fence_begin_signalling();
  1137. dma_fence_get(fence);
  1138. fence->error = ret;
  1139. dma_fence_signal(fence);
  1140. dma_fence_end_signalling(cookie);
  1141. /*
  1142. * The fence will be unref'd in ffs_dmabuf_cleanup.
  1143. * It can't be done here, as the unref functions might try to lock
  1144. * the resv object, which would deadlock.
  1145. */
  1146. INIT_WORK(&dma_fence->work, ffs_dmabuf_cleanup);
  1147. queue_work(priv->ffs->io_completion_wq, &dma_fence->work);
  1148. }
  1149. static void ffs_epfile_dmabuf_io_complete(struct usb_ep *ep,
  1150. struct usb_request *req)
  1151. {
  1152. pr_vdebug("FFS: DMABUF transfer complete, status=%d\n", req->status);
  1153. ffs_dmabuf_signal_done(req->context, req->status);
  1154. usb_ep_free_request(ep, req);
  1155. }
  1156. static const char *ffs_dmabuf_get_driver_name(struct dma_fence *fence)
  1157. {
  1158. return "functionfs";
  1159. }
  1160. static const char *ffs_dmabuf_get_timeline_name(struct dma_fence *fence)
  1161. {
  1162. return "";
  1163. }
  1164. static void ffs_dmabuf_fence_release(struct dma_fence *fence)
  1165. {
  1166. struct ffs_dma_fence *dma_fence =
  1167. container_of(fence, struct ffs_dma_fence, base);
  1168. kfree(dma_fence);
  1169. }
  1170. static const struct dma_fence_ops ffs_dmabuf_fence_ops = {
  1171. .get_driver_name = ffs_dmabuf_get_driver_name,
  1172. .get_timeline_name = ffs_dmabuf_get_timeline_name,
  1173. .release = ffs_dmabuf_fence_release,
  1174. };
  1175. static int ffs_dma_resv_lock(struct dma_buf *dmabuf, bool nonblock)
  1176. {
  1177. if (!nonblock)
  1178. return dma_resv_lock_interruptible(dmabuf->resv, NULL);
  1179. if (!dma_resv_trylock(dmabuf->resv))
  1180. return -EBUSY;
  1181. return 0;
  1182. }
  1183. static struct dma_buf_attachment *
  1184. ffs_dmabuf_find_attachment(struct ffs_epfile *epfile, struct dma_buf *dmabuf)
  1185. {
  1186. struct device *dev = epfile->ffs->gadget->dev.parent;
  1187. struct dma_buf_attachment *attach = NULL;
  1188. struct ffs_dmabuf_priv *priv;
  1189. mutex_lock(&epfile->dmabufs_mutex);
  1190. list_for_each_entry(priv, &epfile->dmabufs, entry) {
  1191. if (priv->attach->dev == dev
  1192. && priv->attach->dmabuf == dmabuf) {
  1193. attach = priv->attach;
  1194. break;
  1195. }
  1196. }
  1197. if (attach)
  1198. ffs_dmabuf_get(attach);
  1199. mutex_unlock(&epfile->dmabufs_mutex);
  1200. return attach ?: ERR_PTR(-EPERM);
  1201. }
  1202. static int ffs_dmabuf_attach(struct file *file, int fd)
  1203. {
  1204. bool nonblock = file->f_flags & O_NONBLOCK;
  1205. struct ffs_epfile *epfile = file->private_data;
  1206. struct usb_gadget *gadget = epfile->ffs->gadget;
  1207. struct dma_buf_attachment *attach;
  1208. struct ffs_dmabuf_priv *priv;
  1209. enum dma_data_direction dir;
  1210. struct sg_table *sg_table;
  1211. struct dma_buf *dmabuf;
  1212. int err;
  1213. if (!gadget || !gadget->sg_supported)
  1214. return -EPERM;
  1215. dmabuf = dma_buf_get(fd);
  1216. if (IS_ERR(dmabuf))
  1217. return PTR_ERR(dmabuf);
  1218. attach = dma_buf_attach(dmabuf, gadget->dev.parent);
  1219. if (IS_ERR(attach)) {
  1220. err = PTR_ERR(attach);
  1221. goto err_dmabuf_put;
  1222. }
  1223. priv = kzalloc(sizeof(*priv), GFP_KERNEL);
  1224. if (!priv) {
  1225. err = -ENOMEM;
  1226. goto err_dmabuf_detach;
  1227. }
  1228. dir = epfile->in ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
  1229. err = ffs_dma_resv_lock(dmabuf, nonblock);
  1230. if (err)
  1231. goto err_free_priv;
  1232. sg_table = dma_buf_map_attachment(attach, dir);
  1233. dma_resv_unlock(dmabuf->resv);
  1234. if (IS_ERR(sg_table)) {
  1235. err = PTR_ERR(sg_table);
  1236. goto err_free_priv;
  1237. }
  1238. attach->importer_priv = priv;
  1239. priv->sgt = sg_table;
  1240. priv->dir = dir;
  1241. priv->ffs = epfile->ffs;
  1242. priv->attach = attach;
  1243. spin_lock_init(&priv->lock);
  1244. kref_init(&priv->ref);
  1245. priv->context = dma_fence_context_alloc(1);
  1246. mutex_lock(&epfile->dmabufs_mutex);
  1247. list_add(&priv->entry, &epfile->dmabufs);
  1248. mutex_unlock(&epfile->dmabufs_mutex);
  1249. return 0;
  1250. err_free_priv:
  1251. kfree(priv);
  1252. err_dmabuf_detach:
  1253. dma_buf_detach(dmabuf, attach);
  1254. err_dmabuf_put:
  1255. dma_buf_put(dmabuf);
  1256. return err;
  1257. }
  1258. static int ffs_dmabuf_detach(struct file *file, int fd)
  1259. {
  1260. struct ffs_epfile *epfile = file->private_data;
  1261. struct ffs_data *ffs = epfile->ffs;
  1262. struct device *dev = ffs->gadget->dev.parent;
  1263. struct ffs_dmabuf_priv *priv, *tmp;
  1264. struct dma_buf *dmabuf;
  1265. int ret = -EPERM;
  1266. dmabuf = dma_buf_get(fd);
  1267. if (IS_ERR(dmabuf))
  1268. return PTR_ERR(dmabuf);
  1269. mutex_lock(&epfile->dmabufs_mutex);
  1270. list_for_each_entry_safe(priv, tmp, &epfile->dmabufs, entry) {
  1271. if (priv->attach->dev == dev
  1272. && priv->attach->dmabuf == dmabuf) {
  1273. /* Cancel any pending transfer */
  1274. spin_lock_irq(&ffs->eps_lock);
  1275. if (priv->ep && priv->req)
  1276. usb_ep_dequeue(priv->ep, priv->req);
  1277. spin_unlock_irq(&ffs->eps_lock);
  1278. list_del(&priv->entry);
  1279. /* Unref the reference from ffs_dmabuf_attach() */
  1280. ffs_dmabuf_put(priv->attach);
  1281. ret = 0;
  1282. break;
  1283. }
  1284. }
  1285. mutex_unlock(&epfile->dmabufs_mutex);
  1286. dma_buf_put(dmabuf);
  1287. return ret;
  1288. }
  1289. static int ffs_dmabuf_transfer(struct file *file,
  1290. const struct usb_ffs_dmabuf_transfer_req *req)
  1291. {
  1292. bool nonblock = file->f_flags & O_NONBLOCK;
  1293. struct ffs_epfile *epfile = file->private_data;
  1294. struct dma_buf_attachment *attach;
  1295. struct ffs_dmabuf_priv *priv;
  1296. struct ffs_dma_fence *fence;
  1297. struct usb_request *usb_req;
  1298. enum dma_resv_usage resv_dir;
  1299. struct dma_buf *dmabuf;
  1300. unsigned long timeout;
  1301. struct ffs_ep *ep;
  1302. bool cookie;
  1303. u32 seqno;
  1304. long retl;
  1305. int ret;
  1306. if (req->flags & ~USB_FFS_DMABUF_TRANSFER_MASK)
  1307. return -EINVAL;
  1308. dmabuf = dma_buf_get(req->fd);
  1309. if (IS_ERR(dmabuf))
  1310. return PTR_ERR(dmabuf);
  1311. if (req->length > dmabuf->size || req->length == 0) {
  1312. ret = -EINVAL;
  1313. goto err_dmabuf_put;
  1314. }
  1315. attach = ffs_dmabuf_find_attachment(epfile, dmabuf);
  1316. if (IS_ERR(attach)) {
  1317. ret = PTR_ERR(attach);
  1318. goto err_dmabuf_put;
  1319. }
  1320. priv = attach->importer_priv;
  1321. ep = ffs_epfile_wait_ep(file);
  1322. if (IS_ERR(ep)) {
  1323. ret = PTR_ERR(ep);
  1324. goto err_attachment_put;
  1325. }
  1326. ret = ffs_dma_resv_lock(dmabuf, nonblock);
  1327. if (ret)
  1328. goto err_attachment_put;
  1329. /* Make sure we don't have writers */
  1330. timeout = nonblock ? 0 : msecs_to_jiffies(DMABUF_ENQUEUE_TIMEOUT_MS);
  1331. retl = dma_resv_wait_timeout(dmabuf->resv,
  1332. dma_resv_usage_rw(epfile->in),
  1333. true, timeout);
  1334. if (retl == 0)
  1335. retl = -EBUSY;
  1336. if (retl < 0) {
  1337. ret = (int)retl;
  1338. goto err_resv_unlock;
  1339. }
  1340. ret = dma_resv_reserve_fences(dmabuf->resv, 1);
  1341. if (ret)
  1342. goto err_resv_unlock;
  1343. fence = kmalloc(sizeof(*fence), GFP_KERNEL);
  1344. if (!fence) {
  1345. ret = -ENOMEM;
  1346. goto err_resv_unlock;
  1347. }
  1348. fence->priv = priv;
  1349. spin_lock_irq(&epfile->ffs->eps_lock);
  1350. /* In the meantime, endpoint got disabled or changed. */
  1351. if (epfile->ep != ep) {
  1352. ret = -ESHUTDOWN;
  1353. goto err_fence_put;
  1354. }
  1355. usb_req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC);
  1356. if (!usb_req) {
  1357. ret = -ENOMEM;
  1358. goto err_fence_put;
  1359. }
  1360. /*
  1361. * usb_ep_queue() guarantees that all transfers are processed in the
  1362. * order they are enqueued, so we can use a simple incrementing
  1363. * sequence number for the dma_fence.
  1364. */
  1365. seqno = atomic_add_return(1, &epfile->seqno);
  1366. dma_fence_init(&fence->base, &ffs_dmabuf_fence_ops,
  1367. &priv->lock, priv->context, seqno);
  1368. resv_dir = epfile->in ? DMA_RESV_USAGE_WRITE : DMA_RESV_USAGE_READ;
  1369. dma_resv_add_fence(dmabuf->resv, &fence->base, resv_dir);
  1370. dma_resv_unlock(dmabuf->resv);
  1371. /* Now that the dma_fence is in place, queue the transfer. */
  1372. usb_req->length = req->length;
  1373. usb_req->buf = NULL;
  1374. usb_req->sg = priv->sgt->sgl;
  1375. usb_req->num_sgs = sg_nents_for_len(priv->sgt->sgl, req->length);
  1376. usb_req->sg_was_mapped = true;
  1377. usb_req->context = fence;
  1378. usb_req->complete = ffs_epfile_dmabuf_io_complete;
  1379. cookie = dma_fence_begin_signalling();
  1380. ret = usb_ep_queue(ep->ep, usb_req, GFP_ATOMIC);
  1381. dma_fence_end_signalling(cookie);
  1382. if (!ret) {
  1383. priv->req = usb_req;
  1384. priv->ep = ep->ep;
  1385. } else {
  1386. pr_warn("FFS: Failed to queue DMABUF: %d\n", ret);
  1387. ffs_dmabuf_signal_done(fence, ret);
  1388. usb_ep_free_request(ep->ep, usb_req);
  1389. }
  1390. spin_unlock_irq(&epfile->ffs->eps_lock);
  1391. dma_buf_put(dmabuf);
  1392. return ret;
  1393. err_fence_put:
  1394. spin_unlock_irq(&epfile->ffs->eps_lock);
  1395. dma_fence_put(&fence->base);
  1396. err_resv_unlock:
  1397. dma_resv_unlock(dmabuf->resv);
  1398. err_attachment_put:
  1399. ffs_dmabuf_put(attach);
  1400. err_dmabuf_put:
  1401. dma_buf_put(dmabuf);
  1402. return ret;
  1403. }
  1404. static long ffs_epfile_ioctl(struct file *file, unsigned code,
  1405. unsigned long value)
  1406. {
  1407. struct ffs_epfile *epfile = file->private_data;
  1408. struct ffs_ep *ep;
  1409. int ret;
  1410. if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
  1411. return -ENODEV;
  1412. switch (code) {
  1413. case FUNCTIONFS_DMABUF_ATTACH:
  1414. {
  1415. int fd;
  1416. if (copy_from_user(&fd, (void __user *)value, sizeof(fd))) {
  1417. ret = -EFAULT;
  1418. break;
  1419. }
  1420. return ffs_dmabuf_attach(file, fd);
  1421. }
  1422. case FUNCTIONFS_DMABUF_DETACH:
  1423. {
  1424. int fd;
  1425. if (copy_from_user(&fd, (void __user *)value, sizeof(fd))) {
  1426. ret = -EFAULT;
  1427. break;
  1428. }
  1429. return ffs_dmabuf_detach(file, fd);
  1430. }
  1431. case FUNCTIONFS_DMABUF_TRANSFER:
  1432. {
  1433. struct usb_ffs_dmabuf_transfer_req req;
  1434. if (copy_from_user(&req, (void __user *)value, sizeof(req))) {
  1435. ret = -EFAULT;
  1436. break;
  1437. }
  1438. return ffs_dmabuf_transfer(file, &req);
  1439. }
  1440. default:
  1441. break;
  1442. }
  1443. /* Wait for endpoint to be enabled */
  1444. ep = ffs_epfile_wait_ep(file);
  1445. if (IS_ERR(ep))
  1446. return PTR_ERR(ep);
  1447. spin_lock_irq(&epfile->ffs->eps_lock);
  1448. /* In the meantime, endpoint got disabled or changed. */
  1449. if (epfile->ep != ep) {
  1450. spin_unlock_irq(&epfile->ffs->eps_lock);
  1451. return -ESHUTDOWN;
  1452. }
  1453. switch (code) {
  1454. case FUNCTIONFS_FIFO_STATUS:
  1455. ret = usb_ep_fifo_status(epfile->ep->ep);
  1456. break;
  1457. case FUNCTIONFS_FIFO_FLUSH:
  1458. usb_ep_fifo_flush(epfile->ep->ep);
  1459. ret = 0;
  1460. break;
  1461. case FUNCTIONFS_CLEAR_HALT:
  1462. ret = usb_ep_clear_halt(epfile->ep->ep);
  1463. break;
  1464. case FUNCTIONFS_ENDPOINT_REVMAP:
  1465. ret = epfile->ep->num;
  1466. break;
  1467. case FUNCTIONFS_ENDPOINT_DESC:
  1468. {
  1469. int desc_idx;
  1470. struct usb_endpoint_descriptor desc1, *desc;
  1471. switch (epfile->ffs->gadget->speed) {
  1472. case USB_SPEED_SUPER:
  1473. case USB_SPEED_SUPER_PLUS:
  1474. desc_idx = 2;
  1475. break;
  1476. case USB_SPEED_HIGH:
  1477. desc_idx = 1;
  1478. break;
  1479. default:
  1480. desc_idx = 0;
  1481. }
  1482. desc = epfile->ep->descs[desc_idx];
  1483. memcpy(&desc1, desc, desc->bLength);
  1484. spin_unlock_irq(&epfile->ffs->eps_lock);
  1485. ret = copy_to_user((void __user *)value, &desc1, desc1.bLength);
  1486. if (ret)
  1487. ret = -EFAULT;
  1488. return ret;
  1489. }
  1490. default:
  1491. ret = -ENOTTY;
  1492. }
  1493. spin_unlock_irq(&epfile->ffs->eps_lock);
  1494. return ret;
  1495. }
  1496. static const struct file_operations ffs_epfile_operations = {
  1497. .open = ffs_epfile_open,
  1498. .write_iter = ffs_epfile_write_iter,
  1499. .read_iter = ffs_epfile_read_iter,
  1500. .release = ffs_epfile_release,
  1501. .unlocked_ioctl = ffs_epfile_ioctl,
  1502. .compat_ioctl = compat_ptr_ioctl,
  1503. };
  1504. /* File system and super block operations ***********************************/
  1505. /*
  1506. * Mounting the file system creates a controller file, used first for
  1507. * function configuration then later for event monitoring.
  1508. */
  1509. static struct inode *__must_check
  1510. ffs_sb_make_inode(struct super_block *sb, void *data,
  1511. const struct file_operations *fops,
  1512. const struct inode_operations *iops,
  1513. struct ffs_file_perms *perms)
  1514. {
  1515. struct inode *inode;
  1516. inode = new_inode(sb);
  1517. if (inode) {
  1518. struct timespec64 ts = inode_set_ctime_current(inode);
  1519. inode->i_ino = get_next_ino();
  1520. inode->i_mode = perms->mode;
  1521. inode->i_uid = perms->uid;
  1522. inode->i_gid = perms->gid;
  1523. inode_set_atime_to_ts(inode, ts);
  1524. inode_set_mtime_to_ts(inode, ts);
  1525. inode->i_private = data;
  1526. if (fops)
  1527. inode->i_fop = fops;
  1528. if (iops)
  1529. inode->i_op = iops;
  1530. }
  1531. return inode;
  1532. }
  1533. /* Create "regular" file */
  1534. static struct dentry *ffs_sb_create_file(struct super_block *sb,
  1535. const char *name, void *data,
  1536. const struct file_operations *fops)
  1537. {
  1538. struct ffs_data *ffs = sb->s_fs_info;
  1539. struct dentry *dentry;
  1540. struct inode *inode;
  1541. dentry = d_alloc_name(sb->s_root, name);
  1542. if (!dentry)
  1543. return NULL;
  1544. inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
  1545. if (!inode) {
  1546. dput(dentry);
  1547. return NULL;
  1548. }
  1549. d_add(dentry, inode);
  1550. return dentry;
  1551. }
  1552. /* Super block */
  1553. static const struct super_operations ffs_sb_operations = {
  1554. .statfs = simple_statfs,
  1555. .drop_inode = generic_delete_inode,
  1556. };
  1557. struct ffs_sb_fill_data {
  1558. struct ffs_file_perms perms;
  1559. umode_t root_mode;
  1560. const char *dev_name;
  1561. bool no_disconnect;
  1562. struct ffs_data *ffs_data;
  1563. };
  1564. static int ffs_sb_fill(struct super_block *sb, struct fs_context *fc)
  1565. {
  1566. struct ffs_sb_fill_data *data = fc->fs_private;
  1567. struct inode *inode;
  1568. struct ffs_data *ffs = data->ffs_data;
  1569. ffs->sb = sb;
  1570. data->ffs_data = NULL;
  1571. sb->s_fs_info = ffs;
  1572. sb->s_blocksize = PAGE_SIZE;
  1573. sb->s_blocksize_bits = PAGE_SHIFT;
  1574. sb->s_magic = FUNCTIONFS_MAGIC;
  1575. sb->s_op = &ffs_sb_operations;
  1576. sb->s_time_gran = 1;
  1577. /* Root inode */
  1578. data->perms.mode = data->root_mode;
  1579. inode = ffs_sb_make_inode(sb, NULL,
  1580. &simple_dir_operations,
  1581. &simple_dir_inode_operations,
  1582. &data->perms);
  1583. sb->s_root = d_make_root(inode);
  1584. if (!sb->s_root)
  1585. return -ENOMEM;
  1586. /* EP0 file */
  1587. if (!ffs_sb_create_file(sb, "ep0", ffs, &ffs_ep0_operations))
  1588. return -ENOMEM;
  1589. return 0;
  1590. }
  1591. enum {
  1592. Opt_no_disconnect,
  1593. Opt_rmode,
  1594. Opt_fmode,
  1595. Opt_mode,
  1596. Opt_uid,
  1597. Opt_gid,
  1598. };
  1599. static const struct fs_parameter_spec ffs_fs_fs_parameters[] = {
  1600. fsparam_bool ("no_disconnect", Opt_no_disconnect),
  1601. fsparam_u32 ("rmode", Opt_rmode),
  1602. fsparam_u32 ("fmode", Opt_fmode),
  1603. fsparam_u32 ("mode", Opt_mode),
  1604. fsparam_u32 ("uid", Opt_uid),
  1605. fsparam_u32 ("gid", Opt_gid),
  1606. {}
  1607. };
  1608. static int ffs_fs_parse_param(struct fs_context *fc, struct fs_parameter *param)
  1609. {
  1610. struct ffs_sb_fill_data *data = fc->fs_private;
  1611. struct fs_parse_result result;
  1612. int opt;
  1613. opt = fs_parse(fc, ffs_fs_fs_parameters, param, &result);
  1614. if (opt < 0)
  1615. return opt;
  1616. switch (opt) {
  1617. case Opt_no_disconnect:
  1618. data->no_disconnect = result.boolean;
  1619. break;
  1620. case Opt_rmode:
  1621. data->root_mode = (result.uint_32 & 0555) | S_IFDIR;
  1622. break;
  1623. case Opt_fmode:
  1624. data->perms.mode = (result.uint_32 & 0666) | S_IFREG;
  1625. break;
  1626. case Opt_mode:
  1627. data->root_mode = (result.uint_32 & 0555) | S_IFDIR;
  1628. data->perms.mode = (result.uint_32 & 0666) | S_IFREG;
  1629. break;
  1630. case Opt_uid:
  1631. data->perms.uid = make_kuid(current_user_ns(), result.uint_32);
  1632. if (!uid_valid(data->perms.uid))
  1633. goto unmapped_value;
  1634. break;
  1635. case Opt_gid:
  1636. data->perms.gid = make_kgid(current_user_ns(), result.uint_32);
  1637. if (!gid_valid(data->perms.gid))
  1638. goto unmapped_value;
  1639. break;
  1640. default:
  1641. return -ENOPARAM;
  1642. }
  1643. return 0;
  1644. unmapped_value:
  1645. return invalf(fc, "%s: unmapped value: %u", param->key, result.uint_32);
  1646. }
  1647. /*
  1648. * Set up the superblock for a mount.
  1649. */
  1650. static int ffs_fs_get_tree(struct fs_context *fc)
  1651. {
  1652. struct ffs_sb_fill_data *ctx = fc->fs_private;
  1653. struct ffs_data *ffs;
  1654. int ret;
  1655. if (!fc->source)
  1656. return invalf(fc, "No source specified");
  1657. ffs = ffs_data_new(fc->source);
  1658. if (!ffs)
  1659. return -ENOMEM;
  1660. ffs->file_perms = ctx->perms;
  1661. ffs->no_disconnect = ctx->no_disconnect;
  1662. ffs->dev_name = kstrdup(fc->source, GFP_KERNEL);
  1663. if (!ffs->dev_name) {
  1664. ffs_data_put(ffs);
  1665. return -ENOMEM;
  1666. }
  1667. ret = ffs_acquire_dev(ffs->dev_name, ffs);
  1668. if (ret) {
  1669. ffs_data_put(ffs);
  1670. return ret;
  1671. }
  1672. ctx->ffs_data = ffs;
  1673. return get_tree_nodev(fc, ffs_sb_fill);
  1674. }
  1675. static void ffs_fs_free_fc(struct fs_context *fc)
  1676. {
  1677. struct ffs_sb_fill_data *ctx = fc->fs_private;
  1678. if (ctx) {
  1679. if (ctx->ffs_data) {
  1680. ffs_data_put(ctx->ffs_data);
  1681. }
  1682. kfree(ctx);
  1683. }
  1684. }
  1685. static const struct fs_context_operations ffs_fs_context_ops = {
  1686. .free = ffs_fs_free_fc,
  1687. .parse_param = ffs_fs_parse_param,
  1688. .get_tree = ffs_fs_get_tree,
  1689. };
  1690. static int ffs_fs_init_fs_context(struct fs_context *fc)
  1691. {
  1692. struct ffs_sb_fill_data *ctx;
  1693. ctx = kzalloc(sizeof(struct ffs_sb_fill_data), GFP_KERNEL);
  1694. if (!ctx)
  1695. return -ENOMEM;
  1696. ctx->perms.mode = S_IFREG | 0600;
  1697. ctx->perms.uid = GLOBAL_ROOT_UID;
  1698. ctx->perms.gid = GLOBAL_ROOT_GID;
  1699. ctx->root_mode = S_IFDIR | 0500;
  1700. ctx->no_disconnect = false;
  1701. fc->fs_private = ctx;
  1702. fc->ops = &ffs_fs_context_ops;
  1703. return 0;
  1704. }
  1705. static void
  1706. ffs_fs_kill_sb(struct super_block *sb)
  1707. {
  1708. kill_litter_super(sb);
  1709. if (sb->s_fs_info)
  1710. ffs_data_closed(sb->s_fs_info);
  1711. }
  1712. static struct file_system_type ffs_fs_type = {
  1713. .owner = THIS_MODULE,
  1714. .name = "functionfs",
  1715. .init_fs_context = ffs_fs_init_fs_context,
  1716. .parameters = ffs_fs_fs_parameters,
  1717. .kill_sb = ffs_fs_kill_sb,
  1718. };
  1719. MODULE_ALIAS_FS("functionfs");
  1720. /* Driver's main init/cleanup functions *************************************/
  1721. static int functionfs_init(void)
  1722. {
  1723. int ret;
  1724. ret = register_filesystem(&ffs_fs_type);
  1725. if (!ret)
  1726. pr_info("file system registered\n");
  1727. else
  1728. pr_err("failed registering file system (%d)\n", ret);
  1729. return ret;
  1730. }
  1731. static void functionfs_cleanup(void)
  1732. {
  1733. pr_info("unloading\n");
  1734. unregister_filesystem(&ffs_fs_type);
  1735. }
  1736. /* ffs_data and ffs_function construction and destruction code **************/
  1737. static void ffs_data_clear(struct ffs_data *ffs);
  1738. static void ffs_data_reset(struct ffs_data *ffs);
  1739. static void ffs_data_get(struct ffs_data *ffs)
  1740. {
  1741. refcount_inc(&ffs->ref);
  1742. }
  1743. static void ffs_data_opened(struct ffs_data *ffs)
  1744. {
  1745. refcount_inc(&ffs->ref);
  1746. if (atomic_add_return(1, &ffs->opened) == 1 &&
  1747. ffs->state == FFS_DEACTIVATED) {
  1748. ffs->state = FFS_CLOSING;
  1749. ffs_data_reset(ffs);
  1750. }
  1751. }
  1752. static void ffs_data_put(struct ffs_data *ffs)
  1753. {
  1754. if (refcount_dec_and_test(&ffs->ref)) {
  1755. pr_info("%s(): freeing\n", __func__);
  1756. ffs_data_clear(ffs);
  1757. ffs_release_dev(ffs->private_data);
  1758. BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
  1759. swait_active(&ffs->ep0req_completion.wait) ||
  1760. waitqueue_active(&ffs->wait));
  1761. destroy_workqueue(ffs->io_completion_wq);
  1762. kfree(ffs->dev_name);
  1763. kfree(ffs);
  1764. }
  1765. }
  1766. static void ffs_data_closed(struct ffs_data *ffs)
  1767. {
  1768. struct ffs_epfile *epfiles;
  1769. unsigned long flags;
  1770. if (atomic_dec_and_test(&ffs->opened)) {
  1771. if (ffs->no_disconnect) {
  1772. ffs->state = FFS_DEACTIVATED;
  1773. spin_lock_irqsave(&ffs->eps_lock, flags);
  1774. epfiles = ffs->epfiles;
  1775. ffs->epfiles = NULL;
  1776. spin_unlock_irqrestore(&ffs->eps_lock,
  1777. flags);
  1778. if (epfiles)
  1779. ffs_epfiles_destroy(epfiles,
  1780. ffs->eps_count);
  1781. if (ffs->setup_state == FFS_SETUP_PENDING)
  1782. __ffs_ep0_stall(ffs);
  1783. } else {
  1784. ffs->state = FFS_CLOSING;
  1785. ffs_data_reset(ffs);
  1786. }
  1787. }
  1788. if (atomic_read(&ffs->opened) < 0) {
  1789. ffs->state = FFS_CLOSING;
  1790. ffs_data_reset(ffs);
  1791. }
  1792. ffs_data_put(ffs);
  1793. }
  1794. static struct ffs_data *ffs_data_new(const char *dev_name)
  1795. {
  1796. struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
  1797. if (!ffs)
  1798. return NULL;
  1799. ffs->io_completion_wq = alloc_ordered_workqueue("%s", 0, dev_name);
  1800. if (!ffs->io_completion_wq) {
  1801. kfree(ffs);
  1802. return NULL;
  1803. }
  1804. refcount_set(&ffs->ref, 1);
  1805. atomic_set(&ffs->opened, 0);
  1806. ffs->state = FFS_READ_DESCRIPTORS;
  1807. mutex_init(&ffs->mutex);
  1808. spin_lock_init(&ffs->eps_lock);
  1809. init_waitqueue_head(&ffs->ev.waitq);
  1810. init_waitqueue_head(&ffs->wait);
  1811. init_completion(&ffs->ep0req_completion);
  1812. /* XXX REVISIT need to update it in some places, or do we? */
  1813. ffs->ev.can_stall = 1;
  1814. return ffs;
  1815. }
  1816. static void ffs_data_clear(struct ffs_data *ffs)
  1817. {
  1818. struct ffs_epfile *epfiles;
  1819. unsigned long flags;
  1820. ffs_closed(ffs);
  1821. BUG_ON(ffs->gadget);
  1822. spin_lock_irqsave(&ffs->eps_lock, flags);
  1823. epfiles = ffs->epfiles;
  1824. ffs->epfiles = NULL;
  1825. spin_unlock_irqrestore(&ffs->eps_lock, flags);
  1826. /*
  1827. * potential race possible between ffs_func_eps_disable
  1828. * & ffs_epfile_release therefore maintaining a local
  1829. * copy of epfile will save us from use-after-free.
  1830. */
  1831. if (epfiles) {
  1832. ffs_epfiles_destroy(epfiles, ffs->eps_count);
  1833. ffs->epfiles = NULL;
  1834. }
  1835. if (ffs->ffs_eventfd) {
  1836. eventfd_ctx_put(ffs->ffs_eventfd);
  1837. ffs->ffs_eventfd = NULL;
  1838. }
  1839. kfree(ffs->raw_descs_data);
  1840. kfree(ffs->raw_strings);
  1841. kfree(ffs->stringtabs);
  1842. }
  1843. static void ffs_data_reset(struct ffs_data *ffs)
  1844. {
  1845. ffs_data_clear(ffs);
  1846. ffs->raw_descs_data = NULL;
  1847. ffs->raw_descs = NULL;
  1848. ffs->raw_strings = NULL;
  1849. ffs->stringtabs = NULL;
  1850. ffs->raw_descs_length = 0;
  1851. ffs->fs_descs_count = 0;
  1852. ffs->hs_descs_count = 0;
  1853. ffs->ss_descs_count = 0;
  1854. ffs->strings_count = 0;
  1855. ffs->interfaces_count = 0;
  1856. ffs->eps_count = 0;
  1857. ffs->ev.count = 0;
  1858. ffs->state = FFS_READ_DESCRIPTORS;
  1859. ffs->setup_state = FFS_NO_SETUP;
  1860. ffs->flags = 0;
  1861. ffs->ms_os_descs_ext_prop_count = 0;
  1862. ffs->ms_os_descs_ext_prop_name_len = 0;
  1863. ffs->ms_os_descs_ext_prop_data_len = 0;
  1864. }
  1865. static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
  1866. {
  1867. struct usb_gadget_strings **lang;
  1868. int first_id;
  1869. if ((ffs->state != FFS_ACTIVE
  1870. || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
  1871. return -EBADFD;
  1872. first_id = usb_string_ids_n(cdev, ffs->strings_count);
  1873. if (first_id < 0)
  1874. return first_id;
  1875. ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
  1876. if (!ffs->ep0req)
  1877. return -ENOMEM;
  1878. ffs->ep0req->complete = ffs_ep0_complete;
  1879. ffs->ep0req->context = ffs;
  1880. lang = ffs->stringtabs;
  1881. if (lang) {
  1882. for (; *lang; ++lang) {
  1883. struct usb_string *str = (*lang)->strings;
  1884. int id = first_id;
  1885. for (; str->s; ++id, ++str)
  1886. str->id = id;
  1887. }
  1888. }
  1889. ffs->gadget = cdev->gadget;
  1890. ffs_data_get(ffs);
  1891. return 0;
  1892. }
  1893. static void functionfs_unbind(struct ffs_data *ffs)
  1894. {
  1895. if (!WARN_ON(!ffs->gadget)) {
  1896. /* dequeue before freeing ep0req */
  1897. usb_ep_dequeue(ffs->gadget->ep0, ffs->ep0req);
  1898. mutex_lock(&ffs->mutex);
  1899. usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
  1900. ffs->ep0req = NULL;
  1901. ffs->gadget = NULL;
  1902. clear_bit(FFS_FL_BOUND, &ffs->flags);
  1903. mutex_unlock(&ffs->mutex);
  1904. ffs_data_put(ffs);
  1905. }
  1906. }
  1907. static int ffs_epfiles_create(struct ffs_data *ffs)
  1908. {
  1909. struct ffs_epfile *epfile, *epfiles;
  1910. unsigned i, count;
  1911. count = ffs->eps_count;
  1912. epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
  1913. if (!epfiles)
  1914. return -ENOMEM;
  1915. epfile = epfiles;
  1916. for (i = 1; i <= count; ++i, ++epfile) {
  1917. epfile->ffs = ffs;
  1918. mutex_init(&epfile->mutex);
  1919. mutex_init(&epfile->dmabufs_mutex);
  1920. INIT_LIST_HEAD(&epfile->dmabufs);
  1921. if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
  1922. sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
  1923. else
  1924. sprintf(epfile->name, "ep%u", i);
  1925. epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
  1926. epfile,
  1927. &ffs_epfile_operations);
  1928. if (!epfile->dentry) {
  1929. ffs_epfiles_destroy(epfiles, i - 1);
  1930. return -ENOMEM;
  1931. }
  1932. }
  1933. ffs->epfiles = epfiles;
  1934. return 0;
  1935. }
  1936. static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
  1937. {
  1938. struct ffs_epfile *epfile = epfiles;
  1939. for (; count; --count, ++epfile) {
  1940. BUG_ON(mutex_is_locked(&epfile->mutex));
  1941. if (epfile->dentry) {
  1942. d_delete(epfile->dentry);
  1943. dput(epfile->dentry);
  1944. epfile->dentry = NULL;
  1945. }
  1946. }
  1947. kfree(epfiles);
  1948. }
  1949. static void ffs_func_eps_disable(struct ffs_function *func)
  1950. {
  1951. struct ffs_ep *ep;
  1952. struct ffs_epfile *epfile;
  1953. unsigned short count;
  1954. unsigned long flags;
  1955. spin_lock_irqsave(&func->ffs->eps_lock, flags);
  1956. count = func->ffs->eps_count;
  1957. epfile = func->ffs->epfiles;
  1958. ep = func->eps;
  1959. while (count--) {
  1960. /* pending requests get nuked */
  1961. if (ep->ep)
  1962. usb_ep_disable(ep->ep);
  1963. ++ep;
  1964. if (epfile) {
  1965. epfile->ep = NULL;
  1966. __ffs_epfile_read_buffer_free(epfile);
  1967. ++epfile;
  1968. }
  1969. }
  1970. spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
  1971. }
  1972. static int ffs_func_eps_enable(struct ffs_function *func)
  1973. {
  1974. struct ffs_data *ffs;
  1975. struct ffs_ep *ep;
  1976. struct ffs_epfile *epfile;
  1977. unsigned short count;
  1978. unsigned long flags;
  1979. int ret = 0;
  1980. spin_lock_irqsave(&func->ffs->eps_lock, flags);
  1981. ffs = func->ffs;
  1982. ep = func->eps;
  1983. epfile = ffs->epfiles;
  1984. count = ffs->eps_count;
  1985. while(count--) {
  1986. ep->ep->driver_data = ep;
  1987. ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
  1988. if (ret) {
  1989. pr_err("%s: config_ep_by_speed(%s) returned %d\n",
  1990. __func__, ep->ep->name, ret);
  1991. break;
  1992. }
  1993. ret = usb_ep_enable(ep->ep);
  1994. if (!ret) {
  1995. epfile->ep = ep;
  1996. epfile->in = usb_endpoint_dir_in(ep->ep->desc);
  1997. epfile->isoc = usb_endpoint_xfer_isoc(ep->ep->desc);
  1998. } else {
  1999. break;
  2000. }
  2001. ++ep;
  2002. ++epfile;
  2003. }
  2004. wake_up_interruptible(&ffs->wait);
  2005. spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
  2006. return ret;
  2007. }
  2008. /* Parsing and building descriptors and strings *****************************/
  2009. /*
  2010. * This validates if data pointed by data is a valid USB descriptor as
  2011. * well as record how many interfaces, endpoints and strings are
  2012. * required by given configuration. Returns address after the
  2013. * descriptor or NULL if data is invalid.
  2014. */
  2015. enum ffs_entity_type {
  2016. FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
  2017. };
  2018. enum ffs_os_desc_type {
  2019. FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
  2020. };
  2021. typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
  2022. u8 *valuep,
  2023. struct usb_descriptor_header *desc,
  2024. void *priv);
  2025. typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
  2026. struct usb_os_desc_header *h, void *data,
  2027. unsigned len, void *priv);
  2028. static int __must_check ffs_do_single_desc(char *data, unsigned len,
  2029. ffs_entity_callback entity,
  2030. void *priv, int *current_class, int *current_subclass)
  2031. {
  2032. struct usb_descriptor_header *_ds = (void *)data;
  2033. u8 length;
  2034. int ret;
  2035. /* At least two bytes are required: length and type */
  2036. if (len < 2) {
  2037. pr_vdebug("descriptor too short\n");
  2038. return -EINVAL;
  2039. }
  2040. /* If we have at least as many bytes as the descriptor takes? */
  2041. length = _ds->bLength;
  2042. if (len < length) {
  2043. pr_vdebug("descriptor longer then available data\n");
  2044. return -EINVAL;
  2045. }
  2046. #define __entity_check_INTERFACE(val) 1
  2047. #define __entity_check_STRING(val) (val)
  2048. #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
  2049. #define __entity(type, val) do { \
  2050. pr_vdebug("entity " #type "(%02x)\n", (val)); \
  2051. if (!__entity_check_ ##type(val)) { \
  2052. pr_vdebug("invalid entity's value\n"); \
  2053. return -EINVAL; \
  2054. } \
  2055. ret = entity(FFS_ ##type, &val, _ds, priv); \
  2056. if (ret < 0) { \
  2057. pr_debug("entity " #type "(%02x); ret = %d\n", \
  2058. (val), ret); \
  2059. return ret; \
  2060. } \
  2061. } while (0)
  2062. /* Parse descriptor depending on type. */
  2063. switch (_ds->bDescriptorType) {
  2064. case USB_DT_DEVICE:
  2065. case USB_DT_CONFIG:
  2066. case USB_DT_STRING:
  2067. case USB_DT_DEVICE_QUALIFIER:
  2068. /* function can't have any of those */
  2069. pr_vdebug("descriptor reserved for gadget: %d\n",
  2070. _ds->bDescriptorType);
  2071. return -EINVAL;
  2072. case USB_DT_INTERFACE: {
  2073. struct usb_interface_descriptor *ds = (void *)_ds;
  2074. pr_vdebug("interface descriptor\n");
  2075. if (length != sizeof *ds)
  2076. goto inv_length;
  2077. __entity(INTERFACE, ds->bInterfaceNumber);
  2078. if (ds->iInterface)
  2079. __entity(STRING, ds->iInterface);
  2080. *current_class = ds->bInterfaceClass;
  2081. *current_subclass = ds->bInterfaceSubClass;
  2082. }
  2083. break;
  2084. case USB_DT_ENDPOINT: {
  2085. struct usb_endpoint_descriptor *ds = (void *)_ds;
  2086. pr_vdebug("endpoint descriptor\n");
  2087. if (length != USB_DT_ENDPOINT_SIZE &&
  2088. length != USB_DT_ENDPOINT_AUDIO_SIZE)
  2089. goto inv_length;
  2090. __entity(ENDPOINT, ds->bEndpointAddress);
  2091. }
  2092. break;
  2093. case USB_TYPE_CLASS | 0x01:
  2094. if (*current_class == USB_INTERFACE_CLASS_HID) {
  2095. pr_vdebug("hid descriptor\n");
  2096. if (length != sizeof(struct hid_descriptor))
  2097. goto inv_length;
  2098. break;
  2099. } else if (*current_class == USB_INTERFACE_CLASS_CCID) {
  2100. pr_vdebug("ccid descriptor\n");
  2101. if (length != sizeof(struct ccid_descriptor))
  2102. goto inv_length;
  2103. break;
  2104. } else if (*current_class == USB_CLASS_APP_SPEC &&
  2105. *current_subclass == USB_SUBCLASS_DFU) {
  2106. pr_vdebug("dfu functional descriptor\n");
  2107. if (length != sizeof(struct usb_dfu_functional_descriptor))
  2108. goto inv_length;
  2109. break;
  2110. } else {
  2111. pr_vdebug("unknown descriptor: %d for class %d\n",
  2112. _ds->bDescriptorType, *current_class);
  2113. return -EINVAL;
  2114. }
  2115. case USB_DT_OTG:
  2116. if (length != sizeof(struct usb_otg_descriptor))
  2117. goto inv_length;
  2118. break;
  2119. case USB_DT_INTERFACE_ASSOCIATION: {
  2120. struct usb_interface_assoc_descriptor *ds = (void *)_ds;
  2121. pr_vdebug("interface association descriptor\n");
  2122. if (length != sizeof *ds)
  2123. goto inv_length;
  2124. if (ds->iFunction)
  2125. __entity(STRING, ds->iFunction);
  2126. }
  2127. break;
  2128. case USB_DT_SS_ENDPOINT_COMP:
  2129. pr_vdebug("EP SS companion descriptor\n");
  2130. if (length != sizeof(struct usb_ss_ep_comp_descriptor))
  2131. goto inv_length;
  2132. break;
  2133. case USB_DT_OTHER_SPEED_CONFIG:
  2134. case USB_DT_INTERFACE_POWER:
  2135. case USB_DT_DEBUG:
  2136. case USB_DT_SECURITY:
  2137. case USB_DT_CS_RADIO_CONTROL:
  2138. /* TODO */
  2139. pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
  2140. return -EINVAL;
  2141. default:
  2142. /* We should never be here */
  2143. pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
  2144. return -EINVAL;
  2145. inv_length:
  2146. pr_vdebug("invalid length: %d (descriptor %d)\n",
  2147. _ds->bLength, _ds->bDescriptorType);
  2148. return -EINVAL;
  2149. }
  2150. #undef __entity
  2151. #undef __entity_check_DESCRIPTOR
  2152. #undef __entity_check_INTERFACE
  2153. #undef __entity_check_STRING
  2154. #undef __entity_check_ENDPOINT
  2155. return length;
  2156. }
  2157. static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
  2158. ffs_entity_callback entity, void *priv)
  2159. {
  2160. const unsigned _len = len;
  2161. unsigned long num = 0;
  2162. int current_class = -1;
  2163. int current_subclass = -1;
  2164. for (;;) {
  2165. int ret;
  2166. if (num == count)
  2167. data = NULL;
  2168. /* Record "descriptor" entity */
  2169. ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
  2170. if (ret < 0) {
  2171. pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
  2172. num, ret);
  2173. return ret;
  2174. }
  2175. if (!data)
  2176. return _len - len;
  2177. ret = ffs_do_single_desc(data, len, entity, priv,
  2178. &current_class, &current_subclass);
  2179. if (ret < 0) {
  2180. pr_debug("%s returns %d\n", __func__, ret);
  2181. return ret;
  2182. }
  2183. len -= ret;
  2184. data += ret;
  2185. ++num;
  2186. }
  2187. }
  2188. static int __ffs_data_do_entity(enum ffs_entity_type type,
  2189. u8 *valuep, struct usb_descriptor_header *desc,
  2190. void *priv)
  2191. {
  2192. struct ffs_desc_helper *helper = priv;
  2193. struct usb_endpoint_descriptor *d;
  2194. switch (type) {
  2195. case FFS_DESCRIPTOR:
  2196. break;
  2197. case FFS_INTERFACE:
  2198. /*
  2199. * Interfaces are indexed from zero so if we
  2200. * encountered interface "n" then there are at least
  2201. * "n+1" interfaces.
  2202. */
  2203. if (*valuep >= helper->interfaces_count)
  2204. helper->interfaces_count = *valuep + 1;
  2205. break;
  2206. case FFS_STRING:
  2207. /*
  2208. * Strings are indexed from 1 (0 is reserved
  2209. * for languages list)
  2210. */
  2211. if (*valuep > helper->ffs->strings_count)
  2212. helper->ffs->strings_count = *valuep;
  2213. break;
  2214. case FFS_ENDPOINT:
  2215. d = (void *)desc;
  2216. helper->eps_count++;
  2217. if (helper->eps_count >= FFS_MAX_EPS_COUNT)
  2218. return -EINVAL;
  2219. /* Check if descriptors for any speed were already parsed */
  2220. if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
  2221. helper->ffs->eps_addrmap[helper->eps_count] =
  2222. d->bEndpointAddress;
  2223. else if (helper->ffs->eps_addrmap[helper->eps_count] !=
  2224. d->bEndpointAddress)
  2225. return -EINVAL;
  2226. break;
  2227. }
  2228. return 0;
  2229. }
  2230. static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
  2231. struct usb_os_desc_header *desc)
  2232. {
  2233. u16 bcd_version = le16_to_cpu(desc->bcdVersion);
  2234. u16 w_index = le16_to_cpu(desc->wIndex);
  2235. if (bcd_version == 0x1) {
  2236. pr_warn("bcdVersion must be 0x0100, stored in Little Endian order. "
  2237. "Userspace driver should be fixed, accepting 0x0001 for compatibility.\n");
  2238. } else if (bcd_version != 0x100) {
  2239. pr_vdebug("unsupported os descriptors version: 0x%x\n",
  2240. bcd_version);
  2241. return -EINVAL;
  2242. }
  2243. switch (w_index) {
  2244. case 0x4:
  2245. *next_type = FFS_OS_DESC_EXT_COMPAT;
  2246. break;
  2247. case 0x5:
  2248. *next_type = FFS_OS_DESC_EXT_PROP;
  2249. break;
  2250. default:
  2251. pr_vdebug("unsupported os descriptor type: %d", w_index);
  2252. return -EINVAL;
  2253. }
  2254. return sizeof(*desc);
  2255. }
  2256. /*
  2257. * Process all extended compatibility/extended property descriptors
  2258. * of a feature descriptor
  2259. */
  2260. static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
  2261. enum ffs_os_desc_type type,
  2262. u16 feature_count,
  2263. ffs_os_desc_callback entity,
  2264. void *priv,
  2265. struct usb_os_desc_header *h)
  2266. {
  2267. int ret;
  2268. const unsigned _len = len;
  2269. /* loop over all ext compat/ext prop descriptors */
  2270. while (feature_count--) {
  2271. ret = entity(type, h, data, len, priv);
  2272. if (ret < 0) {
  2273. pr_debug("bad OS descriptor, type: %d\n", type);
  2274. return ret;
  2275. }
  2276. data += ret;
  2277. len -= ret;
  2278. }
  2279. return _len - len;
  2280. }
  2281. /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
  2282. static int __must_check ffs_do_os_descs(unsigned count,
  2283. char *data, unsigned len,
  2284. ffs_os_desc_callback entity, void *priv)
  2285. {
  2286. const unsigned _len = len;
  2287. unsigned long num = 0;
  2288. for (num = 0; num < count; ++num) {
  2289. int ret;
  2290. enum ffs_os_desc_type type;
  2291. u16 feature_count;
  2292. struct usb_os_desc_header *desc = (void *)data;
  2293. if (len < sizeof(*desc))
  2294. return -EINVAL;
  2295. /*
  2296. * Record "descriptor" entity.
  2297. * Process dwLength, bcdVersion, wIndex, get b/wCount.
  2298. * Move the data pointer to the beginning of extended
  2299. * compatibilities proper or extended properties proper
  2300. * portions of the data
  2301. */
  2302. if (le32_to_cpu(desc->dwLength) > len)
  2303. return -EINVAL;
  2304. ret = __ffs_do_os_desc_header(&type, desc);
  2305. if (ret < 0) {
  2306. pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
  2307. num, ret);
  2308. return ret;
  2309. }
  2310. /*
  2311. * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
  2312. */
  2313. feature_count = le16_to_cpu(desc->wCount);
  2314. if (type == FFS_OS_DESC_EXT_COMPAT &&
  2315. (feature_count > 255 || desc->Reserved))
  2316. return -EINVAL;
  2317. len -= ret;
  2318. data += ret;
  2319. /*
  2320. * Process all function/property descriptors
  2321. * of this Feature Descriptor
  2322. */
  2323. ret = ffs_do_single_os_desc(data, len, type,
  2324. feature_count, entity, priv, desc);
  2325. if (ret < 0) {
  2326. pr_debug("%s returns %d\n", __func__, ret);
  2327. return ret;
  2328. }
  2329. len -= ret;
  2330. data += ret;
  2331. }
  2332. return _len - len;
  2333. }
  2334. /*
  2335. * Validate contents of the buffer from userspace related to OS descriptors.
  2336. */
  2337. static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
  2338. struct usb_os_desc_header *h, void *data,
  2339. unsigned len, void *priv)
  2340. {
  2341. struct ffs_data *ffs = priv;
  2342. u8 length;
  2343. switch (type) {
  2344. case FFS_OS_DESC_EXT_COMPAT: {
  2345. struct usb_ext_compat_desc *d = data;
  2346. int i;
  2347. if (len < sizeof(*d) ||
  2348. d->bFirstInterfaceNumber >= ffs->interfaces_count)
  2349. return -EINVAL;
  2350. if (d->Reserved1 != 1) {
  2351. /*
  2352. * According to the spec, Reserved1 must be set to 1
  2353. * but older kernels incorrectly rejected non-zero
  2354. * values. We fix it here to avoid returning EINVAL
  2355. * in response to values we used to accept.
  2356. */
  2357. pr_debug("usb_ext_compat_desc::Reserved1 forced to 1\n");
  2358. d->Reserved1 = 1;
  2359. }
  2360. for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
  2361. if (d->Reserved2[i])
  2362. return -EINVAL;
  2363. length = sizeof(struct usb_ext_compat_desc);
  2364. }
  2365. break;
  2366. case FFS_OS_DESC_EXT_PROP: {
  2367. struct usb_ext_prop_desc *d = data;
  2368. u32 type, pdl;
  2369. u16 pnl;
  2370. if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
  2371. return -EINVAL;
  2372. length = le32_to_cpu(d->dwSize);
  2373. if (len < length)
  2374. return -EINVAL;
  2375. type = le32_to_cpu(d->dwPropertyDataType);
  2376. if (type < USB_EXT_PROP_UNICODE ||
  2377. type > USB_EXT_PROP_UNICODE_MULTI) {
  2378. pr_vdebug("unsupported os descriptor property type: %d",
  2379. type);
  2380. return -EINVAL;
  2381. }
  2382. pnl = le16_to_cpu(d->wPropertyNameLength);
  2383. if (length < 14 + pnl) {
  2384. pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
  2385. length, pnl, type);
  2386. return -EINVAL;
  2387. }
  2388. pdl = le32_to_cpu(*(__le32 *)((u8 *)data + 10 + pnl));
  2389. if (length != 14 + pnl + pdl) {
  2390. pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
  2391. length, pnl, pdl, type);
  2392. return -EINVAL;
  2393. }
  2394. ++ffs->ms_os_descs_ext_prop_count;
  2395. /* property name reported to the host as "WCHAR"s */
  2396. ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
  2397. ffs->ms_os_descs_ext_prop_data_len += pdl;
  2398. }
  2399. break;
  2400. default:
  2401. pr_vdebug("unknown descriptor: %d\n", type);
  2402. return -EINVAL;
  2403. }
  2404. return length;
  2405. }
  2406. static int __ffs_data_got_descs(struct ffs_data *ffs,
  2407. char *const _data, size_t len)
  2408. {
  2409. char *data = _data, *raw_descs;
  2410. unsigned os_descs_count = 0, counts[3], flags;
  2411. int ret = -EINVAL, i;
  2412. struct ffs_desc_helper helper;
  2413. if (get_unaligned_le32(data + 4) != len)
  2414. goto error;
  2415. switch (get_unaligned_le32(data)) {
  2416. case FUNCTIONFS_DESCRIPTORS_MAGIC:
  2417. flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
  2418. data += 8;
  2419. len -= 8;
  2420. break;
  2421. case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
  2422. flags = get_unaligned_le32(data + 8);
  2423. ffs->user_flags = flags;
  2424. if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
  2425. FUNCTIONFS_HAS_HS_DESC |
  2426. FUNCTIONFS_HAS_SS_DESC |
  2427. FUNCTIONFS_HAS_MS_OS_DESC |
  2428. FUNCTIONFS_VIRTUAL_ADDR |
  2429. FUNCTIONFS_EVENTFD |
  2430. FUNCTIONFS_ALL_CTRL_RECIP |
  2431. FUNCTIONFS_CONFIG0_SETUP)) {
  2432. ret = -ENOSYS;
  2433. goto error;
  2434. }
  2435. data += 12;
  2436. len -= 12;
  2437. break;
  2438. default:
  2439. goto error;
  2440. }
  2441. if (flags & FUNCTIONFS_EVENTFD) {
  2442. if (len < 4)
  2443. goto error;
  2444. ffs->ffs_eventfd =
  2445. eventfd_ctx_fdget((int)get_unaligned_le32(data));
  2446. if (IS_ERR(ffs->ffs_eventfd)) {
  2447. ret = PTR_ERR(ffs->ffs_eventfd);
  2448. ffs->ffs_eventfd = NULL;
  2449. goto error;
  2450. }
  2451. data += 4;
  2452. len -= 4;
  2453. }
  2454. /* Read fs_count, hs_count and ss_count (if present) */
  2455. for (i = 0; i < 3; ++i) {
  2456. if (!(flags & (1 << i))) {
  2457. counts[i] = 0;
  2458. } else if (len < 4) {
  2459. goto error;
  2460. } else {
  2461. counts[i] = get_unaligned_le32(data);
  2462. data += 4;
  2463. len -= 4;
  2464. }
  2465. }
  2466. if (flags & (1 << i)) {
  2467. if (len < 4) {
  2468. goto error;
  2469. }
  2470. os_descs_count = get_unaligned_le32(data);
  2471. data += 4;
  2472. len -= 4;
  2473. }
  2474. /* Read descriptors */
  2475. raw_descs = data;
  2476. helper.ffs = ffs;
  2477. for (i = 0; i < 3; ++i) {
  2478. if (!counts[i])
  2479. continue;
  2480. helper.interfaces_count = 0;
  2481. helper.eps_count = 0;
  2482. ret = ffs_do_descs(counts[i], data, len,
  2483. __ffs_data_do_entity, &helper);
  2484. if (ret < 0)
  2485. goto error;
  2486. if (!ffs->eps_count && !ffs->interfaces_count) {
  2487. ffs->eps_count = helper.eps_count;
  2488. ffs->interfaces_count = helper.interfaces_count;
  2489. } else {
  2490. if (ffs->eps_count != helper.eps_count) {
  2491. ret = -EINVAL;
  2492. goto error;
  2493. }
  2494. if (ffs->interfaces_count != helper.interfaces_count) {
  2495. ret = -EINVAL;
  2496. goto error;
  2497. }
  2498. }
  2499. data += ret;
  2500. len -= ret;
  2501. }
  2502. if (os_descs_count) {
  2503. ret = ffs_do_os_descs(os_descs_count, data, len,
  2504. __ffs_data_do_os_desc, ffs);
  2505. if (ret < 0)
  2506. goto error;
  2507. data += ret;
  2508. len -= ret;
  2509. }
  2510. if (raw_descs == data || len) {
  2511. ret = -EINVAL;
  2512. goto error;
  2513. }
  2514. ffs->raw_descs_data = _data;
  2515. ffs->raw_descs = raw_descs;
  2516. ffs->raw_descs_length = data - raw_descs;
  2517. ffs->fs_descs_count = counts[0];
  2518. ffs->hs_descs_count = counts[1];
  2519. ffs->ss_descs_count = counts[2];
  2520. ffs->ms_os_descs_count = os_descs_count;
  2521. return 0;
  2522. error:
  2523. kfree(_data);
  2524. return ret;
  2525. }
  2526. static int __ffs_data_got_strings(struct ffs_data *ffs,
  2527. char *const _data, size_t len)
  2528. {
  2529. u32 str_count, needed_count, lang_count;
  2530. struct usb_gadget_strings **stringtabs, *t;
  2531. const char *data = _data;
  2532. struct usb_string *s;
  2533. if (len < 16 ||
  2534. get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
  2535. get_unaligned_le32(data + 4) != len)
  2536. goto error;
  2537. str_count = get_unaligned_le32(data + 8);
  2538. lang_count = get_unaligned_le32(data + 12);
  2539. /* if one is zero the other must be zero */
  2540. if (!str_count != !lang_count)
  2541. goto error;
  2542. /* Do we have at least as many strings as descriptors need? */
  2543. needed_count = ffs->strings_count;
  2544. if (str_count < needed_count)
  2545. goto error;
  2546. /*
  2547. * If we don't need any strings just return and free all
  2548. * memory.
  2549. */
  2550. if (!needed_count) {
  2551. kfree(_data);
  2552. return 0;
  2553. }
  2554. /* Allocate everything in one chunk so there's less maintenance. */
  2555. {
  2556. unsigned i = 0;
  2557. vla_group(d);
  2558. vla_item(d, struct usb_gadget_strings *, stringtabs,
  2559. size_add(lang_count, 1));
  2560. vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
  2561. vla_item(d, struct usb_string, strings,
  2562. size_mul(lang_count, (needed_count + 1)));
  2563. char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
  2564. if (!vlabuf) {
  2565. kfree(_data);
  2566. return -ENOMEM;
  2567. }
  2568. /* Initialize the VLA pointers */
  2569. stringtabs = vla_ptr(vlabuf, d, stringtabs);
  2570. t = vla_ptr(vlabuf, d, stringtab);
  2571. i = lang_count;
  2572. do {
  2573. *stringtabs++ = t++;
  2574. } while (--i);
  2575. *stringtabs = NULL;
  2576. /* stringtabs = vlabuf = d_stringtabs for later kfree */
  2577. stringtabs = vla_ptr(vlabuf, d, stringtabs);
  2578. t = vla_ptr(vlabuf, d, stringtab);
  2579. s = vla_ptr(vlabuf, d, strings);
  2580. }
  2581. /* For each language */
  2582. data += 16;
  2583. len -= 16;
  2584. do { /* lang_count > 0 so we can use do-while */
  2585. unsigned needed = needed_count;
  2586. u32 str_per_lang = str_count;
  2587. if (len < 3)
  2588. goto error_free;
  2589. t->language = get_unaligned_le16(data);
  2590. t->strings = s;
  2591. ++t;
  2592. data += 2;
  2593. len -= 2;
  2594. /* For each string */
  2595. do { /* str_count > 0 so we can use do-while */
  2596. size_t length = strnlen(data, len);
  2597. if (length == len)
  2598. goto error_free;
  2599. /*
  2600. * User may provide more strings then we need,
  2601. * if that's the case we simply ignore the
  2602. * rest
  2603. */
  2604. if (needed) {
  2605. /*
  2606. * s->id will be set while adding
  2607. * function to configuration so for
  2608. * now just leave garbage here.
  2609. */
  2610. s->s = data;
  2611. --needed;
  2612. ++s;
  2613. }
  2614. data += length + 1;
  2615. len -= length + 1;
  2616. } while (--str_per_lang);
  2617. s->id = 0; /* terminator */
  2618. s->s = NULL;
  2619. ++s;
  2620. } while (--lang_count);
  2621. /* Some garbage left? */
  2622. if (len)
  2623. goto error_free;
  2624. /* Done! */
  2625. ffs->stringtabs = stringtabs;
  2626. ffs->raw_strings = _data;
  2627. return 0;
  2628. error_free:
  2629. kfree(stringtabs);
  2630. error:
  2631. kfree(_data);
  2632. return -EINVAL;
  2633. }
  2634. /* Events handling and management *******************************************/
  2635. static void __ffs_event_add(struct ffs_data *ffs,
  2636. enum usb_functionfs_event_type type)
  2637. {
  2638. enum usb_functionfs_event_type rem_type1, rem_type2 = type;
  2639. int neg = 0;
  2640. /*
  2641. * Abort any unhandled setup
  2642. *
  2643. * We do not need to worry about some cmpxchg() changing value
  2644. * of ffs->setup_state without holding the lock because when
  2645. * state is FFS_SETUP_PENDING cmpxchg() in several places in
  2646. * the source does nothing.
  2647. */
  2648. if (ffs->setup_state == FFS_SETUP_PENDING)
  2649. ffs->setup_state = FFS_SETUP_CANCELLED;
  2650. /*
  2651. * Logic of this function guarantees that there are at most four pending
  2652. * evens on ffs->ev.types queue. This is important because the queue
  2653. * has space for four elements only and __ffs_ep0_read_events function
  2654. * depends on that limit as well. If more event types are added, those
  2655. * limits have to be revisited or guaranteed to still hold.
  2656. */
  2657. switch (type) {
  2658. case FUNCTIONFS_RESUME:
  2659. rem_type2 = FUNCTIONFS_SUSPEND;
  2660. fallthrough;
  2661. case FUNCTIONFS_SUSPEND:
  2662. case FUNCTIONFS_SETUP:
  2663. rem_type1 = type;
  2664. /* Discard all similar events */
  2665. break;
  2666. case FUNCTIONFS_BIND:
  2667. case FUNCTIONFS_UNBIND:
  2668. case FUNCTIONFS_DISABLE:
  2669. case FUNCTIONFS_ENABLE:
  2670. /* Discard everything other then power management. */
  2671. rem_type1 = FUNCTIONFS_SUSPEND;
  2672. rem_type2 = FUNCTIONFS_RESUME;
  2673. neg = 1;
  2674. break;
  2675. default:
  2676. WARN(1, "%d: unknown event, this should not happen\n", type);
  2677. return;
  2678. }
  2679. {
  2680. u8 *ev = ffs->ev.types, *out = ev;
  2681. unsigned n = ffs->ev.count;
  2682. for (; n; --n, ++ev)
  2683. if ((*ev == rem_type1 || *ev == rem_type2) == neg)
  2684. *out++ = *ev;
  2685. else
  2686. pr_vdebug("purging event %d\n", *ev);
  2687. ffs->ev.count = out - ffs->ev.types;
  2688. }
  2689. pr_vdebug("adding event %d\n", type);
  2690. ffs->ev.types[ffs->ev.count++] = type;
  2691. wake_up_locked(&ffs->ev.waitq);
  2692. if (ffs->ffs_eventfd)
  2693. eventfd_signal(ffs->ffs_eventfd);
  2694. }
  2695. static void ffs_event_add(struct ffs_data *ffs,
  2696. enum usb_functionfs_event_type type)
  2697. {
  2698. unsigned long flags;
  2699. spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
  2700. __ffs_event_add(ffs, type);
  2701. spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
  2702. }
  2703. /* Bind/unbind USB function hooks *******************************************/
  2704. static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
  2705. {
  2706. int i;
  2707. for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
  2708. if (ffs->eps_addrmap[i] == endpoint_address)
  2709. return i;
  2710. return -ENOENT;
  2711. }
  2712. static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
  2713. struct usb_descriptor_header *desc,
  2714. void *priv)
  2715. {
  2716. struct usb_endpoint_descriptor *ds = (void *)desc;
  2717. struct ffs_function *func = priv;
  2718. struct ffs_ep *ffs_ep;
  2719. unsigned ep_desc_id;
  2720. int idx;
  2721. static const char *speed_names[] = { "full", "high", "super" };
  2722. if (type != FFS_DESCRIPTOR)
  2723. return 0;
  2724. /*
  2725. * If ss_descriptors is not NULL, we are reading super speed
  2726. * descriptors; if hs_descriptors is not NULL, we are reading high
  2727. * speed descriptors; otherwise, we are reading full speed
  2728. * descriptors.
  2729. */
  2730. if (func->function.ss_descriptors) {
  2731. ep_desc_id = 2;
  2732. func->function.ss_descriptors[(long)valuep] = desc;
  2733. } else if (func->function.hs_descriptors) {
  2734. ep_desc_id = 1;
  2735. func->function.hs_descriptors[(long)valuep] = desc;
  2736. } else {
  2737. ep_desc_id = 0;
  2738. func->function.fs_descriptors[(long)valuep] = desc;
  2739. }
  2740. if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
  2741. return 0;
  2742. idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
  2743. if (idx < 0)
  2744. return idx;
  2745. ffs_ep = func->eps + idx;
  2746. if (ffs_ep->descs[ep_desc_id]) {
  2747. pr_err("two %sspeed descriptors for EP %d\n",
  2748. speed_names[ep_desc_id],
  2749. ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
  2750. return -EINVAL;
  2751. }
  2752. ffs_ep->descs[ep_desc_id] = ds;
  2753. ffs_dump_mem(": Original ep desc", ds, ds->bLength);
  2754. if (ffs_ep->ep) {
  2755. ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
  2756. if (!ds->wMaxPacketSize)
  2757. ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
  2758. } else {
  2759. struct usb_request *req;
  2760. struct usb_ep *ep;
  2761. u8 bEndpointAddress;
  2762. u16 wMaxPacketSize;
  2763. /*
  2764. * We back up bEndpointAddress because autoconfig overwrites
  2765. * it with physical endpoint address.
  2766. */
  2767. bEndpointAddress = ds->bEndpointAddress;
  2768. /*
  2769. * We back up wMaxPacketSize because autoconfig treats
  2770. * endpoint descriptors as if they were full speed.
  2771. */
  2772. wMaxPacketSize = ds->wMaxPacketSize;
  2773. pr_vdebug("autoconfig\n");
  2774. ep = usb_ep_autoconfig(func->gadget, ds);
  2775. if (!ep)
  2776. return -ENOTSUPP;
  2777. ep->driver_data = func->eps + idx;
  2778. req = usb_ep_alloc_request(ep, GFP_KERNEL);
  2779. if (!req)
  2780. return -ENOMEM;
  2781. ffs_ep->ep = ep;
  2782. ffs_ep->req = req;
  2783. func->eps_revmap[ds->bEndpointAddress &
  2784. USB_ENDPOINT_NUMBER_MASK] = idx + 1;
  2785. /*
  2786. * If we use virtual address mapping, we restore
  2787. * original bEndpointAddress value.
  2788. */
  2789. if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
  2790. ds->bEndpointAddress = bEndpointAddress;
  2791. /*
  2792. * Restore wMaxPacketSize which was potentially
  2793. * overwritten by autoconfig.
  2794. */
  2795. ds->wMaxPacketSize = wMaxPacketSize;
  2796. }
  2797. ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
  2798. return 0;
  2799. }
  2800. static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
  2801. struct usb_descriptor_header *desc,
  2802. void *priv)
  2803. {
  2804. struct ffs_function *func = priv;
  2805. unsigned idx;
  2806. u8 newValue;
  2807. switch (type) {
  2808. default:
  2809. case FFS_DESCRIPTOR:
  2810. /* Handled in previous pass by __ffs_func_bind_do_descs() */
  2811. return 0;
  2812. case FFS_INTERFACE:
  2813. idx = *valuep;
  2814. if (func->interfaces_nums[idx] < 0) {
  2815. int id = usb_interface_id(func->conf, &func->function);
  2816. if (id < 0)
  2817. return id;
  2818. func->interfaces_nums[idx] = id;
  2819. }
  2820. newValue = func->interfaces_nums[idx];
  2821. break;
  2822. case FFS_STRING:
  2823. /* String' IDs are allocated when fsf_data is bound to cdev */
  2824. newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
  2825. break;
  2826. case FFS_ENDPOINT:
  2827. /*
  2828. * USB_DT_ENDPOINT are handled in
  2829. * __ffs_func_bind_do_descs().
  2830. */
  2831. if (desc->bDescriptorType == USB_DT_ENDPOINT)
  2832. return 0;
  2833. idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
  2834. if (!func->eps[idx].ep)
  2835. return -EINVAL;
  2836. {
  2837. struct usb_endpoint_descriptor **descs;
  2838. descs = func->eps[idx].descs;
  2839. newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
  2840. }
  2841. break;
  2842. }
  2843. pr_vdebug("%02x -> %02x\n", *valuep, newValue);
  2844. *valuep = newValue;
  2845. return 0;
  2846. }
  2847. static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
  2848. struct usb_os_desc_header *h, void *data,
  2849. unsigned len, void *priv)
  2850. {
  2851. struct ffs_function *func = priv;
  2852. u8 length = 0;
  2853. switch (type) {
  2854. case FFS_OS_DESC_EXT_COMPAT: {
  2855. struct usb_ext_compat_desc *desc = data;
  2856. struct usb_os_desc_table *t;
  2857. t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
  2858. t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
  2859. memcpy(t->os_desc->ext_compat_id, &desc->IDs,
  2860. sizeof_field(struct usb_ext_compat_desc, IDs));
  2861. length = sizeof(*desc);
  2862. }
  2863. break;
  2864. case FFS_OS_DESC_EXT_PROP: {
  2865. struct usb_ext_prop_desc *desc = data;
  2866. struct usb_os_desc_table *t;
  2867. struct usb_os_desc_ext_prop *ext_prop;
  2868. char *ext_prop_name;
  2869. char *ext_prop_data;
  2870. t = &func->function.os_desc_table[h->interface];
  2871. t->if_id = func->interfaces_nums[h->interface];
  2872. ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
  2873. func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
  2874. ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
  2875. ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
  2876. ext_prop->data_len = le32_to_cpu(*(__le32 *)
  2877. usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
  2878. length = ext_prop->name_len + ext_prop->data_len + 14;
  2879. ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
  2880. func->ffs->ms_os_descs_ext_prop_name_avail +=
  2881. ext_prop->name_len;
  2882. ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
  2883. func->ffs->ms_os_descs_ext_prop_data_avail +=
  2884. ext_prop->data_len;
  2885. memcpy(ext_prop_data,
  2886. usb_ext_prop_data_ptr(data, ext_prop->name_len),
  2887. ext_prop->data_len);
  2888. /* unicode data reported to the host as "WCHAR"s */
  2889. switch (ext_prop->type) {
  2890. case USB_EXT_PROP_UNICODE:
  2891. case USB_EXT_PROP_UNICODE_ENV:
  2892. case USB_EXT_PROP_UNICODE_LINK:
  2893. case USB_EXT_PROP_UNICODE_MULTI:
  2894. ext_prop->data_len *= 2;
  2895. break;
  2896. }
  2897. ext_prop->data = ext_prop_data;
  2898. memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
  2899. ext_prop->name_len);
  2900. /* property name reported to the host as "WCHAR"s */
  2901. ext_prop->name_len *= 2;
  2902. ext_prop->name = ext_prop_name;
  2903. t->os_desc->ext_prop_len +=
  2904. ext_prop->name_len + ext_prop->data_len + 14;
  2905. ++t->os_desc->ext_prop_count;
  2906. list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
  2907. }
  2908. break;
  2909. default:
  2910. pr_vdebug("unknown descriptor: %d\n", type);
  2911. }
  2912. return length;
  2913. }
  2914. static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
  2915. struct usb_configuration *c)
  2916. {
  2917. struct ffs_function *func = ffs_func_from_usb(f);
  2918. struct f_fs_opts *ffs_opts =
  2919. container_of(f->fi, struct f_fs_opts, func_inst);
  2920. struct ffs_data *ffs_data;
  2921. int ret;
  2922. /*
  2923. * Legacy gadget triggers binding in functionfs_ready_callback,
  2924. * which already uses locking; taking the same lock here would
  2925. * cause a deadlock.
  2926. *
  2927. * Configfs-enabled gadgets however do need ffs_dev_lock.
  2928. */
  2929. if (!ffs_opts->no_configfs)
  2930. ffs_dev_lock();
  2931. ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
  2932. ffs_data = ffs_opts->dev->ffs_data;
  2933. if (!ffs_opts->no_configfs)
  2934. ffs_dev_unlock();
  2935. if (ret)
  2936. return ERR_PTR(ret);
  2937. func->ffs = ffs_data;
  2938. func->conf = c;
  2939. func->gadget = c->cdev->gadget;
  2940. /*
  2941. * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
  2942. * configurations are bound in sequence with list_for_each_entry,
  2943. * in each configuration its functions are bound in sequence
  2944. * with list_for_each_entry, so we assume no race condition
  2945. * with regard to ffs_opts->bound access
  2946. */
  2947. if (!ffs_opts->refcnt) {
  2948. ret = functionfs_bind(func->ffs, c->cdev);
  2949. if (ret)
  2950. return ERR_PTR(ret);
  2951. }
  2952. ffs_opts->refcnt++;
  2953. func->function.strings = func->ffs->stringtabs;
  2954. return ffs_opts;
  2955. }
  2956. static int _ffs_func_bind(struct usb_configuration *c,
  2957. struct usb_function *f)
  2958. {
  2959. struct ffs_function *func = ffs_func_from_usb(f);
  2960. struct ffs_data *ffs = func->ffs;
  2961. const int full = !!func->ffs->fs_descs_count;
  2962. const int high = !!func->ffs->hs_descs_count;
  2963. const int super = !!func->ffs->ss_descs_count;
  2964. int fs_len, hs_len, ss_len, ret, i;
  2965. struct ffs_ep *eps_ptr;
  2966. /* Make it a single chunk, less management later on */
  2967. vla_group(d);
  2968. vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
  2969. vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
  2970. full ? ffs->fs_descs_count + 1 : 0);
  2971. vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
  2972. high ? ffs->hs_descs_count + 1 : 0);
  2973. vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
  2974. super ? ffs->ss_descs_count + 1 : 0);
  2975. vla_item_with_sz(d, short, inums, ffs->interfaces_count);
  2976. vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
  2977. c->cdev->use_os_string ? ffs->interfaces_count : 0);
  2978. vla_item_with_sz(d, char[16], ext_compat,
  2979. c->cdev->use_os_string ? ffs->interfaces_count : 0);
  2980. vla_item_with_sz(d, struct usb_os_desc, os_desc,
  2981. c->cdev->use_os_string ? ffs->interfaces_count : 0);
  2982. vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
  2983. ffs->ms_os_descs_ext_prop_count);
  2984. vla_item_with_sz(d, char, ext_prop_name,
  2985. ffs->ms_os_descs_ext_prop_name_len);
  2986. vla_item_with_sz(d, char, ext_prop_data,
  2987. ffs->ms_os_descs_ext_prop_data_len);
  2988. vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
  2989. char *vlabuf;
  2990. /* Has descriptors only for speeds gadget does not support */
  2991. if (!(full | high | super))
  2992. return -ENOTSUPP;
  2993. /* Allocate a single chunk, less management later on */
  2994. vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
  2995. if (!vlabuf)
  2996. return -ENOMEM;
  2997. ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
  2998. ffs->ms_os_descs_ext_prop_name_avail =
  2999. vla_ptr(vlabuf, d, ext_prop_name);
  3000. ffs->ms_os_descs_ext_prop_data_avail =
  3001. vla_ptr(vlabuf, d, ext_prop_data);
  3002. /* Copy descriptors */
  3003. memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
  3004. ffs->raw_descs_length);
  3005. memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
  3006. eps_ptr = vla_ptr(vlabuf, d, eps);
  3007. for (i = 0; i < ffs->eps_count; i++)
  3008. eps_ptr[i].num = -1;
  3009. /* Save pointers
  3010. * d_eps == vlabuf, func->eps used to kfree vlabuf later
  3011. */
  3012. func->eps = vla_ptr(vlabuf, d, eps);
  3013. func->interfaces_nums = vla_ptr(vlabuf, d, inums);
  3014. /*
  3015. * Go through all the endpoint descriptors and allocate
  3016. * endpoints first, so that later we can rewrite the endpoint
  3017. * numbers without worrying that it may be described later on.
  3018. */
  3019. if (full) {
  3020. func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
  3021. fs_len = ffs_do_descs(ffs->fs_descs_count,
  3022. vla_ptr(vlabuf, d, raw_descs),
  3023. d_raw_descs__sz,
  3024. __ffs_func_bind_do_descs, func);
  3025. if (fs_len < 0) {
  3026. ret = fs_len;
  3027. goto error;
  3028. }
  3029. } else {
  3030. fs_len = 0;
  3031. }
  3032. if (high) {
  3033. func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
  3034. hs_len = ffs_do_descs(ffs->hs_descs_count,
  3035. vla_ptr(vlabuf, d, raw_descs) + fs_len,
  3036. d_raw_descs__sz - fs_len,
  3037. __ffs_func_bind_do_descs, func);
  3038. if (hs_len < 0) {
  3039. ret = hs_len;
  3040. goto error;
  3041. }
  3042. } else {
  3043. hs_len = 0;
  3044. }
  3045. if (super) {
  3046. func->function.ss_descriptors = func->function.ssp_descriptors =
  3047. vla_ptr(vlabuf, d, ss_descs);
  3048. ss_len = ffs_do_descs(ffs->ss_descs_count,
  3049. vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
  3050. d_raw_descs__sz - fs_len - hs_len,
  3051. __ffs_func_bind_do_descs, func);
  3052. if (ss_len < 0) {
  3053. ret = ss_len;
  3054. goto error;
  3055. }
  3056. } else {
  3057. ss_len = 0;
  3058. }
  3059. /*
  3060. * Now handle interface numbers allocation and interface and
  3061. * endpoint numbers rewriting. We can do that in one go
  3062. * now.
  3063. */
  3064. ret = ffs_do_descs(ffs->fs_descs_count +
  3065. (high ? ffs->hs_descs_count : 0) +
  3066. (super ? ffs->ss_descs_count : 0),
  3067. vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
  3068. __ffs_func_bind_do_nums, func);
  3069. if (ret < 0)
  3070. goto error;
  3071. func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
  3072. if (c->cdev->use_os_string) {
  3073. for (i = 0; i < ffs->interfaces_count; ++i) {
  3074. struct usb_os_desc *desc;
  3075. desc = func->function.os_desc_table[i].os_desc =
  3076. vla_ptr(vlabuf, d, os_desc) +
  3077. i * sizeof(struct usb_os_desc);
  3078. desc->ext_compat_id =
  3079. vla_ptr(vlabuf, d, ext_compat) + i * 16;
  3080. INIT_LIST_HEAD(&desc->ext_prop);
  3081. }
  3082. ret = ffs_do_os_descs(ffs->ms_os_descs_count,
  3083. vla_ptr(vlabuf, d, raw_descs) +
  3084. fs_len + hs_len + ss_len,
  3085. d_raw_descs__sz - fs_len - hs_len -
  3086. ss_len,
  3087. __ffs_func_bind_do_os_desc, func);
  3088. if (ret < 0)
  3089. goto error;
  3090. }
  3091. func->function.os_desc_n =
  3092. c->cdev->use_os_string ? ffs->interfaces_count : 0;
  3093. /* And we're done */
  3094. ffs_event_add(ffs, FUNCTIONFS_BIND);
  3095. return 0;
  3096. error:
  3097. /* XXX Do we need to release all claimed endpoints here? */
  3098. return ret;
  3099. }
  3100. static int ffs_func_bind(struct usb_configuration *c,
  3101. struct usb_function *f)
  3102. {
  3103. struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
  3104. struct ffs_function *func = ffs_func_from_usb(f);
  3105. int ret;
  3106. if (IS_ERR(ffs_opts))
  3107. return PTR_ERR(ffs_opts);
  3108. ret = _ffs_func_bind(c, f);
  3109. if (ret && !--ffs_opts->refcnt)
  3110. functionfs_unbind(func->ffs);
  3111. return ret;
  3112. }
  3113. /* Other USB function hooks *************************************************/
  3114. static void ffs_reset_work(struct work_struct *work)
  3115. {
  3116. struct ffs_data *ffs = container_of(work,
  3117. struct ffs_data, reset_work);
  3118. ffs_data_reset(ffs);
  3119. }
  3120. static int ffs_func_get_alt(struct usb_function *f,
  3121. unsigned int interface)
  3122. {
  3123. struct ffs_function *func = ffs_func_from_usb(f);
  3124. int intf = ffs_func_revmap_intf(func, interface);
  3125. return (intf < 0) ? intf : func->cur_alt[interface];
  3126. }
  3127. static int ffs_func_set_alt(struct usb_function *f,
  3128. unsigned interface, unsigned alt)
  3129. {
  3130. struct ffs_function *func = ffs_func_from_usb(f);
  3131. struct ffs_data *ffs = func->ffs;
  3132. int ret = 0, intf;
  3133. if (alt > MAX_ALT_SETTINGS)
  3134. return -EINVAL;
  3135. intf = ffs_func_revmap_intf(func, interface);
  3136. if (intf < 0)
  3137. return intf;
  3138. if (ffs->func)
  3139. ffs_func_eps_disable(ffs->func);
  3140. if (ffs->state == FFS_DEACTIVATED) {
  3141. ffs->state = FFS_CLOSING;
  3142. INIT_WORK(&ffs->reset_work, ffs_reset_work);
  3143. schedule_work(&ffs->reset_work);
  3144. return -ENODEV;
  3145. }
  3146. if (ffs->state != FFS_ACTIVE)
  3147. return -ENODEV;
  3148. ffs->func = func;
  3149. ret = ffs_func_eps_enable(func);
  3150. if (ret >= 0) {
  3151. ffs_event_add(ffs, FUNCTIONFS_ENABLE);
  3152. func->cur_alt[interface] = alt;
  3153. }
  3154. return ret;
  3155. }
  3156. static void ffs_func_disable(struct usb_function *f)
  3157. {
  3158. struct ffs_function *func = ffs_func_from_usb(f);
  3159. struct ffs_data *ffs = func->ffs;
  3160. if (ffs->func)
  3161. ffs_func_eps_disable(ffs->func);
  3162. if (ffs->state == FFS_DEACTIVATED) {
  3163. ffs->state = FFS_CLOSING;
  3164. INIT_WORK(&ffs->reset_work, ffs_reset_work);
  3165. schedule_work(&ffs->reset_work);
  3166. return;
  3167. }
  3168. if (ffs->state == FFS_ACTIVE) {
  3169. ffs->func = NULL;
  3170. ffs_event_add(ffs, FUNCTIONFS_DISABLE);
  3171. }
  3172. }
  3173. static int ffs_func_setup(struct usb_function *f,
  3174. const struct usb_ctrlrequest *creq)
  3175. {
  3176. struct ffs_function *func = ffs_func_from_usb(f);
  3177. struct ffs_data *ffs = func->ffs;
  3178. unsigned long flags;
  3179. int ret;
  3180. pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
  3181. pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
  3182. pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
  3183. pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
  3184. pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
  3185. /*
  3186. * Most requests directed to interface go through here
  3187. * (notable exceptions are set/get interface) so we need to
  3188. * handle them. All other either handled by composite or
  3189. * passed to usb_configuration->setup() (if one is set). No
  3190. * matter, we will handle requests directed to endpoint here
  3191. * as well (as it's straightforward). Other request recipient
  3192. * types are only handled when the user flag FUNCTIONFS_ALL_CTRL_RECIP
  3193. * is being used.
  3194. */
  3195. if (ffs->state != FFS_ACTIVE)
  3196. return -ENODEV;
  3197. switch (creq->bRequestType & USB_RECIP_MASK) {
  3198. case USB_RECIP_INTERFACE:
  3199. ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
  3200. if (ret < 0)
  3201. return ret;
  3202. break;
  3203. case USB_RECIP_ENDPOINT:
  3204. ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
  3205. if (ret < 0)
  3206. return ret;
  3207. if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
  3208. ret = func->ffs->eps_addrmap[ret];
  3209. break;
  3210. default:
  3211. if (func->ffs->user_flags & FUNCTIONFS_ALL_CTRL_RECIP)
  3212. ret = le16_to_cpu(creq->wIndex);
  3213. else
  3214. return -EOPNOTSUPP;
  3215. }
  3216. spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
  3217. ffs->ev.setup = *creq;
  3218. ffs->ev.setup.wIndex = cpu_to_le16(ret);
  3219. __ffs_event_add(ffs, FUNCTIONFS_SETUP);
  3220. spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
  3221. return ffs->ev.setup.wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
  3222. }
  3223. static bool ffs_func_req_match(struct usb_function *f,
  3224. const struct usb_ctrlrequest *creq,
  3225. bool config0)
  3226. {
  3227. struct ffs_function *func = ffs_func_from_usb(f);
  3228. if (config0 && !(func->ffs->user_flags & FUNCTIONFS_CONFIG0_SETUP))
  3229. return false;
  3230. switch (creq->bRequestType & USB_RECIP_MASK) {
  3231. case USB_RECIP_INTERFACE:
  3232. return (ffs_func_revmap_intf(func,
  3233. le16_to_cpu(creq->wIndex)) >= 0);
  3234. case USB_RECIP_ENDPOINT:
  3235. return (ffs_func_revmap_ep(func,
  3236. le16_to_cpu(creq->wIndex)) >= 0);
  3237. default:
  3238. return (bool) (func->ffs->user_flags &
  3239. FUNCTIONFS_ALL_CTRL_RECIP);
  3240. }
  3241. }
  3242. static void ffs_func_suspend(struct usb_function *f)
  3243. {
  3244. ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
  3245. }
  3246. static void ffs_func_resume(struct usb_function *f)
  3247. {
  3248. ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
  3249. }
  3250. /* Endpoint and interface numbers reverse mapping ***************************/
  3251. static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
  3252. {
  3253. num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
  3254. return num ? num : -EDOM;
  3255. }
  3256. static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
  3257. {
  3258. short *nums = func->interfaces_nums;
  3259. unsigned count = func->ffs->interfaces_count;
  3260. for (; count; --count, ++nums) {
  3261. if (*nums >= 0 && *nums == intf)
  3262. return nums - func->interfaces_nums;
  3263. }
  3264. return -EDOM;
  3265. }
  3266. /* Devices management *******************************************************/
  3267. static LIST_HEAD(ffs_devices);
  3268. static struct ffs_dev *_ffs_do_find_dev(const char *name)
  3269. {
  3270. struct ffs_dev *dev;
  3271. if (!name)
  3272. return NULL;
  3273. list_for_each_entry(dev, &ffs_devices, entry) {
  3274. if (strcmp(dev->name, name) == 0)
  3275. return dev;
  3276. }
  3277. return NULL;
  3278. }
  3279. /*
  3280. * ffs_lock must be taken by the caller of this function
  3281. */
  3282. static struct ffs_dev *_ffs_get_single_dev(void)
  3283. {
  3284. struct ffs_dev *dev;
  3285. if (list_is_singular(&ffs_devices)) {
  3286. dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
  3287. if (dev->single)
  3288. return dev;
  3289. }
  3290. return NULL;
  3291. }
  3292. /*
  3293. * ffs_lock must be taken by the caller of this function
  3294. */
  3295. static struct ffs_dev *_ffs_find_dev(const char *name)
  3296. {
  3297. struct ffs_dev *dev;
  3298. dev = _ffs_get_single_dev();
  3299. if (dev)
  3300. return dev;
  3301. return _ffs_do_find_dev(name);
  3302. }
  3303. /* Configfs support *********************************************************/
  3304. static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
  3305. {
  3306. return container_of(to_config_group(item), struct f_fs_opts,
  3307. func_inst.group);
  3308. }
  3309. static ssize_t f_fs_opts_ready_show(struct config_item *item, char *page)
  3310. {
  3311. struct f_fs_opts *opts = to_ffs_opts(item);
  3312. int ready;
  3313. ffs_dev_lock();
  3314. ready = opts->dev->desc_ready;
  3315. ffs_dev_unlock();
  3316. return sprintf(page, "%d\n", ready);
  3317. }
  3318. CONFIGFS_ATTR_RO(f_fs_opts_, ready);
  3319. static struct configfs_attribute *ffs_attrs[] = {
  3320. &f_fs_opts_attr_ready,
  3321. NULL,
  3322. };
  3323. static void ffs_attr_release(struct config_item *item)
  3324. {
  3325. struct f_fs_opts *opts = to_ffs_opts(item);
  3326. usb_put_function_instance(&opts->func_inst);
  3327. }
  3328. static struct configfs_item_operations ffs_item_ops = {
  3329. .release = ffs_attr_release,
  3330. };
  3331. static const struct config_item_type ffs_func_type = {
  3332. .ct_item_ops = &ffs_item_ops,
  3333. .ct_attrs = ffs_attrs,
  3334. .ct_owner = THIS_MODULE,
  3335. };
  3336. /* Function registration interface ******************************************/
  3337. static void ffs_free_inst(struct usb_function_instance *f)
  3338. {
  3339. struct f_fs_opts *opts;
  3340. opts = to_f_fs_opts(f);
  3341. ffs_release_dev(opts->dev);
  3342. ffs_dev_lock();
  3343. _ffs_free_dev(opts->dev);
  3344. ffs_dev_unlock();
  3345. kfree(opts);
  3346. }
  3347. static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
  3348. {
  3349. if (strlen(name) >= sizeof_field(struct ffs_dev, name))
  3350. return -ENAMETOOLONG;
  3351. return ffs_name_dev(to_f_fs_opts(fi)->dev, name);
  3352. }
  3353. static struct usb_function_instance *ffs_alloc_inst(void)
  3354. {
  3355. struct f_fs_opts *opts;
  3356. struct ffs_dev *dev;
  3357. opts = kzalloc(sizeof(*opts), GFP_KERNEL);
  3358. if (!opts)
  3359. return ERR_PTR(-ENOMEM);
  3360. opts->func_inst.set_inst_name = ffs_set_inst_name;
  3361. opts->func_inst.free_func_inst = ffs_free_inst;
  3362. ffs_dev_lock();
  3363. dev = _ffs_alloc_dev();
  3364. ffs_dev_unlock();
  3365. if (IS_ERR(dev)) {
  3366. kfree(opts);
  3367. return ERR_CAST(dev);
  3368. }
  3369. opts->dev = dev;
  3370. dev->opts = opts;
  3371. config_group_init_type_name(&opts->func_inst.group, "",
  3372. &ffs_func_type);
  3373. return &opts->func_inst;
  3374. }
  3375. static void ffs_free(struct usb_function *f)
  3376. {
  3377. kfree(ffs_func_from_usb(f));
  3378. }
  3379. static void ffs_func_unbind(struct usb_configuration *c,
  3380. struct usb_function *f)
  3381. {
  3382. struct ffs_function *func = ffs_func_from_usb(f);
  3383. struct ffs_data *ffs = func->ffs;
  3384. struct f_fs_opts *opts =
  3385. container_of(f->fi, struct f_fs_opts, func_inst);
  3386. struct ffs_ep *ep = func->eps;
  3387. unsigned count = ffs->eps_count;
  3388. unsigned long flags;
  3389. if (ffs->func == func) {
  3390. ffs_func_eps_disable(func);
  3391. ffs->func = NULL;
  3392. }
  3393. /* Drain any pending AIO completions */
  3394. drain_workqueue(ffs->io_completion_wq);
  3395. ffs_event_add(ffs, FUNCTIONFS_UNBIND);
  3396. if (!--opts->refcnt)
  3397. functionfs_unbind(ffs);
  3398. /* cleanup after autoconfig */
  3399. spin_lock_irqsave(&func->ffs->eps_lock, flags);
  3400. while (count--) {
  3401. if (ep->ep && ep->req)
  3402. usb_ep_free_request(ep->ep, ep->req);
  3403. ep->req = NULL;
  3404. ++ep;
  3405. }
  3406. spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
  3407. kfree(func->eps);
  3408. func->eps = NULL;
  3409. /*
  3410. * eps, descriptors and interfaces_nums are allocated in the
  3411. * same chunk so only one free is required.
  3412. */
  3413. func->function.fs_descriptors = NULL;
  3414. func->function.hs_descriptors = NULL;
  3415. func->function.ss_descriptors = NULL;
  3416. func->function.ssp_descriptors = NULL;
  3417. func->interfaces_nums = NULL;
  3418. }
  3419. static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
  3420. {
  3421. struct ffs_function *func;
  3422. func = kzalloc(sizeof(*func), GFP_KERNEL);
  3423. if (!func)
  3424. return ERR_PTR(-ENOMEM);
  3425. func->function.name = "Function FS Gadget";
  3426. func->function.bind = ffs_func_bind;
  3427. func->function.unbind = ffs_func_unbind;
  3428. func->function.set_alt = ffs_func_set_alt;
  3429. func->function.get_alt = ffs_func_get_alt;
  3430. func->function.disable = ffs_func_disable;
  3431. func->function.setup = ffs_func_setup;
  3432. func->function.req_match = ffs_func_req_match;
  3433. func->function.suspend = ffs_func_suspend;
  3434. func->function.resume = ffs_func_resume;
  3435. func->function.free_func = ffs_free;
  3436. return &func->function;
  3437. }
  3438. /*
  3439. * ffs_lock must be taken by the caller of this function
  3440. */
  3441. static struct ffs_dev *_ffs_alloc_dev(void)
  3442. {
  3443. struct ffs_dev *dev;
  3444. int ret;
  3445. if (_ffs_get_single_dev())
  3446. return ERR_PTR(-EBUSY);
  3447. dev = kzalloc(sizeof(*dev), GFP_KERNEL);
  3448. if (!dev)
  3449. return ERR_PTR(-ENOMEM);
  3450. if (list_empty(&ffs_devices)) {
  3451. ret = functionfs_init();
  3452. if (ret) {
  3453. kfree(dev);
  3454. return ERR_PTR(ret);
  3455. }
  3456. }
  3457. list_add(&dev->entry, &ffs_devices);
  3458. return dev;
  3459. }
  3460. int ffs_name_dev(struct ffs_dev *dev, const char *name)
  3461. {
  3462. struct ffs_dev *existing;
  3463. int ret = 0;
  3464. ffs_dev_lock();
  3465. existing = _ffs_do_find_dev(name);
  3466. if (!existing)
  3467. strscpy(dev->name, name, ARRAY_SIZE(dev->name));
  3468. else if (existing != dev)
  3469. ret = -EBUSY;
  3470. ffs_dev_unlock();
  3471. return ret;
  3472. }
  3473. EXPORT_SYMBOL_GPL(ffs_name_dev);
  3474. int ffs_single_dev(struct ffs_dev *dev)
  3475. {
  3476. int ret;
  3477. ret = 0;
  3478. ffs_dev_lock();
  3479. if (!list_is_singular(&ffs_devices))
  3480. ret = -EBUSY;
  3481. else
  3482. dev->single = true;
  3483. ffs_dev_unlock();
  3484. return ret;
  3485. }
  3486. EXPORT_SYMBOL_GPL(ffs_single_dev);
  3487. /*
  3488. * ffs_lock must be taken by the caller of this function
  3489. */
  3490. static void _ffs_free_dev(struct ffs_dev *dev)
  3491. {
  3492. list_del(&dev->entry);
  3493. kfree(dev);
  3494. if (list_empty(&ffs_devices))
  3495. functionfs_cleanup();
  3496. }
  3497. static int ffs_acquire_dev(const char *dev_name, struct ffs_data *ffs_data)
  3498. {
  3499. int ret = 0;
  3500. struct ffs_dev *ffs_dev;
  3501. ffs_dev_lock();
  3502. ffs_dev = _ffs_find_dev(dev_name);
  3503. if (!ffs_dev) {
  3504. ret = -ENOENT;
  3505. } else if (ffs_dev->mounted) {
  3506. ret = -EBUSY;
  3507. } else if (ffs_dev->ffs_acquire_dev_callback &&
  3508. ffs_dev->ffs_acquire_dev_callback(ffs_dev)) {
  3509. ret = -ENOENT;
  3510. } else {
  3511. ffs_dev->mounted = true;
  3512. ffs_dev->ffs_data = ffs_data;
  3513. ffs_data->private_data = ffs_dev;
  3514. }
  3515. ffs_dev_unlock();
  3516. return ret;
  3517. }
  3518. static void ffs_release_dev(struct ffs_dev *ffs_dev)
  3519. {
  3520. ffs_dev_lock();
  3521. if (ffs_dev && ffs_dev->mounted) {
  3522. ffs_dev->mounted = false;
  3523. if (ffs_dev->ffs_data) {
  3524. ffs_dev->ffs_data->private_data = NULL;
  3525. ffs_dev->ffs_data = NULL;
  3526. }
  3527. if (ffs_dev->ffs_release_dev_callback)
  3528. ffs_dev->ffs_release_dev_callback(ffs_dev);
  3529. }
  3530. ffs_dev_unlock();
  3531. }
  3532. static int ffs_ready(struct ffs_data *ffs)
  3533. {
  3534. struct ffs_dev *ffs_obj;
  3535. int ret = 0;
  3536. ffs_dev_lock();
  3537. ffs_obj = ffs->private_data;
  3538. if (!ffs_obj) {
  3539. ret = -EINVAL;
  3540. goto done;
  3541. }
  3542. if (WARN_ON(ffs_obj->desc_ready)) {
  3543. ret = -EBUSY;
  3544. goto done;
  3545. }
  3546. ffs_obj->desc_ready = true;
  3547. if (ffs_obj->ffs_ready_callback) {
  3548. ret = ffs_obj->ffs_ready_callback(ffs);
  3549. if (ret)
  3550. goto done;
  3551. }
  3552. set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
  3553. done:
  3554. ffs_dev_unlock();
  3555. return ret;
  3556. }
  3557. static void ffs_closed(struct ffs_data *ffs)
  3558. {
  3559. struct ffs_dev *ffs_obj;
  3560. struct f_fs_opts *opts;
  3561. struct config_item *ci;
  3562. ffs_dev_lock();
  3563. ffs_obj = ffs->private_data;
  3564. if (!ffs_obj)
  3565. goto done;
  3566. ffs_obj->desc_ready = false;
  3567. if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
  3568. ffs_obj->ffs_closed_callback)
  3569. ffs_obj->ffs_closed_callback(ffs);
  3570. if (ffs_obj->opts)
  3571. opts = ffs_obj->opts;
  3572. else
  3573. goto done;
  3574. if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
  3575. || !kref_read(&opts->func_inst.group.cg_item.ci_kref))
  3576. goto done;
  3577. ci = opts->func_inst.group.cg_item.ci_parent->ci_parent;
  3578. ffs_dev_unlock();
  3579. if (test_bit(FFS_FL_BOUND, &ffs->flags))
  3580. unregister_gadget_item(ci);
  3581. return;
  3582. done:
  3583. ffs_dev_unlock();
  3584. }
  3585. /* Misc helper functions ****************************************************/
  3586. static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
  3587. {
  3588. return nonblock
  3589. ? mutex_trylock(mutex) ? 0 : -EAGAIN
  3590. : mutex_lock_interruptible(mutex);
  3591. }
  3592. static char *ffs_prepare_buffer(const char __user *buf, size_t len)
  3593. {
  3594. char *data;
  3595. if (!len)
  3596. return NULL;
  3597. data = memdup_user(buf, len);
  3598. if (IS_ERR(data))
  3599. return data;
  3600. pr_vdebug("Buffer from user space:\n");
  3601. ffs_dump_mem("", data, len);
  3602. return data;
  3603. }
  3604. DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
  3605. MODULE_DESCRIPTION("user mode file system API for USB composite function controllers");
  3606. MODULE_LICENSE("GPL");
  3607. MODULE_AUTHOR("Michal Nazarewicz");