f_fs.c 87 KB

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