f_fs.c 87 KB

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