f_fs.c 88 KB

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