f_fs.c 87 KB

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