futex.c 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188
  1. /*
  2. * Fast Userspace Mutexes (which I call "Futexes!").
  3. * (C) Rusty Russell, IBM 2002
  4. *
  5. * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
  6. * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
  7. *
  8. * Removed page pinning, fix privately mapped COW pages and other cleanups
  9. * (C) Copyright 2003, 2004 Jamie Lokier
  10. *
  11. * Robust futex support started by Ingo Molnar
  12. * (C) Copyright 2006 Red Hat Inc, All Rights Reserved
  13. * Thanks to Thomas Gleixner for suggestions, analysis and fixes.
  14. *
  15. * PI-futex support started by Ingo Molnar and Thomas Gleixner
  16. * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  17. * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
  18. *
  19. * PRIVATE futexes by Eric Dumazet
  20. * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
  21. *
  22. * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
  23. * Copyright (C) IBM Corporation, 2009
  24. * Thanks to Thomas Gleixner for conceptual design and careful reviews.
  25. *
  26. * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
  27. * enough at me, Linus for the original (flawed) idea, Matthew
  28. * Kirkwood for proof-of-concept implementation.
  29. *
  30. * "The futexes are also cursed."
  31. * "But they come in a choice of three flavours!"
  32. *
  33. * This program is free software; you can redistribute it and/or modify
  34. * it under the terms of the GNU General Public License as published by
  35. * the Free Software Foundation; either version 2 of the License, or
  36. * (at your option) any later version.
  37. *
  38. * This program is distributed in the hope that it will be useful,
  39. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  40. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  41. * GNU General Public License for more details.
  42. *
  43. * You should have received a copy of the GNU General Public License
  44. * along with this program; if not, write to the Free Software
  45. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  46. */
  47. #include <linux/compat.h>
  48. #include <linux/slab.h>
  49. #include <linux/poll.h>
  50. #include <linux/fs.h>
  51. #include <linux/file.h>
  52. #include <linux/jhash.h>
  53. #include <linux/init.h>
  54. #include <linux/futex.h>
  55. #include <linux/mount.h>
  56. #include <linux/pagemap.h>
  57. #include <linux/syscalls.h>
  58. #include <linux/signal.h>
  59. #include <linux/export.h>
  60. #include <linux/magic.h>
  61. #include <linux/pid.h>
  62. #include <linux/nsproxy.h>
  63. #include <linux/ptrace.h>
  64. #include <linux/sched/rt.h>
  65. #include <linux/sched/wake_q.h>
  66. #include <linux/sched/mm.h>
  67. #include <linux/hugetlb.h>
  68. #include <linux/freezer.h>
  69. #include <linux/bootmem.h>
  70. #include <linux/fault-inject.h>
  71. #include <asm/futex.h>
  72. #include "locking/rtmutex_common.h"
  73. /*
  74. * READ this before attempting to hack on futexes!
  75. *
  76. * Basic futex operation and ordering guarantees
  77. * =============================================
  78. *
  79. * The waiter reads the futex value in user space and calls
  80. * futex_wait(). This function computes the hash bucket and acquires
  81. * the hash bucket lock. After that it reads the futex user space value
  82. * again and verifies that the data has not changed. If it has not changed
  83. * it enqueues itself into the hash bucket, releases the hash bucket lock
  84. * and schedules.
  85. *
  86. * The waker side modifies the user space value of the futex and calls
  87. * futex_wake(). This function computes the hash bucket and acquires the
  88. * hash bucket lock. Then it looks for waiters on that futex in the hash
  89. * bucket and wakes them.
  90. *
  91. * In futex wake up scenarios where no tasks are blocked on a futex, taking
  92. * the hb spinlock can be avoided and simply return. In order for this
  93. * optimization to work, ordering guarantees must exist so that the waiter
  94. * being added to the list is acknowledged when the list is concurrently being
  95. * checked by the waker, avoiding scenarios like the following:
  96. *
  97. * CPU 0 CPU 1
  98. * val = *futex;
  99. * sys_futex(WAIT, futex, val);
  100. * futex_wait(futex, val);
  101. * uval = *futex;
  102. * *futex = newval;
  103. * sys_futex(WAKE, futex);
  104. * futex_wake(futex);
  105. * if (queue_empty())
  106. * return;
  107. * if (uval == val)
  108. * lock(hash_bucket(futex));
  109. * queue();
  110. * unlock(hash_bucket(futex));
  111. * schedule();
  112. *
  113. * This would cause the waiter on CPU 0 to wait forever because it
  114. * missed the transition of the user space value from val to newval
  115. * and the waker did not find the waiter in the hash bucket queue.
  116. *
  117. * The correct serialization ensures that a waiter either observes
  118. * the changed user space value before blocking or is woken by a
  119. * concurrent waker:
  120. *
  121. * CPU 0 CPU 1
  122. * val = *futex;
  123. * sys_futex(WAIT, futex, val);
  124. * futex_wait(futex, val);
  125. *
  126. * waiters++; (a)
  127. * smp_mb(); (A) <-- paired with -.
  128. * |
  129. * lock(hash_bucket(futex)); |
  130. * |
  131. * uval = *futex; |
  132. * | *futex = newval;
  133. * | sys_futex(WAKE, futex);
  134. * | futex_wake(futex);
  135. * |
  136. * `--------> smp_mb(); (B)
  137. * if (uval == val)
  138. * queue();
  139. * unlock(hash_bucket(futex));
  140. * schedule(); if (waiters)
  141. * lock(hash_bucket(futex));
  142. * else wake_waiters(futex);
  143. * waiters--; (b) unlock(hash_bucket(futex));
  144. *
  145. * Where (A) orders the waiters increment and the futex value read through
  146. * atomic operations (see hb_waiters_inc) and where (B) orders the write
  147. * to futex and the waiters read -- this is done by the barriers for both
  148. * shared and private futexes in get_futex_key_refs().
  149. *
  150. * This yields the following case (where X:=waiters, Y:=futex):
  151. *
  152. * X = Y = 0
  153. *
  154. * w[X]=1 w[Y]=1
  155. * MB MB
  156. * r[Y]=y r[X]=x
  157. *
  158. * Which guarantees that x==0 && y==0 is impossible; which translates back into
  159. * the guarantee that we cannot both miss the futex variable change and the
  160. * enqueue.
  161. *
  162. * Note that a new waiter is accounted for in (a) even when it is possible that
  163. * the wait call can return error, in which case we backtrack from it in (b).
  164. * Refer to the comment in queue_lock().
  165. *
  166. * Similarly, in order to account for waiters being requeued on another
  167. * address we always increment the waiters for the destination bucket before
  168. * acquiring the lock. It then decrements them again after releasing it -
  169. * the code that actually moves the futex(es) between hash buckets (requeue_futex)
  170. * will do the additional required waiter count housekeeping. This is done for
  171. * double_lock_hb() and double_unlock_hb(), respectively.
  172. */
  173. #ifdef CONFIG_HAVE_FUTEX_CMPXCHG
  174. #define futex_cmpxchg_enabled 1
  175. #else
  176. static int __read_mostly futex_cmpxchg_enabled;
  177. #endif
  178. /*
  179. * Futex flags used to encode options to functions and preserve them across
  180. * restarts.
  181. */
  182. #ifdef CONFIG_MMU
  183. # define FLAGS_SHARED 0x01
  184. #else
  185. /*
  186. * NOMMU does not have per process address space. Let the compiler optimize
  187. * code away.
  188. */
  189. # define FLAGS_SHARED 0x00
  190. #endif
  191. #define FLAGS_CLOCKRT 0x02
  192. #define FLAGS_HAS_TIMEOUT 0x04
  193. /*
  194. * Priority Inheritance state:
  195. */
  196. struct futex_pi_state {
  197. /*
  198. * list of 'owned' pi_state instances - these have to be
  199. * cleaned up in do_exit() if the task exits prematurely:
  200. */
  201. struct list_head list;
  202. /*
  203. * The PI object:
  204. */
  205. struct rt_mutex pi_mutex;
  206. struct task_struct *owner;
  207. atomic_t refcount;
  208. union futex_key key;
  209. } __randomize_layout;
  210. /**
  211. * struct futex_q - The hashed futex queue entry, one per waiting task
  212. * @list: priority-sorted list of tasks waiting on this futex
  213. * @task: the task waiting on the futex
  214. * @lock_ptr: the hash bucket lock
  215. * @key: the key the futex is hashed on
  216. * @pi_state: optional priority inheritance state
  217. * @rt_waiter: rt_waiter storage for use with requeue_pi
  218. * @requeue_pi_key: the requeue_pi target futex key
  219. * @bitset: bitset for the optional bitmasked wakeup
  220. *
  221. * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
  222. * we can wake only the relevant ones (hashed queues may be shared).
  223. *
  224. * A futex_q has a woken state, just like tasks have TASK_RUNNING.
  225. * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
  226. * The order of wakeup is always to make the first condition true, then
  227. * the second.
  228. *
  229. * PI futexes are typically woken before they are removed from the hash list via
  230. * the rt_mutex code. See unqueue_me_pi().
  231. */
  232. struct futex_q {
  233. struct plist_node list;
  234. struct task_struct *task;
  235. spinlock_t *lock_ptr;
  236. union futex_key key;
  237. struct futex_pi_state *pi_state;
  238. struct rt_mutex_waiter *rt_waiter;
  239. union futex_key *requeue_pi_key;
  240. u32 bitset;
  241. } __randomize_layout;
  242. static const struct futex_q futex_q_init = {
  243. /* list gets initialized in queue_me()*/
  244. .key = FUTEX_KEY_INIT,
  245. .bitset = FUTEX_BITSET_MATCH_ANY
  246. };
  247. /*
  248. * Hash buckets are shared by all the futex_keys that hash to the same
  249. * location. Each key may have multiple futex_q structures, one for each task
  250. * waiting on a futex.
  251. */
  252. struct futex_hash_bucket {
  253. atomic_t waiters;
  254. spinlock_t lock;
  255. struct plist_head chain;
  256. } ____cacheline_aligned_in_smp;
  257. /*
  258. * The base of the bucket array and its size are always used together
  259. * (after initialization only in hash_futex()), so ensure that they
  260. * reside in the same cacheline.
  261. */
  262. static struct {
  263. struct futex_hash_bucket *queues;
  264. unsigned long hashsize;
  265. } __futex_data __read_mostly __aligned(2*sizeof(long));
  266. #define futex_queues (__futex_data.queues)
  267. #define futex_hashsize (__futex_data.hashsize)
  268. /*
  269. * Fault injections for futexes.
  270. */
  271. #ifdef CONFIG_FAIL_FUTEX
  272. static struct {
  273. struct fault_attr attr;
  274. bool ignore_private;
  275. } fail_futex = {
  276. .attr = FAULT_ATTR_INITIALIZER,
  277. .ignore_private = false,
  278. };
  279. static int __init setup_fail_futex(char *str)
  280. {
  281. return setup_fault_attr(&fail_futex.attr, str);
  282. }
  283. __setup("fail_futex=", setup_fail_futex);
  284. static bool should_fail_futex(bool fshared)
  285. {
  286. if (fail_futex.ignore_private && !fshared)
  287. return false;
  288. return should_fail(&fail_futex.attr, 1);
  289. }
  290. #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
  291. static int __init fail_futex_debugfs(void)
  292. {
  293. umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
  294. struct dentry *dir;
  295. dir = fault_create_debugfs_attr("fail_futex", NULL,
  296. &fail_futex.attr);
  297. if (IS_ERR(dir))
  298. return PTR_ERR(dir);
  299. if (!debugfs_create_bool("ignore-private", mode, dir,
  300. &fail_futex.ignore_private)) {
  301. debugfs_remove_recursive(dir);
  302. return -ENOMEM;
  303. }
  304. return 0;
  305. }
  306. late_initcall(fail_futex_debugfs);
  307. #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
  308. #else
  309. static inline bool should_fail_futex(bool fshared)
  310. {
  311. return false;
  312. }
  313. #endif /* CONFIG_FAIL_FUTEX */
  314. #ifdef CONFIG_COMPAT
  315. static void compat_exit_robust_list(struct task_struct *curr);
  316. #else
  317. static inline void compat_exit_robust_list(struct task_struct *curr) { }
  318. #endif
  319. static inline void futex_get_mm(union futex_key *key)
  320. {
  321. mmgrab(key->private.mm);
  322. /*
  323. * Ensure futex_get_mm() implies a full barrier such that
  324. * get_futex_key() implies a full barrier. This is relied upon
  325. * as smp_mb(); (B), see the ordering comment above.
  326. */
  327. smp_mb__after_atomic();
  328. }
  329. /*
  330. * Reflects a new waiter being added to the waitqueue.
  331. */
  332. static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
  333. {
  334. #ifdef CONFIG_SMP
  335. atomic_inc(&hb->waiters);
  336. /*
  337. * Full barrier (A), see the ordering comment above.
  338. */
  339. smp_mb__after_atomic();
  340. #endif
  341. }
  342. /*
  343. * Reflects a waiter being removed from the waitqueue by wakeup
  344. * paths.
  345. */
  346. static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
  347. {
  348. #ifdef CONFIG_SMP
  349. atomic_dec(&hb->waiters);
  350. #endif
  351. }
  352. static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
  353. {
  354. #ifdef CONFIG_SMP
  355. return atomic_read(&hb->waiters);
  356. #else
  357. return 1;
  358. #endif
  359. }
  360. /**
  361. * hash_futex - Return the hash bucket in the global hash
  362. * @key: Pointer to the futex key for which the hash is calculated
  363. *
  364. * We hash on the keys returned from get_futex_key (see below) and return the
  365. * corresponding hash bucket in the global hash.
  366. */
  367. static struct futex_hash_bucket *hash_futex(union futex_key *key)
  368. {
  369. u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
  370. key->both.offset);
  371. return &futex_queues[hash & (futex_hashsize - 1)];
  372. }
  373. /**
  374. * match_futex - Check whether two futex keys are equal
  375. * @key1: Pointer to key1
  376. * @key2: Pointer to key2
  377. *
  378. * Return 1 if two futex_keys are equal, 0 otherwise.
  379. */
  380. static inline int match_futex(union futex_key *key1, union futex_key *key2)
  381. {
  382. return (key1 && key2
  383. && key1->both.word == key2->both.word
  384. && key1->both.ptr == key2->both.ptr
  385. && key1->both.offset == key2->both.offset);
  386. }
  387. /*
  388. * Take a reference to the resource addressed by a key.
  389. * Can be called while holding spinlocks.
  390. *
  391. */
  392. static void get_futex_key_refs(union futex_key *key)
  393. {
  394. if (!key->both.ptr)
  395. return;
  396. /*
  397. * On MMU less systems futexes are always "private" as there is no per
  398. * process address space. We need the smp wmb nevertheless - yes,
  399. * arch/blackfin has MMU less SMP ...
  400. */
  401. if (!IS_ENABLED(CONFIG_MMU)) {
  402. smp_mb(); /* explicit smp_mb(); (B) */
  403. return;
  404. }
  405. switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
  406. case FUT_OFF_INODE:
  407. smp_mb(); /* explicit smp_mb(); (B) */
  408. break;
  409. case FUT_OFF_MMSHARED:
  410. futex_get_mm(key); /* implies smp_mb(); (B) */
  411. break;
  412. default:
  413. /*
  414. * Private futexes do not hold reference on an inode or
  415. * mm, therefore the only purpose of calling get_futex_key_refs
  416. * is because we need the barrier for the lockless waiter check.
  417. */
  418. smp_mb(); /* explicit smp_mb(); (B) */
  419. }
  420. }
  421. /*
  422. * Drop a reference to the resource addressed by a key.
  423. * The hash bucket spinlock must not be held. This is
  424. * a no-op for private futexes, see comment in the get
  425. * counterpart.
  426. */
  427. static void drop_futex_key_refs(union futex_key *key)
  428. {
  429. if (!key->both.ptr) {
  430. /* If we're here then we tried to put a key we failed to get */
  431. WARN_ON_ONCE(1);
  432. return;
  433. }
  434. if (!IS_ENABLED(CONFIG_MMU))
  435. return;
  436. switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
  437. case FUT_OFF_INODE:
  438. break;
  439. case FUT_OFF_MMSHARED:
  440. mmdrop(key->private.mm);
  441. break;
  442. }
  443. }
  444. /*
  445. * Generate a machine wide unique identifier for this inode.
  446. *
  447. * This relies on u64 not wrapping in the life-time of the machine; which with
  448. * 1ns resolution means almost 585 years.
  449. *
  450. * This further relies on the fact that a well formed program will not unmap
  451. * the file while it has a (shared) futex waiting on it. This mapping will have
  452. * a file reference which pins the mount and inode.
  453. *
  454. * If for some reason an inode gets evicted and read back in again, it will get
  455. * a new sequence number and will _NOT_ match, even though it is the exact same
  456. * file.
  457. *
  458. * It is important that match_futex() will never have a false-positive, esp.
  459. * for PI futexes that can mess up the state. The above argues that false-negatives
  460. * are only possible for malformed programs.
  461. */
  462. static u64 get_inode_sequence_number(struct inode *inode)
  463. {
  464. static atomic64_t i_seq;
  465. u64 old;
  466. /* Does the inode already have a sequence number? */
  467. old = atomic64_read(&inode->i_sequence);
  468. if (likely(old))
  469. return old;
  470. for (;;) {
  471. u64 new = atomic64_add_return(1, &i_seq);
  472. if (WARN_ON_ONCE(!new))
  473. continue;
  474. old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
  475. if (old)
  476. return old;
  477. return new;
  478. }
  479. }
  480. /**
  481. * get_futex_key() - Get parameters which are the keys for a futex
  482. * @uaddr: virtual address of the futex
  483. * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
  484. * @key: address where result is stored.
  485. * @rw: mapping needs to be read/write (values: VERIFY_READ,
  486. * VERIFY_WRITE)
  487. *
  488. * Return: a negative error code or 0
  489. *
  490. * The key words are stored in @key on success.
  491. *
  492. * For shared mappings (when @fshared), the key is:
  493. * ( inode->i_sequence, page->index, offset_within_page )
  494. * [ also see get_inode_sequence_number() ]
  495. *
  496. * For private mappings (or when !@fshared), the key is:
  497. * ( current->mm, address, 0 )
  498. *
  499. * This allows (cross process, where applicable) identification of the futex
  500. * without keeping the page pinned for the duration of the FUTEX_WAIT.
  501. *
  502. * lock_page() might sleep, the caller should not hold a spinlock.
  503. */
  504. static int
  505. get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
  506. {
  507. unsigned long address = (unsigned long)uaddr;
  508. struct mm_struct *mm = current->mm;
  509. struct page *page, *tail;
  510. struct address_space *mapping;
  511. int err, ro = 0;
  512. /*
  513. * The futex address must be "naturally" aligned.
  514. */
  515. key->both.offset = address % PAGE_SIZE;
  516. if (unlikely((address % sizeof(u32)) != 0))
  517. return -EINVAL;
  518. address -= key->both.offset;
  519. if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
  520. return -EFAULT;
  521. if (unlikely(should_fail_futex(fshared)))
  522. return -EFAULT;
  523. /*
  524. * PROCESS_PRIVATE futexes are fast.
  525. * As the mm cannot disappear under us and the 'key' only needs
  526. * virtual address, we dont even have to find the underlying vma.
  527. * Note : We do have to check 'uaddr' is a valid user address,
  528. * but access_ok() should be faster than find_vma()
  529. */
  530. if (!fshared) {
  531. key->private.mm = mm;
  532. key->private.address = address;
  533. get_futex_key_refs(key); /* implies smp_mb(); (B) */
  534. return 0;
  535. }
  536. again:
  537. /* Ignore any VERIFY_READ mapping (futex common case) */
  538. if (unlikely(should_fail_futex(fshared)))
  539. return -EFAULT;
  540. err = get_user_pages_fast(address, 1, 1, &page);
  541. /*
  542. * If write access is not required (eg. FUTEX_WAIT), try
  543. * and get read-only access.
  544. */
  545. if (err == -EFAULT && rw == VERIFY_READ) {
  546. err = get_user_pages_fast(address, 1, 0, &page);
  547. ro = 1;
  548. }
  549. if (err < 0)
  550. return err;
  551. else
  552. err = 0;
  553. /*
  554. * The treatment of mapping from this point on is critical. The page
  555. * lock protects many things but in this context the page lock
  556. * stabilizes mapping, prevents inode freeing in the shared
  557. * file-backed region case and guards against movement to swap cache.
  558. *
  559. * Strictly speaking the page lock is not needed in all cases being
  560. * considered here and page lock forces unnecessarily serialization
  561. * From this point on, mapping will be re-verified if necessary and
  562. * page lock will be acquired only if it is unavoidable
  563. *
  564. * Mapping checks require the head page for any compound page so the
  565. * head page and mapping is looked up now. For anonymous pages, it
  566. * does not matter if the page splits in the future as the key is
  567. * based on the address. For filesystem-backed pages, the tail is
  568. * required as the index of the page determines the key. For
  569. * base pages, there is no tail page and tail == page.
  570. */
  571. tail = page;
  572. page = compound_head(page);
  573. mapping = READ_ONCE(page->mapping);
  574. /*
  575. * If page->mapping is NULL, then it cannot be a PageAnon
  576. * page; but it might be the ZERO_PAGE or in the gate area or
  577. * in a special mapping (all cases which we are happy to fail);
  578. * or it may have been a good file page when get_user_pages_fast
  579. * found it, but truncated or holepunched or subjected to
  580. * invalidate_complete_page2 before we got the page lock (also
  581. * cases which we are happy to fail). And we hold a reference,
  582. * so refcount care in invalidate_complete_page's remove_mapping
  583. * prevents drop_caches from setting mapping to NULL beneath us.
  584. *
  585. * The case we do have to guard against is when memory pressure made
  586. * shmem_writepage move it from filecache to swapcache beneath us:
  587. * an unlikely race, but we do need to retry for page->mapping.
  588. */
  589. if (unlikely(!mapping)) {
  590. int shmem_swizzled;
  591. /*
  592. * Page lock is required to identify which special case above
  593. * applies. If this is really a shmem page then the page lock
  594. * will prevent unexpected transitions.
  595. */
  596. lock_page(page);
  597. shmem_swizzled = PageSwapCache(page) || page->mapping;
  598. unlock_page(page);
  599. put_page(page);
  600. if (shmem_swizzled)
  601. goto again;
  602. return -EFAULT;
  603. }
  604. /*
  605. * Private mappings are handled in a simple way.
  606. *
  607. * If the futex key is stored on an anonymous page, then the associated
  608. * object is the mm which is implicitly pinned by the calling process.
  609. *
  610. * NOTE: When userspace waits on a MAP_SHARED mapping, even if
  611. * it's a read-only handle, it's expected that futexes attach to
  612. * the object not the particular process.
  613. */
  614. if (PageAnon(page)) {
  615. /*
  616. * A RO anonymous page will never change and thus doesn't make
  617. * sense for futex operations.
  618. */
  619. if (unlikely(should_fail_futex(fshared)) || ro) {
  620. err = -EFAULT;
  621. goto out;
  622. }
  623. key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
  624. key->private.mm = mm;
  625. key->private.address = address;
  626. } else {
  627. struct inode *inode;
  628. /*
  629. * The associated futex object in this case is the inode and
  630. * the page->mapping must be traversed. Ordinarily this should
  631. * be stabilised under page lock but it's not strictly
  632. * necessary in this case as we just want to pin the inode, not
  633. * update the radix tree or anything like that.
  634. *
  635. * The RCU read lock is taken as the inode is finally freed
  636. * under RCU. If the mapping still matches expectations then the
  637. * mapping->host can be safely accessed as being a valid inode.
  638. */
  639. rcu_read_lock();
  640. if (READ_ONCE(page->mapping) != mapping) {
  641. rcu_read_unlock();
  642. put_page(page);
  643. goto again;
  644. }
  645. inode = READ_ONCE(mapping->host);
  646. if (!inode) {
  647. rcu_read_unlock();
  648. put_page(page);
  649. goto again;
  650. }
  651. key->both.offset |= FUT_OFF_INODE; /* inode-based key */
  652. key->shared.i_seq = get_inode_sequence_number(inode);
  653. key->shared.pgoff = basepage_index(tail);
  654. rcu_read_unlock();
  655. }
  656. get_futex_key_refs(key); /* implies smp_mb(); (B) */
  657. out:
  658. put_page(page);
  659. return err;
  660. }
  661. static inline void put_futex_key(union futex_key *key)
  662. {
  663. drop_futex_key_refs(key);
  664. }
  665. /**
  666. * fault_in_user_writeable() - Fault in user address and verify RW access
  667. * @uaddr: pointer to faulting user space address
  668. *
  669. * Slow path to fixup the fault we just took in the atomic write
  670. * access to @uaddr.
  671. *
  672. * We have no generic implementation of a non-destructive write to the
  673. * user address. We know that we faulted in the atomic pagefault
  674. * disabled section so we can as well avoid the #PF overhead by
  675. * calling get_user_pages() right away.
  676. */
  677. static int fault_in_user_writeable(u32 __user *uaddr)
  678. {
  679. struct mm_struct *mm = current->mm;
  680. int ret;
  681. down_read(&mm->mmap_sem);
  682. ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
  683. FAULT_FLAG_WRITE, NULL);
  684. up_read(&mm->mmap_sem);
  685. return ret < 0 ? ret : 0;
  686. }
  687. /**
  688. * futex_top_waiter() - Return the highest priority waiter on a futex
  689. * @hb: the hash bucket the futex_q's reside in
  690. * @key: the futex key (to distinguish it from other futex futex_q's)
  691. *
  692. * Must be called with the hb lock held.
  693. */
  694. static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
  695. union futex_key *key)
  696. {
  697. struct futex_q *this;
  698. plist_for_each_entry(this, &hb->chain, list) {
  699. if (match_futex(&this->key, key))
  700. return this;
  701. }
  702. return NULL;
  703. }
  704. static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
  705. u32 uval, u32 newval)
  706. {
  707. int ret;
  708. pagefault_disable();
  709. ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
  710. pagefault_enable();
  711. return ret;
  712. }
  713. static int get_futex_value_locked(u32 *dest, u32 __user *from)
  714. {
  715. int ret;
  716. pagefault_disable();
  717. ret = __get_user(*dest, from);
  718. pagefault_enable();
  719. return ret ? -EFAULT : 0;
  720. }
  721. /*
  722. * PI code:
  723. */
  724. static int refill_pi_state_cache(void)
  725. {
  726. struct futex_pi_state *pi_state;
  727. if (likely(current->pi_state_cache))
  728. return 0;
  729. pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
  730. if (!pi_state)
  731. return -ENOMEM;
  732. INIT_LIST_HEAD(&pi_state->list);
  733. /* pi_mutex gets initialized later */
  734. pi_state->owner = NULL;
  735. atomic_set(&pi_state->refcount, 1);
  736. pi_state->key = FUTEX_KEY_INIT;
  737. current->pi_state_cache = pi_state;
  738. return 0;
  739. }
  740. static struct futex_pi_state *alloc_pi_state(void)
  741. {
  742. struct futex_pi_state *pi_state = current->pi_state_cache;
  743. WARN_ON(!pi_state);
  744. current->pi_state_cache = NULL;
  745. return pi_state;
  746. }
  747. static void pi_state_update_owner(struct futex_pi_state *pi_state,
  748. struct task_struct *new_owner)
  749. {
  750. struct task_struct *old_owner = pi_state->owner;
  751. lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
  752. if (old_owner) {
  753. raw_spin_lock(&old_owner->pi_lock);
  754. WARN_ON(list_empty(&pi_state->list));
  755. list_del_init(&pi_state->list);
  756. raw_spin_unlock(&old_owner->pi_lock);
  757. }
  758. if (new_owner) {
  759. raw_spin_lock(&new_owner->pi_lock);
  760. WARN_ON(!list_empty(&pi_state->list));
  761. list_add(&pi_state->list, &new_owner->pi_state_list);
  762. pi_state->owner = new_owner;
  763. raw_spin_unlock(&new_owner->pi_lock);
  764. }
  765. }
  766. static void get_pi_state(struct futex_pi_state *pi_state)
  767. {
  768. WARN_ON_ONCE(!atomic_inc_not_zero(&pi_state->refcount));
  769. }
  770. /*
  771. * Drops a reference to the pi_state object and frees or caches it
  772. * when the last reference is gone.
  773. */
  774. static void put_pi_state(struct futex_pi_state *pi_state)
  775. {
  776. if (!pi_state)
  777. return;
  778. if (!atomic_dec_and_test(&pi_state->refcount))
  779. return;
  780. /*
  781. * If pi_state->owner is NULL, the owner is most probably dying
  782. * and has cleaned up the pi_state already
  783. */
  784. if (pi_state->owner) {
  785. unsigned long flags;
  786. raw_spin_lock_irqsave(&pi_state->pi_mutex.wait_lock, flags);
  787. pi_state_update_owner(pi_state, NULL);
  788. rt_mutex_proxy_unlock(&pi_state->pi_mutex);
  789. raw_spin_unlock_irqrestore(&pi_state->pi_mutex.wait_lock, flags);
  790. }
  791. if (current->pi_state_cache) {
  792. kfree(pi_state);
  793. } else {
  794. /*
  795. * pi_state->list is already empty.
  796. * clear pi_state->owner.
  797. * refcount is at 0 - put it back to 1.
  798. */
  799. pi_state->owner = NULL;
  800. atomic_set(&pi_state->refcount, 1);
  801. current->pi_state_cache = pi_state;
  802. }
  803. }
  804. #ifdef CONFIG_FUTEX_PI
  805. /*
  806. * This task is holding PI mutexes at exit time => bad.
  807. * Kernel cleans up PI-state, but userspace is likely hosed.
  808. * (Robust-futex cleanup is separate and might save the day for userspace.)
  809. */
  810. static void exit_pi_state_list(struct task_struct *curr)
  811. {
  812. struct list_head *next, *head = &curr->pi_state_list;
  813. struct futex_pi_state *pi_state;
  814. struct futex_hash_bucket *hb;
  815. union futex_key key = FUTEX_KEY_INIT;
  816. if (!futex_cmpxchg_enabled)
  817. return;
  818. /*
  819. * We are a ZOMBIE and nobody can enqueue itself on
  820. * pi_state_list anymore, but we have to be careful
  821. * versus waiters unqueueing themselves:
  822. */
  823. raw_spin_lock_irq(&curr->pi_lock);
  824. while (!list_empty(head)) {
  825. next = head->next;
  826. pi_state = list_entry(next, struct futex_pi_state, list);
  827. key = pi_state->key;
  828. hb = hash_futex(&key);
  829. /*
  830. * We can race against put_pi_state() removing itself from the
  831. * list (a waiter going away). put_pi_state() will first
  832. * decrement the reference count and then modify the list, so
  833. * its possible to see the list entry but fail this reference
  834. * acquire.
  835. *
  836. * In that case; drop the locks to let put_pi_state() make
  837. * progress and retry the loop.
  838. */
  839. if (!atomic_inc_not_zero(&pi_state->refcount)) {
  840. raw_spin_unlock_irq(&curr->pi_lock);
  841. cpu_relax();
  842. raw_spin_lock_irq(&curr->pi_lock);
  843. continue;
  844. }
  845. raw_spin_unlock_irq(&curr->pi_lock);
  846. spin_lock(&hb->lock);
  847. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  848. raw_spin_lock(&curr->pi_lock);
  849. /*
  850. * We dropped the pi-lock, so re-check whether this
  851. * task still owns the PI-state:
  852. */
  853. if (head->next != next) {
  854. /* retain curr->pi_lock for the loop invariant */
  855. raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
  856. spin_unlock(&hb->lock);
  857. put_pi_state(pi_state);
  858. continue;
  859. }
  860. WARN_ON(pi_state->owner != curr);
  861. WARN_ON(list_empty(&pi_state->list));
  862. list_del_init(&pi_state->list);
  863. pi_state->owner = NULL;
  864. raw_spin_unlock(&curr->pi_lock);
  865. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  866. spin_unlock(&hb->lock);
  867. rt_mutex_futex_unlock(&pi_state->pi_mutex);
  868. put_pi_state(pi_state);
  869. raw_spin_lock_irq(&curr->pi_lock);
  870. }
  871. raw_spin_unlock_irq(&curr->pi_lock);
  872. }
  873. #else
  874. static inline void exit_pi_state_list(struct task_struct *curr) { }
  875. #endif
  876. /*
  877. * We need to check the following states:
  878. *
  879. * Waiter | pi_state | pi->owner | uTID | uODIED | ?
  880. *
  881. * [1] NULL | --- | --- | 0 | 0/1 | Valid
  882. * [2] NULL | --- | --- | >0 | 0/1 | Valid
  883. *
  884. * [3] Found | NULL | -- | Any | 0/1 | Invalid
  885. *
  886. * [4] Found | Found | NULL | 0 | 1 | Valid
  887. * [5] Found | Found | NULL | >0 | 1 | Invalid
  888. *
  889. * [6] Found | Found | task | 0 | 1 | Valid
  890. *
  891. * [7] Found | Found | NULL | Any | 0 | Invalid
  892. *
  893. * [8] Found | Found | task | ==taskTID | 0/1 | Valid
  894. * [9] Found | Found | task | 0 | 0 | Invalid
  895. * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
  896. *
  897. * [1] Indicates that the kernel can acquire the futex atomically. We
  898. * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
  899. *
  900. * [2] Valid, if TID does not belong to a kernel thread. If no matching
  901. * thread is found then it indicates that the owner TID has died.
  902. *
  903. * [3] Invalid. The waiter is queued on a non PI futex
  904. *
  905. * [4] Valid state after exit_robust_list(), which sets the user space
  906. * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
  907. *
  908. * [5] The user space value got manipulated between exit_robust_list()
  909. * and exit_pi_state_list()
  910. *
  911. * [6] Valid state after exit_pi_state_list() which sets the new owner in
  912. * the pi_state but cannot access the user space value.
  913. *
  914. * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
  915. *
  916. * [8] Owner and user space value match
  917. *
  918. * [9] There is no transient state which sets the user space TID to 0
  919. * except exit_robust_list(), but this is indicated by the
  920. * FUTEX_OWNER_DIED bit. See [4]
  921. *
  922. * [10] There is no transient state which leaves owner and user space
  923. * TID out of sync. Except one error case where the kernel is denied
  924. * write access to the user address, see fixup_pi_state_owner().
  925. *
  926. *
  927. * Serialization and lifetime rules:
  928. *
  929. * hb->lock:
  930. *
  931. * hb -> futex_q, relation
  932. * futex_q -> pi_state, relation
  933. *
  934. * (cannot be raw because hb can contain arbitrary amount
  935. * of futex_q's)
  936. *
  937. * pi_mutex->wait_lock:
  938. *
  939. * {uval, pi_state}
  940. *
  941. * (and pi_mutex 'obviously')
  942. *
  943. * p->pi_lock:
  944. *
  945. * p->pi_state_list -> pi_state->list, relation
  946. *
  947. * pi_state->refcount:
  948. *
  949. * pi_state lifetime
  950. *
  951. *
  952. * Lock order:
  953. *
  954. * hb->lock
  955. * pi_mutex->wait_lock
  956. * p->pi_lock
  957. *
  958. */
  959. /*
  960. * Validate that the existing waiter has a pi_state and sanity check
  961. * the pi_state against the user space value. If correct, attach to
  962. * it.
  963. */
  964. static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
  965. struct futex_pi_state *pi_state,
  966. struct futex_pi_state **ps)
  967. {
  968. pid_t pid = uval & FUTEX_TID_MASK;
  969. u32 uval2;
  970. int ret;
  971. /*
  972. * Userspace might have messed up non-PI and PI futexes [3]
  973. */
  974. if (unlikely(!pi_state))
  975. return -EINVAL;
  976. /*
  977. * We get here with hb->lock held, and having found a
  978. * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
  979. * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
  980. * which in turn means that futex_lock_pi() still has a reference on
  981. * our pi_state.
  982. *
  983. * The waiter holding a reference on @pi_state also protects against
  984. * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
  985. * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
  986. * free pi_state before we can take a reference ourselves.
  987. */
  988. WARN_ON(!atomic_read(&pi_state->refcount));
  989. /*
  990. * Now that we have a pi_state, we can acquire wait_lock
  991. * and do the state validation.
  992. */
  993. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  994. /*
  995. * Since {uval, pi_state} is serialized by wait_lock, and our current
  996. * uval was read without holding it, it can have changed. Verify it
  997. * still is what we expect it to be, otherwise retry the entire
  998. * operation.
  999. */
  1000. if (get_futex_value_locked(&uval2, uaddr))
  1001. goto out_efault;
  1002. if (uval != uval2)
  1003. goto out_eagain;
  1004. /*
  1005. * Handle the owner died case:
  1006. */
  1007. if (uval & FUTEX_OWNER_DIED) {
  1008. /*
  1009. * exit_pi_state_list sets owner to NULL and wakes the
  1010. * topmost waiter. The task which acquires the
  1011. * pi_state->rt_mutex will fixup owner.
  1012. */
  1013. if (!pi_state->owner) {
  1014. /*
  1015. * No pi state owner, but the user space TID
  1016. * is not 0. Inconsistent state. [5]
  1017. */
  1018. if (pid)
  1019. goto out_einval;
  1020. /*
  1021. * Take a ref on the state and return success. [4]
  1022. */
  1023. goto out_attach;
  1024. }
  1025. /*
  1026. * If TID is 0, then either the dying owner has not
  1027. * yet executed exit_pi_state_list() or some waiter
  1028. * acquired the rtmutex in the pi state, but did not
  1029. * yet fixup the TID in user space.
  1030. *
  1031. * Take a ref on the state and return success. [6]
  1032. */
  1033. if (!pid)
  1034. goto out_attach;
  1035. } else {
  1036. /*
  1037. * If the owner died bit is not set, then the pi_state
  1038. * must have an owner. [7]
  1039. */
  1040. if (!pi_state->owner)
  1041. goto out_einval;
  1042. }
  1043. /*
  1044. * Bail out if user space manipulated the futex value. If pi
  1045. * state exists then the owner TID must be the same as the
  1046. * user space TID. [9/10]
  1047. */
  1048. if (pid != task_pid_vnr(pi_state->owner))
  1049. goto out_einval;
  1050. out_attach:
  1051. get_pi_state(pi_state);
  1052. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  1053. *ps = pi_state;
  1054. return 0;
  1055. out_einval:
  1056. ret = -EINVAL;
  1057. goto out_error;
  1058. out_eagain:
  1059. ret = -EAGAIN;
  1060. goto out_error;
  1061. out_efault:
  1062. ret = -EFAULT;
  1063. goto out_error;
  1064. out_error:
  1065. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  1066. return ret;
  1067. }
  1068. /**
  1069. * wait_for_owner_exiting - Block until the owner has exited
  1070. * @exiting: Pointer to the exiting task
  1071. *
  1072. * Caller must hold a refcount on @exiting.
  1073. */
  1074. static void wait_for_owner_exiting(int ret, struct task_struct *exiting)
  1075. {
  1076. if (ret != -EBUSY) {
  1077. WARN_ON_ONCE(exiting);
  1078. return;
  1079. }
  1080. if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
  1081. return;
  1082. mutex_lock(&exiting->futex_exit_mutex);
  1083. /*
  1084. * No point in doing state checking here. If the waiter got here
  1085. * while the task was in exec()->exec_futex_release() then it can
  1086. * have any FUTEX_STATE_* value when the waiter has acquired the
  1087. * mutex. OK, if running, EXITING or DEAD if it reached exit()
  1088. * already. Highly unlikely and not a problem. Just one more round
  1089. * through the futex maze.
  1090. */
  1091. mutex_unlock(&exiting->futex_exit_mutex);
  1092. put_task_struct(exiting);
  1093. }
  1094. static int handle_exit_race(u32 __user *uaddr, u32 uval,
  1095. struct task_struct *tsk)
  1096. {
  1097. u32 uval2;
  1098. /*
  1099. * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
  1100. * caller that the alleged owner is busy.
  1101. */
  1102. if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
  1103. return -EBUSY;
  1104. /*
  1105. * Reread the user space value to handle the following situation:
  1106. *
  1107. * CPU0 CPU1
  1108. *
  1109. * sys_exit() sys_futex()
  1110. * do_exit() futex_lock_pi()
  1111. * futex_lock_pi_atomic()
  1112. * exit_signals(tsk) No waiters:
  1113. * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
  1114. * mm_release(tsk) Set waiter bit
  1115. * exit_robust_list(tsk) { *uaddr = 0x80000PID;
  1116. * Set owner died attach_to_pi_owner() {
  1117. * *uaddr = 0xC0000000; tsk = get_task(PID);
  1118. * } if (!tsk->flags & PF_EXITING) {
  1119. * ... attach();
  1120. * tsk->futex_state = } else {
  1121. * FUTEX_STATE_DEAD; if (tsk->futex_state !=
  1122. * FUTEX_STATE_DEAD)
  1123. * return -EAGAIN;
  1124. * return -ESRCH; <--- FAIL
  1125. * }
  1126. *
  1127. * Returning ESRCH unconditionally is wrong here because the
  1128. * user space value has been changed by the exiting task.
  1129. *
  1130. * The same logic applies to the case where the exiting task is
  1131. * already gone.
  1132. */
  1133. if (get_futex_value_locked(&uval2, uaddr))
  1134. return -EFAULT;
  1135. /* If the user space value has changed, try again. */
  1136. if (uval2 != uval)
  1137. return -EAGAIN;
  1138. /*
  1139. * The exiting task did not have a robust list, the robust list was
  1140. * corrupted or the user space value in *uaddr is simply bogus.
  1141. * Give up and tell user space.
  1142. */
  1143. return -ESRCH;
  1144. }
  1145. /*
  1146. * Lookup the task for the TID provided from user space and attach to
  1147. * it after doing proper sanity checks.
  1148. */
  1149. static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
  1150. struct futex_pi_state **ps,
  1151. struct task_struct **exiting)
  1152. {
  1153. pid_t pid = uval & FUTEX_TID_MASK;
  1154. struct futex_pi_state *pi_state;
  1155. struct task_struct *p;
  1156. /*
  1157. * We are the first waiter - try to look up the real owner and attach
  1158. * the new pi_state to it, but bail out when TID = 0 [1]
  1159. *
  1160. * The !pid check is paranoid. None of the call sites should end up
  1161. * with pid == 0, but better safe than sorry. Let the caller retry
  1162. */
  1163. if (!pid)
  1164. return -EAGAIN;
  1165. p = find_get_task_by_vpid(pid);
  1166. if (!p)
  1167. return handle_exit_race(uaddr, uval, NULL);
  1168. if (unlikely(p->flags & PF_KTHREAD)) {
  1169. put_task_struct(p);
  1170. return -EPERM;
  1171. }
  1172. /*
  1173. * We need to look at the task state to figure out, whether the
  1174. * task is exiting. To protect against the change of the task state
  1175. * in futex_exit_release(), we do this protected by p->pi_lock:
  1176. */
  1177. raw_spin_lock_irq(&p->pi_lock);
  1178. if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
  1179. /*
  1180. * The task is on the way out. When the futex state is
  1181. * FUTEX_STATE_DEAD, we know that the task has finished
  1182. * the cleanup:
  1183. */
  1184. int ret = handle_exit_race(uaddr, uval, p);
  1185. raw_spin_unlock_irq(&p->pi_lock);
  1186. /*
  1187. * If the owner task is between FUTEX_STATE_EXITING and
  1188. * FUTEX_STATE_DEAD then store the task pointer and keep
  1189. * the reference on the task struct. The calling code will
  1190. * drop all locks, wait for the task to reach
  1191. * FUTEX_STATE_DEAD and then drop the refcount. This is
  1192. * required to prevent a live lock when the current task
  1193. * preempted the exiting task between the two states.
  1194. */
  1195. if (ret == -EBUSY)
  1196. *exiting = p;
  1197. else
  1198. put_task_struct(p);
  1199. return ret;
  1200. }
  1201. /*
  1202. * No existing pi state. First waiter. [2]
  1203. *
  1204. * This creates pi_state, we have hb->lock held, this means nothing can
  1205. * observe this state, wait_lock is irrelevant.
  1206. */
  1207. pi_state = alloc_pi_state();
  1208. /*
  1209. * Initialize the pi_mutex in locked state and make @p
  1210. * the owner of it:
  1211. */
  1212. rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
  1213. /* Store the key for possible exit cleanups: */
  1214. pi_state->key = *key;
  1215. WARN_ON(!list_empty(&pi_state->list));
  1216. list_add(&pi_state->list, &p->pi_state_list);
  1217. /*
  1218. * Assignment without holding pi_state->pi_mutex.wait_lock is safe
  1219. * because there is no concurrency as the object is not published yet.
  1220. */
  1221. pi_state->owner = p;
  1222. raw_spin_unlock_irq(&p->pi_lock);
  1223. put_task_struct(p);
  1224. *ps = pi_state;
  1225. return 0;
  1226. }
  1227. static int lookup_pi_state(u32 __user *uaddr, u32 uval,
  1228. struct futex_hash_bucket *hb,
  1229. union futex_key *key, struct futex_pi_state **ps,
  1230. struct task_struct **exiting)
  1231. {
  1232. struct futex_q *top_waiter = futex_top_waiter(hb, key);
  1233. /*
  1234. * If there is a waiter on that futex, validate it and
  1235. * attach to the pi_state when the validation succeeds.
  1236. */
  1237. if (top_waiter)
  1238. return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
  1239. /*
  1240. * We are the first waiter - try to look up the owner based on
  1241. * @uval and attach to it.
  1242. */
  1243. return attach_to_pi_owner(uaddr, uval, key, ps, exiting);
  1244. }
  1245. static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
  1246. {
  1247. int err;
  1248. u32 uninitialized_var(curval);
  1249. if (unlikely(should_fail_futex(true)))
  1250. return -EFAULT;
  1251. err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
  1252. if (unlikely(err))
  1253. return err;
  1254. /* If user space value changed, let the caller retry */
  1255. return curval != uval ? -EAGAIN : 0;
  1256. }
  1257. /**
  1258. * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
  1259. * @uaddr: the pi futex user address
  1260. * @hb: the pi futex hash bucket
  1261. * @key: the futex key associated with uaddr and hb
  1262. * @ps: the pi_state pointer where we store the result of the
  1263. * lookup
  1264. * @task: the task to perform the atomic lock work for. This will
  1265. * be "current" except in the case of requeue pi.
  1266. * @exiting: Pointer to store the task pointer of the owner task
  1267. * which is in the middle of exiting
  1268. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
  1269. *
  1270. * Return:
  1271. * - 0 - ready to wait;
  1272. * - 1 - acquired the lock;
  1273. * - <0 - error
  1274. *
  1275. * The hb->lock and futex_key refs shall be held by the caller.
  1276. *
  1277. * @exiting is only set when the return value is -EBUSY. If so, this holds
  1278. * a refcount on the exiting task on return and the caller needs to drop it
  1279. * after waiting for the exit to complete.
  1280. */
  1281. static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
  1282. union futex_key *key,
  1283. struct futex_pi_state **ps,
  1284. struct task_struct *task,
  1285. struct task_struct **exiting,
  1286. int set_waiters)
  1287. {
  1288. u32 uval, newval, vpid = task_pid_vnr(task);
  1289. struct futex_q *top_waiter;
  1290. int ret;
  1291. /*
  1292. * Read the user space value first so we can validate a few
  1293. * things before proceeding further.
  1294. */
  1295. if (get_futex_value_locked(&uval, uaddr))
  1296. return -EFAULT;
  1297. if (unlikely(should_fail_futex(true)))
  1298. return -EFAULT;
  1299. /*
  1300. * Detect deadlocks.
  1301. */
  1302. if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
  1303. return -EDEADLK;
  1304. if ((unlikely(should_fail_futex(true))))
  1305. return -EDEADLK;
  1306. /*
  1307. * Lookup existing state first. If it exists, try to attach to
  1308. * its pi_state.
  1309. */
  1310. top_waiter = futex_top_waiter(hb, key);
  1311. if (top_waiter)
  1312. return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
  1313. /*
  1314. * No waiter and user TID is 0. We are here because the
  1315. * waiters or the owner died bit is set or called from
  1316. * requeue_cmp_pi or for whatever reason something took the
  1317. * syscall.
  1318. */
  1319. if (!(uval & FUTEX_TID_MASK)) {
  1320. /*
  1321. * We take over the futex. No other waiters and the user space
  1322. * TID is 0. We preserve the owner died bit.
  1323. */
  1324. newval = uval & FUTEX_OWNER_DIED;
  1325. newval |= vpid;
  1326. /* The futex requeue_pi code can enforce the waiters bit */
  1327. if (set_waiters)
  1328. newval |= FUTEX_WAITERS;
  1329. ret = lock_pi_update_atomic(uaddr, uval, newval);
  1330. /* If the take over worked, return 1 */
  1331. return ret < 0 ? ret : 1;
  1332. }
  1333. /*
  1334. * First waiter. Set the waiters bit before attaching ourself to
  1335. * the owner. If owner tries to unlock, it will be forced into
  1336. * the kernel and blocked on hb->lock.
  1337. */
  1338. newval = uval | FUTEX_WAITERS;
  1339. ret = lock_pi_update_atomic(uaddr, uval, newval);
  1340. if (ret)
  1341. return ret;
  1342. /*
  1343. * If the update of the user space value succeeded, we try to
  1344. * attach to the owner. If that fails, no harm done, we only
  1345. * set the FUTEX_WAITERS bit in the user space variable.
  1346. */
  1347. return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
  1348. }
  1349. /**
  1350. * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
  1351. * @q: The futex_q to unqueue
  1352. *
  1353. * The q->lock_ptr must not be NULL and must be held by the caller.
  1354. */
  1355. static void __unqueue_futex(struct futex_q *q)
  1356. {
  1357. struct futex_hash_bucket *hb;
  1358. if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
  1359. || WARN_ON(plist_node_empty(&q->list)))
  1360. return;
  1361. hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
  1362. plist_del(&q->list, &hb->chain);
  1363. hb_waiters_dec(hb);
  1364. }
  1365. /*
  1366. * The hash bucket lock must be held when this is called.
  1367. * Afterwards, the futex_q must not be accessed. Callers
  1368. * must ensure to later call wake_up_q() for the actual
  1369. * wakeups to occur.
  1370. */
  1371. static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
  1372. {
  1373. struct task_struct *p = q->task;
  1374. if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
  1375. return;
  1376. get_task_struct(p);
  1377. __unqueue_futex(q);
  1378. /*
  1379. * The waiting task can free the futex_q as soon as q->lock_ptr = NULL
  1380. * is written, without taking any locks. This is possible in the event
  1381. * of a spurious wakeup, for example. A memory barrier is required here
  1382. * to prevent the following store to lock_ptr from getting ahead of the
  1383. * plist_del in __unqueue_futex().
  1384. */
  1385. smp_store_release(&q->lock_ptr, NULL);
  1386. /*
  1387. * Queue the task for later wakeup for after we've released
  1388. * the hb->lock. wake_q_add() grabs reference to p.
  1389. */
  1390. wake_q_add(wake_q, p);
  1391. put_task_struct(p);
  1392. }
  1393. /*
  1394. * Caller must hold a reference on @pi_state.
  1395. */
  1396. static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
  1397. {
  1398. u32 uninitialized_var(curval), newval;
  1399. struct task_struct *new_owner;
  1400. bool postunlock = false;
  1401. DEFINE_WAKE_Q(wake_q);
  1402. int ret = 0;
  1403. new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
  1404. if (WARN_ON_ONCE(!new_owner)) {
  1405. /*
  1406. * As per the comment in futex_unlock_pi() this should not happen.
  1407. *
  1408. * When this happens, give up our locks and try again, giving
  1409. * the futex_lock_pi() instance time to complete, either by
  1410. * waiting on the rtmutex or removing itself from the futex
  1411. * queue.
  1412. */
  1413. ret = -EAGAIN;
  1414. goto out_unlock;
  1415. }
  1416. /*
  1417. * We pass it to the next owner. The WAITERS bit is always kept
  1418. * enabled while there is PI state around. We cleanup the owner
  1419. * died bit, because we are the owner.
  1420. */
  1421. newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
  1422. if (unlikely(should_fail_futex(true))) {
  1423. ret = -EFAULT;
  1424. goto out_unlock;
  1425. }
  1426. ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
  1427. if (!ret && (curval != uval)) {
  1428. /*
  1429. * If a unconditional UNLOCK_PI operation (user space did not
  1430. * try the TID->0 transition) raced with a waiter setting the
  1431. * FUTEX_WAITERS flag between get_user() and locking the hash
  1432. * bucket lock, retry the operation.
  1433. */
  1434. if ((FUTEX_TID_MASK & curval) == uval)
  1435. ret = -EAGAIN;
  1436. else
  1437. ret = -EINVAL;
  1438. }
  1439. if (!ret) {
  1440. /*
  1441. * This is a point of no return; once we modified the uval
  1442. * there is no going back and subsequent operations must
  1443. * not fail.
  1444. */
  1445. pi_state_update_owner(pi_state, new_owner);
  1446. postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wake_q);
  1447. }
  1448. out_unlock:
  1449. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  1450. if (postunlock)
  1451. rt_mutex_postunlock(&wake_q);
  1452. return ret;
  1453. }
  1454. /*
  1455. * Express the locking dependencies for lockdep:
  1456. */
  1457. static inline void
  1458. double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
  1459. {
  1460. if (hb1 <= hb2) {
  1461. spin_lock(&hb1->lock);
  1462. if (hb1 < hb2)
  1463. spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
  1464. } else { /* hb1 > hb2 */
  1465. spin_lock(&hb2->lock);
  1466. spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
  1467. }
  1468. }
  1469. static inline void
  1470. double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
  1471. {
  1472. spin_unlock(&hb1->lock);
  1473. if (hb1 != hb2)
  1474. spin_unlock(&hb2->lock);
  1475. }
  1476. /*
  1477. * Wake up waiters matching bitset queued on this futex (uaddr).
  1478. */
  1479. static int
  1480. futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
  1481. {
  1482. struct futex_hash_bucket *hb;
  1483. struct futex_q *this, *next;
  1484. union futex_key key = FUTEX_KEY_INIT;
  1485. int ret;
  1486. DEFINE_WAKE_Q(wake_q);
  1487. if (!bitset)
  1488. return -EINVAL;
  1489. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
  1490. if (unlikely(ret != 0))
  1491. goto out;
  1492. hb = hash_futex(&key);
  1493. /* Make sure we really have tasks to wakeup */
  1494. if (!hb_waiters_pending(hb))
  1495. goto out_put_key;
  1496. spin_lock(&hb->lock);
  1497. plist_for_each_entry_safe(this, next, &hb->chain, list) {
  1498. if (match_futex (&this->key, &key)) {
  1499. if (this->pi_state || this->rt_waiter) {
  1500. ret = -EINVAL;
  1501. break;
  1502. }
  1503. /* Check if one of the bits is set in both bitsets */
  1504. if (!(this->bitset & bitset))
  1505. continue;
  1506. mark_wake_futex(&wake_q, this);
  1507. if (++ret >= nr_wake)
  1508. break;
  1509. }
  1510. }
  1511. spin_unlock(&hb->lock);
  1512. wake_up_q(&wake_q);
  1513. out_put_key:
  1514. put_futex_key(&key);
  1515. out:
  1516. return ret;
  1517. }
  1518. static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
  1519. {
  1520. unsigned int op = (encoded_op & 0x70000000) >> 28;
  1521. unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
  1522. int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
  1523. int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
  1524. int oldval, ret;
  1525. if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
  1526. if (oparg < 0 || oparg > 31) {
  1527. char comm[sizeof(current->comm)];
  1528. /*
  1529. * kill this print and return -EINVAL when userspace
  1530. * is sane again
  1531. */
  1532. pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
  1533. get_task_comm(comm, current), oparg);
  1534. oparg &= 31;
  1535. }
  1536. oparg = 1 << oparg;
  1537. }
  1538. if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))
  1539. return -EFAULT;
  1540. ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
  1541. if (ret)
  1542. return ret;
  1543. switch (cmp) {
  1544. case FUTEX_OP_CMP_EQ:
  1545. return oldval == cmparg;
  1546. case FUTEX_OP_CMP_NE:
  1547. return oldval != cmparg;
  1548. case FUTEX_OP_CMP_LT:
  1549. return oldval < cmparg;
  1550. case FUTEX_OP_CMP_GE:
  1551. return oldval >= cmparg;
  1552. case FUTEX_OP_CMP_LE:
  1553. return oldval <= cmparg;
  1554. case FUTEX_OP_CMP_GT:
  1555. return oldval > cmparg;
  1556. default:
  1557. return -ENOSYS;
  1558. }
  1559. }
  1560. /*
  1561. * Wake up all waiters hashed on the physical page that is mapped
  1562. * to this virtual address:
  1563. */
  1564. static int
  1565. futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
  1566. int nr_wake, int nr_wake2, int op)
  1567. {
  1568. union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
  1569. struct futex_hash_bucket *hb1, *hb2;
  1570. struct futex_q *this, *next;
  1571. int ret, op_ret;
  1572. DEFINE_WAKE_Q(wake_q);
  1573. retry:
  1574. ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
  1575. if (unlikely(ret != 0))
  1576. goto out;
  1577. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
  1578. if (unlikely(ret != 0))
  1579. goto out_put_key1;
  1580. hb1 = hash_futex(&key1);
  1581. hb2 = hash_futex(&key2);
  1582. retry_private:
  1583. double_lock_hb(hb1, hb2);
  1584. op_ret = futex_atomic_op_inuser(op, uaddr2);
  1585. if (unlikely(op_ret < 0)) {
  1586. double_unlock_hb(hb1, hb2);
  1587. if (!IS_ENABLED(CONFIG_MMU) ||
  1588. unlikely(op_ret != -EFAULT && op_ret != -EAGAIN)) {
  1589. /*
  1590. * we don't get EFAULT from MMU faults if we don't have
  1591. * an MMU, but we might get them from range checking
  1592. */
  1593. ret = op_ret;
  1594. goto out_put_keys;
  1595. }
  1596. if (op_ret == -EFAULT) {
  1597. ret = fault_in_user_writeable(uaddr2);
  1598. if (ret)
  1599. goto out_put_keys;
  1600. }
  1601. if (!(flags & FLAGS_SHARED)) {
  1602. cond_resched();
  1603. goto retry_private;
  1604. }
  1605. put_futex_key(&key2);
  1606. put_futex_key(&key1);
  1607. cond_resched();
  1608. goto retry;
  1609. }
  1610. plist_for_each_entry_safe(this, next, &hb1->chain, list) {
  1611. if (match_futex (&this->key, &key1)) {
  1612. if (this->pi_state || this->rt_waiter) {
  1613. ret = -EINVAL;
  1614. goto out_unlock;
  1615. }
  1616. mark_wake_futex(&wake_q, this);
  1617. if (++ret >= nr_wake)
  1618. break;
  1619. }
  1620. }
  1621. if (op_ret > 0) {
  1622. op_ret = 0;
  1623. plist_for_each_entry_safe(this, next, &hb2->chain, list) {
  1624. if (match_futex (&this->key, &key2)) {
  1625. if (this->pi_state || this->rt_waiter) {
  1626. ret = -EINVAL;
  1627. goto out_unlock;
  1628. }
  1629. mark_wake_futex(&wake_q, this);
  1630. if (++op_ret >= nr_wake2)
  1631. break;
  1632. }
  1633. }
  1634. ret += op_ret;
  1635. }
  1636. out_unlock:
  1637. double_unlock_hb(hb1, hb2);
  1638. wake_up_q(&wake_q);
  1639. out_put_keys:
  1640. put_futex_key(&key2);
  1641. out_put_key1:
  1642. put_futex_key(&key1);
  1643. out:
  1644. return ret;
  1645. }
  1646. /**
  1647. * requeue_futex() - Requeue a futex_q from one hb to another
  1648. * @q: the futex_q to requeue
  1649. * @hb1: the source hash_bucket
  1650. * @hb2: the target hash_bucket
  1651. * @key2: the new key for the requeued futex_q
  1652. */
  1653. static inline
  1654. void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
  1655. struct futex_hash_bucket *hb2, union futex_key *key2)
  1656. {
  1657. /*
  1658. * If key1 and key2 hash to the same bucket, no need to
  1659. * requeue.
  1660. */
  1661. if (likely(&hb1->chain != &hb2->chain)) {
  1662. plist_del(&q->list, &hb1->chain);
  1663. hb_waiters_dec(hb1);
  1664. hb_waiters_inc(hb2);
  1665. plist_add(&q->list, &hb2->chain);
  1666. q->lock_ptr = &hb2->lock;
  1667. }
  1668. get_futex_key_refs(key2);
  1669. q->key = *key2;
  1670. }
  1671. /**
  1672. * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
  1673. * @q: the futex_q
  1674. * @key: the key of the requeue target futex
  1675. * @hb: the hash_bucket of the requeue target futex
  1676. *
  1677. * During futex_requeue, with requeue_pi=1, it is possible to acquire the
  1678. * target futex if it is uncontended or via a lock steal. Set the futex_q key
  1679. * to the requeue target futex so the waiter can detect the wakeup on the right
  1680. * futex, but remove it from the hb and NULL the rt_waiter so it can detect
  1681. * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
  1682. * to protect access to the pi_state to fixup the owner later. Must be called
  1683. * with both q->lock_ptr and hb->lock held.
  1684. */
  1685. static inline
  1686. void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
  1687. struct futex_hash_bucket *hb)
  1688. {
  1689. get_futex_key_refs(key);
  1690. q->key = *key;
  1691. __unqueue_futex(q);
  1692. WARN_ON(!q->rt_waiter);
  1693. q->rt_waiter = NULL;
  1694. q->lock_ptr = &hb->lock;
  1695. wake_up_state(q->task, TASK_NORMAL);
  1696. }
  1697. /**
  1698. * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
  1699. * @pifutex: the user address of the to futex
  1700. * @hb1: the from futex hash bucket, must be locked by the caller
  1701. * @hb2: the to futex hash bucket, must be locked by the caller
  1702. * @key1: the from futex key
  1703. * @key2: the to futex key
  1704. * @ps: address to store the pi_state pointer
  1705. * @exiting: Pointer to store the task pointer of the owner task
  1706. * which is in the middle of exiting
  1707. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
  1708. *
  1709. * Try and get the lock on behalf of the top waiter if we can do it atomically.
  1710. * Wake the top waiter if we succeed. If the caller specified set_waiters,
  1711. * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
  1712. * hb1 and hb2 must be held by the caller.
  1713. *
  1714. * @exiting is only set when the return value is -EBUSY. If so, this holds
  1715. * a refcount on the exiting task on return and the caller needs to drop it
  1716. * after waiting for the exit to complete.
  1717. *
  1718. * Return:
  1719. * - 0 - failed to acquire the lock atomically;
  1720. * - >0 - acquired the lock, return value is vpid of the top_waiter
  1721. * - <0 - error
  1722. */
  1723. static int
  1724. futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
  1725. struct futex_hash_bucket *hb2, union futex_key *key1,
  1726. union futex_key *key2, struct futex_pi_state **ps,
  1727. struct task_struct **exiting, int set_waiters)
  1728. {
  1729. struct futex_q *top_waiter = NULL;
  1730. u32 curval;
  1731. int ret, vpid;
  1732. if (get_futex_value_locked(&curval, pifutex))
  1733. return -EFAULT;
  1734. if (unlikely(should_fail_futex(true)))
  1735. return -EFAULT;
  1736. /*
  1737. * Find the top_waiter and determine if there are additional waiters.
  1738. * If the caller intends to requeue more than 1 waiter to pifutex,
  1739. * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
  1740. * as we have means to handle the possible fault. If not, don't set
  1741. * the bit unecessarily as it will force the subsequent unlock to enter
  1742. * the kernel.
  1743. */
  1744. top_waiter = futex_top_waiter(hb1, key1);
  1745. /* There are no waiters, nothing for us to do. */
  1746. if (!top_waiter)
  1747. return 0;
  1748. /* Ensure we requeue to the expected futex. */
  1749. if (!match_futex(top_waiter->requeue_pi_key, key2))
  1750. return -EINVAL;
  1751. /*
  1752. * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
  1753. * the contended case or if set_waiters is 1. The pi_state is returned
  1754. * in ps in contended cases.
  1755. */
  1756. vpid = task_pid_vnr(top_waiter->task);
  1757. ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
  1758. exiting, set_waiters);
  1759. if (ret == 1) {
  1760. requeue_pi_wake_futex(top_waiter, key2, hb2);
  1761. return vpid;
  1762. }
  1763. return ret;
  1764. }
  1765. /**
  1766. * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
  1767. * @uaddr1: source futex user address
  1768. * @flags: futex flags (FLAGS_SHARED, etc.)
  1769. * @uaddr2: target futex user address
  1770. * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
  1771. * @nr_requeue: number of waiters to requeue (0-INT_MAX)
  1772. * @cmpval: @uaddr1 expected value (or %NULL)
  1773. * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
  1774. * pi futex (pi to pi requeue is not supported)
  1775. *
  1776. * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
  1777. * uaddr2 atomically on behalf of the top waiter.
  1778. *
  1779. * Return:
  1780. * - >=0 - on success, the number of tasks requeued or woken;
  1781. * - <0 - on error
  1782. */
  1783. static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
  1784. u32 __user *uaddr2, int nr_wake, int nr_requeue,
  1785. u32 *cmpval, int requeue_pi)
  1786. {
  1787. union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
  1788. int drop_count = 0, task_count = 0, ret;
  1789. struct futex_pi_state *pi_state = NULL;
  1790. struct futex_hash_bucket *hb1, *hb2;
  1791. struct futex_q *this, *next;
  1792. DEFINE_WAKE_Q(wake_q);
  1793. if (nr_wake < 0 || nr_requeue < 0)
  1794. return -EINVAL;
  1795. /*
  1796. * When PI not supported: return -ENOSYS if requeue_pi is true,
  1797. * consequently the compiler knows requeue_pi is always false past
  1798. * this point which will optimize away all the conditional code
  1799. * further down.
  1800. */
  1801. if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
  1802. return -ENOSYS;
  1803. if (requeue_pi) {
  1804. /*
  1805. * Requeue PI only works on two distinct uaddrs. This
  1806. * check is only valid for private futexes. See below.
  1807. */
  1808. if (uaddr1 == uaddr2)
  1809. return -EINVAL;
  1810. /*
  1811. * requeue_pi requires a pi_state, try to allocate it now
  1812. * without any locks in case it fails.
  1813. */
  1814. if (refill_pi_state_cache())
  1815. return -ENOMEM;
  1816. /*
  1817. * requeue_pi must wake as many tasks as it can, up to nr_wake
  1818. * + nr_requeue, since it acquires the rt_mutex prior to
  1819. * returning to userspace, so as to not leave the rt_mutex with
  1820. * waiters and no owner. However, second and third wake-ups
  1821. * cannot be predicted as they involve race conditions with the
  1822. * first wake and a fault while looking up the pi_state. Both
  1823. * pthread_cond_signal() and pthread_cond_broadcast() should
  1824. * use nr_wake=1.
  1825. */
  1826. if (nr_wake != 1)
  1827. return -EINVAL;
  1828. }
  1829. retry:
  1830. ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
  1831. if (unlikely(ret != 0))
  1832. goto out;
  1833. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
  1834. requeue_pi ? VERIFY_WRITE : VERIFY_READ);
  1835. if (unlikely(ret != 0))
  1836. goto out_put_key1;
  1837. /*
  1838. * The check above which compares uaddrs is not sufficient for
  1839. * shared futexes. We need to compare the keys:
  1840. */
  1841. if (requeue_pi && match_futex(&key1, &key2)) {
  1842. ret = -EINVAL;
  1843. goto out_put_keys;
  1844. }
  1845. hb1 = hash_futex(&key1);
  1846. hb2 = hash_futex(&key2);
  1847. retry_private:
  1848. hb_waiters_inc(hb2);
  1849. double_lock_hb(hb1, hb2);
  1850. if (likely(cmpval != NULL)) {
  1851. u32 curval;
  1852. ret = get_futex_value_locked(&curval, uaddr1);
  1853. if (unlikely(ret)) {
  1854. double_unlock_hb(hb1, hb2);
  1855. hb_waiters_dec(hb2);
  1856. ret = get_user(curval, uaddr1);
  1857. if (ret)
  1858. goto out_put_keys;
  1859. if (!(flags & FLAGS_SHARED))
  1860. goto retry_private;
  1861. put_futex_key(&key2);
  1862. put_futex_key(&key1);
  1863. goto retry;
  1864. }
  1865. if (curval != *cmpval) {
  1866. ret = -EAGAIN;
  1867. goto out_unlock;
  1868. }
  1869. }
  1870. if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
  1871. struct task_struct *exiting = NULL;
  1872. /*
  1873. * Attempt to acquire uaddr2 and wake the top waiter. If we
  1874. * intend to requeue waiters, force setting the FUTEX_WAITERS
  1875. * bit. We force this here where we are able to easily handle
  1876. * faults rather in the requeue loop below.
  1877. */
  1878. ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
  1879. &key2, &pi_state,
  1880. &exiting, nr_requeue);
  1881. /*
  1882. * At this point the top_waiter has either taken uaddr2 or is
  1883. * waiting on it. If the former, then the pi_state will not
  1884. * exist yet, look it up one more time to ensure we have a
  1885. * reference to it. If the lock was taken, ret contains the
  1886. * vpid of the top waiter task.
  1887. * If the lock was not taken, we have pi_state and an initial
  1888. * refcount on it. In case of an error we have nothing.
  1889. */
  1890. if (ret > 0) {
  1891. WARN_ON(pi_state);
  1892. drop_count++;
  1893. task_count++;
  1894. /*
  1895. * If we acquired the lock, then the user space value
  1896. * of uaddr2 should be vpid. It cannot be changed by
  1897. * the top waiter as it is blocked on hb2 lock if it
  1898. * tries to do so. If something fiddled with it behind
  1899. * our back the pi state lookup might unearth it. So
  1900. * we rather use the known value than rereading and
  1901. * handing potential crap to lookup_pi_state.
  1902. *
  1903. * If that call succeeds then we have pi_state and an
  1904. * initial refcount on it.
  1905. */
  1906. ret = lookup_pi_state(uaddr2, ret, hb2, &key2,
  1907. &pi_state, &exiting);
  1908. }
  1909. switch (ret) {
  1910. case 0:
  1911. /* We hold a reference on the pi state. */
  1912. break;
  1913. /* If the above failed, then pi_state is NULL */
  1914. case -EFAULT:
  1915. double_unlock_hb(hb1, hb2);
  1916. hb_waiters_dec(hb2);
  1917. put_futex_key(&key2);
  1918. put_futex_key(&key1);
  1919. ret = fault_in_user_writeable(uaddr2);
  1920. if (!ret)
  1921. goto retry;
  1922. goto out;
  1923. case -EBUSY:
  1924. case -EAGAIN:
  1925. /*
  1926. * Two reasons for this:
  1927. * - EBUSY: Owner is exiting and we just wait for the
  1928. * exit to complete.
  1929. * - EAGAIN: The user space value changed.
  1930. */
  1931. double_unlock_hb(hb1, hb2);
  1932. hb_waiters_dec(hb2);
  1933. put_futex_key(&key2);
  1934. put_futex_key(&key1);
  1935. /*
  1936. * Handle the case where the owner is in the middle of
  1937. * exiting. Wait for the exit to complete otherwise
  1938. * this task might loop forever, aka. live lock.
  1939. */
  1940. wait_for_owner_exiting(ret, exiting);
  1941. cond_resched();
  1942. goto retry;
  1943. default:
  1944. goto out_unlock;
  1945. }
  1946. }
  1947. plist_for_each_entry_safe(this, next, &hb1->chain, list) {
  1948. if (task_count - nr_wake >= nr_requeue)
  1949. break;
  1950. if (!match_futex(&this->key, &key1))
  1951. continue;
  1952. /*
  1953. * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
  1954. * be paired with each other and no other futex ops.
  1955. *
  1956. * We should never be requeueing a futex_q with a pi_state,
  1957. * which is awaiting a futex_unlock_pi().
  1958. */
  1959. if ((requeue_pi && !this->rt_waiter) ||
  1960. (!requeue_pi && this->rt_waiter) ||
  1961. this->pi_state) {
  1962. ret = -EINVAL;
  1963. break;
  1964. }
  1965. /*
  1966. * Wake nr_wake waiters. For requeue_pi, if we acquired the
  1967. * lock, we already woke the top_waiter. If not, it will be
  1968. * woken by futex_unlock_pi().
  1969. */
  1970. if (++task_count <= nr_wake && !requeue_pi) {
  1971. mark_wake_futex(&wake_q, this);
  1972. continue;
  1973. }
  1974. /* Ensure we requeue to the expected futex for requeue_pi. */
  1975. if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
  1976. ret = -EINVAL;
  1977. break;
  1978. }
  1979. /*
  1980. * Requeue nr_requeue waiters and possibly one more in the case
  1981. * of requeue_pi if we couldn't acquire the lock atomically.
  1982. */
  1983. if (requeue_pi) {
  1984. /*
  1985. * Prepare the waiter to take the rt_mutex. Take a
  1986. * refcount on the pi_state and store the pointer in
  1987. * the futex_q object of the waiter.
  1988. */
  1989. get_pi_state(pi_state);
  1990. this->pi_state = pi_state;
  1991. ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
  1992. this->rt_waiter,
  1993. this->task);
  1994. if (ret == 1) {
  1995. /*
  1996. * We got the lock. We do neither drop the
  1997. * refcount on pi_state nor clear
  1998. * this->pi_state because the waiter needs the
  1999. * pi_state for cleaning up the user space
  2000. * value. It will drop the refcount after
  2001. * doing so.
  2002. */
  2003. requeue_pi_wake_futex(this, &key2, hb2);
  2004. drop_count++;
  2005. continue;
  2006. } else if (ret) {
  2007. /*
  2008. * rt_mutex_start_proxy_lock() detected a
  2009. * potential deadlock when we tried to queue
  2010. * that waiter. Drop the pi_state reference
  2011. * which we took above and remove the pointer
  2012. * to the state from the waiters futex_q
  2013. * object.
  2014. */
  2015. this->pi_state = NULL;
  2016. put_pi_state(pi_state);
  2017. /*
  2018. * We stop queueing more waiters and let user
  2019. * space deal with the mess.
  2020. */
  2021. break;
  2022. }
  2023. }
  2024. requeue_futex(this, hb1, hb2, &key2);
  2025. drop_count++;
  2026. }
  2027. /*
  2028. * We took an extra initial reference to the pi_state either
  2029. * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
  2030. * need to drop it here again.
  2031. */
  2032. put_pi_state(pi_state);
  2033. out_unlock:
  2034. double_unlock_hb(hb1, hb2);
  2035. wake_up_q(&wake_q);
  2036. hb_waiters_dec(hb2);
  2037. /*
  2038. * drop_futex_key_refs() must be called outside the spinlocks. During
  2039. * the requeue we moved futex_q's from the hash bucket at key1 to the
  2040. * one at key2 and updated their key pointer. We no longer need to
  2041. * hold the references to key1.
  2042. */
  2043. while (--drop_count >= 0)
  2044. drop_futex_key_refs(&key1);
  2045. out_put_keys:
  2046. put_futex_key(&key2);
  2047. out_put_key1:
  2048. put_futex_key(&key1);
  2049. out:
  2050. return ret ? ret : task_count;
  2051. }
  2052. /* The key must be already stored in q->key. */
  2053. static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
  2054. __acquires(&hb->lock)
  2055. {
  2056. struct futex_hash_bucket *hb;
  2057. hb = hash_futex(&q->key);
  2058. /*
  2059. * Increment the counter before taking the lock so that
  2060. * a potential waker won't miss a to-be-slept task that is
  2061. * waiting for the spinlock. This is safe as all queue_lock()
  2062. * users end up calling queue_me(). Similarly, for housekeeping,
  2063. * decrement the counter at queue_unlock() when some error has
  2064. * occurred and we don't end up adding the task to the list.
  2065. */
  2066. hb_waiters_inc(hb);
  2067. q->lock_ptr = &hb->lock;
  2068. spin_lock(&hb->lock); /* implies smp_mb(); (A) */
  2069. return hb;
  2070. }
  2071. static inline void
  2072. queue_unlock(struct futex_hash_bucket *hb)
  2073. __releases(&hb->lock)
  2074. {
  2075. spin_unlock(&hb->lock);
  2076. hb_waiters_dec(hb);
  2077. }
  2078. static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
  2079. {
  2080. int prio;
  2081. /*
  2082. * The priority used to register this element is
  2083. * - either the real thread-priority for the real-time threads
  2084. * (i.e. threads with a priority lower than MAX_RT_PRIO)
  2085. * - or MAX_RT_PRIO for non-RT threads.
  2086. * Thus, all RT-threads are woken first in priority order, and
  2087. * the others are woken last, in FIFO order.
  2088. */
  2089. prio = min(current->normal_prio, MAX_RT_PRIO);
  2090. plist_node_init(&q->list, prio);
  2091. plist_add(&q->list, &hb->chain);
  2092. q->task = current;
  2093. }
  2094. /**
  2095. * queue_me() - Enqueue the futex_q on the futex_hash_bucket
  2096. * @q: The futex_q to enqueue
  2097. * @hb: The destination hash bucket
  2098. *
  2099. * The hb->lock must be held by the caller, and is released here. A call to
  2100. * queue_me() is typically paired with exactly one call to unqueue_me(). The
  2101. * exceptions involve the PI related operations, which may use unqueue_me_pi()
  2102. * or nothing if the unqueue is done as part of the wake process and the unqueue
  2103. * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
  2104. * an example).
  2105. */
  2106. static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
  2107. __releases(&hb->lock)
  2108. {
  2109. __queue_me(q, hb);
  2110. spin_unlock(&hb->lock);
  2111. }
  2112. /**
  2113. * unqueue_me() - Remove the futex_q from its futex_hash_bucket
  2114. * @q: The futex_q to unqueue
  2115. *
  2116. * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
  2117. * be paired with exactly one earlier call to queue_me().
  2118. *
  2119. * Return:
  2120. * - 1 - if the futex_q was still queued (and we removed unqueued it);
  2121. * - 0 - if the futex_q was already removed by the waking thread
  2122. */
  2123. static int unqueue_me(struct futex_q *q)
  2124. {
  2125. spinlock_t *lock_ptr;
  2126. int ret = 0;
  2127. /* In the common case we don't take the spinlock, which is nice. */
  2128. retry:
  2129. /*
  2130. * q->lock_ptr can change between this read and the following spin_lock.
  2131. * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
  2132. * optimizing lock_ptr out of the logic below.
  2133. */
  2134. lock_ptr = READ_ONCE(q->lock_ptr);
  2135. if (lock_ptr != NULL) {
  2136. spin_lock(lock_ptr);
  2137. /*
  2138. * q->lock_ptr can change between reading it and
  2139. * spin_lock(), causing us to take the wrong lock. This
  2140. * corrects the race condition.
  2141. *
  2142. * Reasoning goes like this: if we have the wrong lock,
  2143. * q->lock_ptr must have changed (maybe several times)
  2144. * between reading it and the spin_lock(). It can
  2145. * change again after the spin_lock() but only if it was
  2146. * already changed before the spin_lock(). It cannot,
  2147. * however, change back to the original value. Therefore
  2148. * we can detect whether we acquired the correct lock.
  2149. */
  2150. if (unlikely(lock_ptr != q->lock_ptr)) {
  2151. spin_unlock(lock_ptr);
  2152. goto retry;
  2153. }
  2154. __unqueue_futex(q);
  2155. BUG_ON(q->pi_state);
  2156. spin_unlock(lock_ptr);
  2157. ret = 1;
  2158. }
  2159. drop_futex_key_refs(&q->key);
  2160. return ret;
  2161. }
  2162. /*
  2163. * PI futexes can not be requeued and must remove themself from the
  2164. * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
  2165. * and dropped here.
  2166. */
  2167. static void unqueue_me_pi(struct futex_q *q)
  2168. __releases(q->lock_ptr)
  2169. {
  2170. __unqueue_futex(q);
  2171. BUG_ON(!q->pi_state);
  2172. put_pi_state(q->pi_state);
  2173. q->pi_state = NULL;
  2174. spin_unlock(q->lock_ptr);
  2175. }
  2176. static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
  2177. struct task_struct *argowner)
  2178. {
  2179. u32 uval, uninitialized_var(curval), newval, newtid;
  2180. struct futex_pi_state *pi_state = q->pi_state;
  2181. struct task_struct *oldowner, *newowner;
  2182. int err = 0;
  2183. oldowner = pi_state->owner;
  2184. /*
  2185. * We are here because either:
  2186. *
  2187. * - we stole the lock and pi_state->owner needs updating to reflect
  2188. * that (@argowner == current),
  2189. *
  2190. * or:
  2191. *
  2192. * - someone stole our lock and we need to fix things to point to the
  2193. * new owner (@argowner == NULL).
  2194. *
  2195. * Either way, we have to replace the TID in the user space variable.
  2196. * This must be atomic as we have to preserve the owner died bit here.
  2197. *
  2198. * Note: We write the user space value _before_ changing the pi_state
  2199. * because we can fault here. Imagine swapped out pages or a fork
  2200. * that marked all the anonymous memory readonly for cow.
  2201. *
  2202. * Modifying pi_state _before_ the user space value would leave the
  2203. * pi_state in an inconsistent state when we fault here, because we
  2204. * need to drop the locks to handle the fault. This might be observed
  2205. * in the PID check in lookup_pi_state.
  2206. */
  2207. retry:
  2208. if (!argowner) {
  2209. if (oldowner != current) {
  2210. /*
  2211. * We raced against a concurrent self; things are
  2212. * already fixed up. Nothing to do.
  2213. */
  2214. return 0;
  2215. }
  2216. if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
  2217. /* We got the lock. pi_state is correct. Tell caller. */
  2218. return 1;
  2219. }
  2220. /*
  2221. * The trylock just failed, so either there is an owner or
  2222. * there is a higher priority waiter than this one.
  2223. */
  2224. newowner = rt_mutex_owner(&pi_state->pi_mutex);
  2225. /*
  2226. * If the higher priority waiter has not yet taken over the
  2227. * rtmutex then newowner is NULL. We can't return here with
  2228. * that state because it's inconsistent vs. the user space
  2229. * state. So drop the locks and try again. It's a valid
  2230. * situation and not any different from the other retry
  2231. * conditions.
  2232. */
  2233. if (unlikely(!newowner)) {
  2234. err = -EAGAIN;
  2235. goto handle_err;
  2236. }
  2237. } else {
  2238. WARN_ON_ONCE(argowner != current);
  2239. if (oldowner == current) {
  2240. /*
  2241. * We raced against a concurrent self; things are
  2242. * already fixed up. Nothing to do.
  2243. */
  2244. return 1;
  2245. }
  2246. newowner = argowner;
  2247. }
  2248. newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
  2249. /* Owner died? */
  2250. if (!pi_state->owner)
  2251. newtid |= FUTEX_OWNER_DIED;
  2252. err = get_futex_value_locked(&uval, uaddr);
  2253. if (err)
  2254. goto handle_err;
  2255. for (;;) {
  2256. newval = (uval & FUTEX_OWNER_DIED) | newtid;
  2257. err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
  2258. if (err)
  2259. goto handle_err;
  2260. if (curval == uval)
  2261. break;
  2262. uval = curval;
  2263. }
  2264. /*
  2265. * We fixed up user space. Now we need to fix the pi_state
  2266. * itself.
  2267. */
  2268. pi_state_update_owner(pi_state, newowner);
  2269. return argowner == current;
  2270. /*
  2271. * In order to reschedule or handle a page fault, we need to drop the
  2272. * locks here. In the case of a fault, this gives the other task
  2273. * (either the highest priority waiter itself or the task which stole
  2274. * the rtmutex) the chance to try the fixup of the pi_state. So once we
  2275. * are back from handling the fault we need to check the pi_state after
  2276. * reacquiring the locks and before trying to do another fixup. When
  2277. * the fixup has been done already we simply return.
  2278. *
  2279. * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
  2280. * drop hb->lock since the caller owns the hb -> futex_q relation.
  2281. * Dropping the pi_mutex->wait_lock requires the state revalidate.
  2282. */
  2283. handle_err:
  2284. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  2285. spin_unlock(q->lock_ptr);
  2286. switch (err) {
  2287. case -EFAULT:
  2288. err = fault_in_user_writeable(uaddr);
  2289. break;
  2290. case -EAGAIN:
  2291. cond_resched();
  2292. err = 0;
  2293. break;
  2294. default:
  2295. WARN_ON_ONCE(1);
  2296. break;
  2297. }
  2298. spin_lock(q->lock_ptr);
  2299. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  2300. /*
  2301. * Check if someone else fixed it for us:
  2302. */
  2303. if (pi_state->owner != oldowner)
  2304. return argowner == current;
  2305. /* Retry if err was -EAGAIN or the fault in succeeded */
  2306. if (!err)
  2307. goto retry;
  2308. /*
  2309. * fault_in_user_writeable() failed so user state is immutable. At
  2310. * best we can make the kernel state consistent but user state will
  2311. * be most likely hosed and any subsequent unlock operation will be
  2312. * rejected due to PI futex rule [10].
  2313. *
  2314. * Ensure that the rtmutex owner is also the pi_state owner despite
  2315. * the user space value claiming something different. There is no
  2316. * point in unlocking the rtmutex if current is the owner as it
  2317. * would need to wait until the next waiter has taken the rtmutex
  2318. * to guarantee consistent state. Keep it simple. Userspace asked
  2319. * for this wreckaged state.
  2320. *
  2321. * The rtmutex has an owner - either current or some other
  2322. * task. See the EAGAIN loop above.
  2323. */
  2324. pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
  2325. return err;
  2326. }
  2327. static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
  2328. struct task_struct *argowner)
  2329. {
  2330. struct futex_pi_state *pi_state = q->pi_state;
  2331. int ret;
  2332. lockdep_assert_held(q->lock_ptr);
  2333. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  2334. ret = __fixup_pi_state_owner(uaddr, q, argowner);
  2335. raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
  2336. return ret;
  2337. }
  2338. static long futex_wait_restart(struct restart_block *restart);
  2339. /**
  2340. * fixup_owner() - Post lock pi_state and corner case management
  2341. * @uaddr: user address of the futex
  2342. * @q: futex_q (contains pi_state and access to the rt_mutex)
  2343. * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
  2344. *
  2345. * After attempting to lock an rt_mutex, this function is called to cleanup
  2346. * the pi_state owner as well as handle race conditions that may allow us to
  2347. * acquire the lock. Must be called with the hb lock held.
  2348. *
  2349. * Return:
  2350. * - 1 - success, lock taken;
  2351. * - 0 - success, lock not taken;
  2352. * - <0 - on error (-EFAULT)
  2353. */
  2354. static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
  2355. {
  2356. if (locked) {
  2357. /*
  2358. * Got the lock. We might not be the anticipated owner if we
  2359. * did a lock-steal - fix up the PI-state in that case:
  2360. *
  2361. * Speculative pi_state->owner read (we don't hold wait_lock);
  2362. * since we own the lock pi_state->owner == current is the
  2363. * stable state, anything else needs more attention.
  2364. */
  2365. if (q->pi_state->owner != current)
  2366. return fixup_pi_state_owner(uaddr, q, current);
  2367. return 1;
  2368. }
  2369. /*
  2370. * If we didn't get the lock; check if anybody stole it from us. In
  2371. * that case, we need to fix up the uval to point to them instead of
  2372. * us, otherwise bad things happen. [10]
  2373. *
  2374. * Another speculative read; pi_state->owner == current is unstable
  2375. * but needs our attention.
  2376. */
  2377. if (q->pi_state->owner == current)
  2378. return fixup_pi_state_owner(uaddr, q, NULL);
  2379. /*
  2380. * Paranoia check. If we did not take the lock, then we should not be
  2381. * the owner of the rt_mutex. Warn and establish consistent state.
  2382. */
  2383. if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
  2384. return fixup_pi_state_owner(uaddr, q, current);
  2385. return 0;
  2386. }
  2387. /**
  2388. * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
  2389. * @hb: the futex hash bucket, must be locked by the caller
  2390. * @q: the futex_q to queue up on
  2391. * @timeout: the prepared hrtimer_sleeper, or null for no timeout
  2392. */
  2393. static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
  2394. struct hrtimer_sleeper *timeout)
  2395. {
  2396. /*
  2397. * The task state is guaranteed to be set before another task can
  2398. * wake it. set_current_state() is implemented using smp_store_mb() and
  2399. * queue_me() calls spin_unlock() upon completion, both serializing
  2400. * access to the hash list and forcing another memory barrier.
  2401. */
  2402. set_current_state(TASK_INTERRUPTIBLE);
  2403. queue_me(q, hb);
  2404. /* Arm the timer */
  2405. if (timeout)
  2406. hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
  2407. /*
  2408. * If we have been removed from the hash list, then another task
  2409. * has tried to wake us, and we can skip the call to schedule().
  2410. */
  2411. if (likely(!plist_node_empty(&q->list))) {
  2412. /*
  2413. * If the timer has already expired, current will already be
  2414. * flagged for rescheduling. Only call schedule if there
  2415. * is no timeout, or if it has yet to expire.
  2416. */
  2417. if (!timeout || timeout->task)
  2418. freezable_schedule();
  2419. }
  2420. __set_current_state(TASK_RUNNING);
  2421. }
  2422. /**
  2423. * futex_wait_setup() - Prepare to wait on a futex
  2424. * @uaddr: the futex userspace address
  2425. * @val: the expected value
  2426. * @flags: futex flags (FLAGS_SHARED, etc.)
  2427. * @q: the associated futex_q
  2428. * @hb: storage for hash_bucket pointer to be returned to caller
  2429. *
  2430. * Setup the futex_q and locate the hash_bucket. Get the futex value and
  2431. * compare it with the expected value. Handle atomic faults internally.
  2432. * Return with the hb lock held and a q.key reference on success, and unlocked
  2433. * with no q.key reference on failure.
  2434. *
  2435. * Return:
  2436. * - 0 - uaddr contains val and hb has been locked;
  2437. * - <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
  2438. */
  2439. static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
  2440. struct futex_q *q, struct futex_hash_bucket **hb)
  2441. {
  2442. u32 uval;
  2443. int ret;
  2444. /*
  2445. * Access the page AFTER the hash-bucket is locked.
  2446. * Order is important:
  2447. *
  2448. * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
  2449. * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
  2450. *
  2451. * The basic logical guarantee of a futex is that it blocks ONLY
  2452. * if cond(var) is known to be true at the time of blocking, for
  2453. * any cond. If we locked the hash-bucket after testing *uaddr, that
  2454. * would open a race condition where we could block indefinitely with
  2455. * cond(var) false, which would violate the guarantee.
  2456. *
  2457. * On the other hand, we insert q and release the hash-bucket only
  2458. * after testing *uaddr. This guarantees that futex_wait() will NOT
  2459. * absorb a wakeup if *uaddr does not match the desired values
  2460. * while the syscall executes.
  2461. */
  2462. retry:
  2463. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
  2464. if (unlikely(ret != 0))
  2465. return ret;
  2466. retry_private:
  2467. *hb = queue_lock(q);
  2468. ret = get_futex_value_locked(&uval, uaddr);
  2469. if (ret) {
  2470. queue_unlock(*hb);
  2471. ret = get_user(uval, uaddr);
  2472. if (ret)
  2473. goto out;
  2474. if (!(flags & FLAGS_SHARED))
  2475. goto retry_private;
  2476. put_futex_key(&q->key);
  2477. goto retry;
  2478. }
  2479. if (uval != val) {
  2480. queue_unlock(*hb);
  2481. ret = -EWOULDBLOCK;
  2482. }
  2483. out:
  2484. if (ret)
  2485. put_futex_key(&q->key);
  2486. return ret;
  2487. }
  2488. static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
  2489. ktime_t *abs_time, u32 bitset)
  2490. {
  2491. struct hrtimer_sleeper timeout, *to = NULL;
  2492. struct restart_block *restart;
  2493. struct futex_hash_bucket *hb;
  2494. struct futex_q q = futex_q_init;
  2495. int ret;
  2496. if (!bitset)
  2497. return -EINVAL;
  2498. q.bitset = bitset;
  2499. if (abs_time) {
  2500. to = &timeout;
  2501. hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
  2502. CLOCK_REALTIME : CLOCK_MONOTONIC,
  2503. HRTIMER_MODE_ABS);
  2504. hrtimer_init_sleeper(to, current);
  2505. hrtimer_set_expires_range_ns(&to->timer, *abs_time,
  2506. current->timer_slack_ns);
  2507. }
  2508. retry:
  2509. /*
  2510. * Prepare to wait on uaddr. On success, holds hb lock and increments
  2511. * q.key refs.
  2512. */
  2513. ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
  2514. if (ret)
  2515. goto out;
  2516. /* queue_me and wait for wakeup, timeout, or a signal. */
  2517. futex_wait_queue_me(hb, &q, to);
  2518. /* If we were woken (and unqueued), we succeeded, whatever. */
  2519. ret = 0;
  2520. /* unqueue_me() drops q.key ref */
  2521. if (!unqueue_me(&q))
  2522. goto out;
  2523. ret = -ETIMEDOUT;
  2524. if (to && !to->task)
  2525. goto out;
  2526. /*
  2527. * We expect signal_pending(current), but we might be the
  2528. * victim of a spurious wakeup as well.
  2529. */
  2530. if (!signal_pending(current))
  2531. goto retry;
  2532. ret = -ERESTARTSYS;
  2533. if (!abs_time)
  2534. goto out;
  2535. restart = &current->restart_block;
  2536. restart->futex.uaddr = uaddr;
  2537. restart->futex.val = val;
  2538. restart->futex.time = *abs_time;
  2539. restart->futex.bitset = bitset;
  2540. restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
  2541. ret = set_restart_fn(restart, futex_wait_restart);
  2542. out:
  2543. if (to) {
  2544. hrtimer_cancel(&to->timer);
  2545. destroy_hrtimer_on_stack(&to->timer);
  2546. }
  2547. return ret;
  2548. }
  2549. static long futex_wait_restart(struct restart_block *restart)
  2550. {
  2551. u32 __user *uaddr = restart->futex.uaddr;
  2552. ktime_t t, *tp = NULL;
  2553. if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
  2554. t = restart->futex.time;
  2555. tp = &t;
  2556. }
  2557. restart->fn = do_no_restart_syscall;
  2558. return (long)futex_wait(uaddr, restart->futex.flags,
  2559. restart->futex.val, tp, restart->futex.bitset);
  2560. }
  2561. /*
  2562. * Userspace tried a 0 -> TID atomic transition of the futex value
  2563. * and failed. The kernel side here does the whole locking operation:
  2564. * if there are waiters then it will block as a consequence of relying
  2565. * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
  2566. * a 0 value of the futex too.).
  2567. *
  2568. * Also serves as futex trylock_pi()'ing, and due semantics.
  2569. */
  2570. static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
  2571. ktime_t *time, int trylock)
  2572. {
  2573. struct hrtimer_sleeper timeout, *to = NULL;
  2574. struct task_struct *exiting = NULL;
  2575. struct rt_mutex_waiter rt_waiter;
  2576. struct futex_hash_bucket *hb;
  2577. struct futex_q q = futex_q_init;
  2578. int res, ret;
  2579. if (!IS_ENABLED(CONFIG_FUTEX_PI))
  2580. return -ENOSYS;
  2581. if (refill_pi_state_cache())
  2582. return -ENOMEM;
  2583. if (time) {
  2584. to = &timeout;
  2585. hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
  2586. HRTIMER_MODE_ABS);
  2587. hrtimer_init_sleeper(to, current);
  2588. hrtimer_set_expires(&to->timer, *time);
  2589. }
  2590. retry:
  2591. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
  2592. if (unlikely(ret != 0))
  2593. goto out;
  2594. retry_private:
  2595. hb = queue_lock(&q);
  2596. ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
  2597. &exiting, 0);
  2598. if (unlikely(ret)) {
  2599. /*
  2600. * Atomic work succeeded and we got the lock,
  2601. * or failed. Either way, we do _not_ block.
  2602. */
  2603. switch (ret) {
  2604. case 1:
  2605. /* We got the lock. */
  2606. ret = 0;
  2607. goto out_unlock_put_key;
  2608. case -EFAULT:
  2609. goto uaddr_faulted;
  2610. case -EBUSY:
  2611. case -EAGAIN:
  2612. /*
  2613. * Two reasons for this:
  2614. * - EBUSY: Task is exiting and we just wait for the
  2615. * exit to complete.
  2616. * - EAGAIN: The user space value changed.
  2617. */
  2618. queue_unlock(hb);
  2619. put_futex_key(&q.key);
  2620. /*
  2621. * Handle the case where the owner is in the middle of
  2622. * exiting. Wait for the exit to complete otherwise
  2623. * this task might loop forever, aka. live lock.
  2624. */
  2625. wait_for_owner_exiting(ret, exiting);
  2626. cond_resched();
  2627. goto retry;
  2628. default:
  2629. goto out_unlock_put_key;
  2630. }
  2631. }
  2632. WARN_ON(!q.pi_state);
  2633. /*
  2634. * Only actually queue now that the atomic ops are done:
  2635. */
  2636. __queue_me(&q, hb);
  2637. if (trylock) {
  2638. ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
  2639. /* Fixup the trylock return value: */
  2640. ret = ret ? 0 : -EWOULDBLOCK;
  2641. goto no_block;
  2642. }
  2643. rt_mutex_init_waiter(&rt_waiter);
  2644. /*
  2645. * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
  2646. * hold it while doing rt_mutex_start_proxy(), because then it will
  2647. * include hb->lock in the blocking chain, even through we'll not in
  2648. * fact hold it while blocking. This will lead it to report -EDEADLK
  2649. * and BUG when futex_unlock_pi() interleaves with this.
  2650. *
  2651. * Therefore acquire wait_lock while holding hb->lock, but drop the
  2652. * latter before calling __rt_mutex_start_proxy_lock(). This
  2653. * interleaves with futex_unlock_pi() -- which does a similar lock
  2654. * handoff -- such that the latter can observe the futex_q::pi_state
  2655. * before __rt_mutex_start_proxy_lock() is done.
  2656. */
  2657. raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
  2658. spin_unlock(q.lock_ptr);
  2659. /*
  2660. * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
  2661. * such that futex_unlock_pi() is guaranteed to observe the waiter when
  2662. * it sees the futex_q::pi_state.
  2663. */
  2664. ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
  2665. raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
  2666. if (ret) {
  2667. if (ret == 1)
  2668. ret = 0;
  2669. goto cleanup;
  2670. }
  2671. if (unlikely(to))
  2672. hrtimer_start_expires(&to->timer, HRTIMER_MODE_ABS);
  2673. ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
  2674. cleanup:
  2675. spin_lock(q.lock_ptr);
  2676. /*
  2677. * If we failed to acquire the lock (deadlock/signal/timeout), we must
  2678. * first acquire the hb->lock before removing the lock from the
  2679. * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
  2680. * lists consistent.
  2681. *
  2682. * In particular; it is important that futex_unlock_pi() can not
  2683. * observe this inconsistency.
  2684. */
  2685. if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
  2686. ret = 0;
  2687. no_block:
  2688. /*
  2689. * Fixup the pi_state owner and possibly acquire the lock if we
  2690. * haven't already.
  2691. */
  2692. res = fixup_owner(uaddr, &q, !ret);
  2693. /*
  2694. * If fixup_owner() returned an error, proprogate that. If it acquired
  2695. * the lock, clear our -ETIMEDOUT or -EINTR.
  2696. */
  2697. if (res)
  2698. ret = (res < 0) ? res : 0;
  2699. /* Unqueue and drop the lock */
  2700. unqueue_me_pi(&q);
  2701. goto out_put_key;
  2702. out_unlock_put_key:
  2703. queue_unlock(hb);
  2704. out_put_key:
  2705. put_futex_key(&q.key);
  2706. out:
  2707. if (to) {
  2708. hrtimer_cancel(&to->timer);
  2709. destroy_hrtimer_on_stack(&to->timer);
  2710. }
  2711. return ret != -EINTR ? ret : -ERESTARTNOINTR;
  2712. uaddr_faulted:
  2713. queue_unlock(hb);
  2714. ret = fault_in_user_writeable(uaddr);
  2715. if (ret)
  2716. goto out_put_key;
  2717. if (!(flags & FLAGS_SHARED))
  2718. goto retry_private;
  2719. put_futex_key(&q.key);
  2720. goto retry;
  2721. }
  2722. /*
  2723. * Userspace attempted a TID -> 0 atomic transition, and failed.
  2724. * This is the in-kernel slowpath: we look up the PI state (if any),
  2725. * and do the rt-mutex unlock.
  2726. */
  2727. static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
  2728. {
  2729. u32 uninitialized_var(curval), uval, vpid = task_pid_vnr(current);
  2730. union futex_key key = FUTEX_KEY_INIT;
  2731. struct futex_hash_bucket *hb;
  2732. struct futex_q *top_waiter;
  2733. int ret;
  2734. if (!IS_ENABLED(CONFIG_FUTEX_PI))
  2735. return -ENOSYS;
  2736. retry:
  2737. if (get_user(uval, uaddr))
  2738. return -EFAULT;
  2739. /*
  2740. * We release only a lock we actually own:
  2741. */
  2742. if ((uval & FUTEX_TID_MASK) != vpid)
  2743. return -EPERM;
  2744. ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
  2745. if (ret)
  2746. return ret;
  2747. hb = hash_futex(&key);
  2748. spin_lock(&hb->lock);
  2749. /*
  2750. * Check waiters first. We do not trust user space values at
  2751. * all and we at least want to know if user space fiddled
  2752. * with the futex value instead of blindly unlocking.
  2753. */
  2754. top_waiter = futex_top_waiter(hb, &key);
  2755. if (top_waiter) {
  2756. struct futex_pi_state *pi_state = top_waiter->pi_state;
  2757. ret = -EINVAL;
  2758. if (!pi_state)
  2759. goto out_unlock;
  2760. /*
  2761. * If current does not own the pi_state then the futex is
  2762. * inconsistent and user space fiddled with the futex value.
  2763. */
  2764. if (pi_state->owner != current)
  2765. goto out_unlock;
  2766. get_pi_state(pi_state);
  2767. /*
  2768. * By taking wait_lock while still holding hb->lock, we ensure
  2769. * there is no point where we hold neither; and therefore
  2770. * wake_futex_pi() must observe a state consistent with what we
  2771. * observed.
  2772. *
  2773. * In particular; this forces __rt_mutex_start_proxy() to
  2774. * complete such that we're guaranteed to observe the
  2775. * rt_waiter. Also see the WARN in wake_futex_pi().
  2776. */
  2777. raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
  2778. spin_unlock(&hb->lock);
  2779. /* drops pi_state->pi_mutex.wait_lock */
  2780. ret = wake_futex_pi(uaddr, uval, pi_state);
  2781. put_pi_state(pi_state);
  2782. /*
  2783. * Success, we're done! No tricky corner cases.
  2784. */
  2785. if (!ret)
  2786. goto out_putkey;
  2787. /*
  2788. * The atomic access to the futex value generated a
  2789. * pagefault, so retry the user-access and the wakeup:
  2790. */
  2791. if (ret == -EFAULT)
  2792. goto pi_faulted;
  2793. /*
  2794. * A unconditional UNLOCK_PI op raced against a waiter
  2795. * setting the FUTEX_WAITERS bit. Try again.
  2796. */
  2797. if (ret == -EAGAIN)
  2798. goto pi_retry;
  2799. /*
  2800. * wake_futex_pi has detected invalid state. Tell user
  2801. * space.
  2802. */
  2803. goto out_putkey;
  2804. }
  2805. /*
  2806. * We have no kernel internal state, i.e. no waiters in the
  2807. * kernel. Waiters which are about to queue themselves are stuck
  2808. * on hb->lock. So we can safely ignore them. We do neither
  2809. * preserve the WAITERS bit not the OWNER_DIED one. We are the
  2810. * owner.
  2811. */
  2812. if ((ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, 0))) {
  2813. spin_unlock(&hb->lock);
  2814. switch (ret) {
  2815. case -EFAULT:
  2816. goto pi_faulted;
  2817. case -EAGAIN:
  2818. goto pi_retry;
  2819. default:
  2820. WARN_ON_ONCE(1);
  2821. goto out_putkey;
  2822. }
  2823. }
  2824. /*
  2825. * If uval has changed, let user space handle it.
  2826. */
  2827. ret = (curval == uval) ? 0 : -EAGAIN;
  2828. out_unlock:
  2829. spin_unlock(&hb->lock);
  2830. out_putkey:
  2831. put_futex_key(&key);
  2832. return ret;
  2833. pi_retry:
  2834. put_futex_key(&key);
  2835. cond_resched();
  2836. goto retry;
  2837. pi_faulted:
  2838. put_futex_key(&key);
  2839. ret = fault_in_user_writeable(uaddr);
  2840. if (!ret)
  2841. goto retry;
  2842. return ret;
  2843. }
  2844. /**
  2845. * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
  2846. * @hb: the hash_bucket futex_q was original enqueued on
  2847. * @q: the futex_q woken while waiting to be requeued
  2848. * @key2: the futex_key of the requeue target futex
  2849. * @timeout: the timeout associated with the wait (NULL if none)
  2850. *
  2851. * Detect if the task was woken on the initial futex as opposed to the requeue
  2852. * target futex. If so, determine if it was a timeout or a signal that caused
  2853. * the wakeup and return the appropriate error code to the caller. Must be
  2854. * called with the hb lock held.
  2855. *
  2856. * Return:
  2857. * - 0 = no early wakeup detected;
  2858. * - <0 = -ETIMEDOUT or -ERESTARTNOINTR
  2859. */
  2860. static inline
  2861. int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
  2862. struct futex_q *q, union futex_key *key2,
  2863. struct hrtimer_sleeper *timeout)
  2864. {
  2865. int ret = 0;
  2866. /*
  2867. * With the hb lock held, we avoid races while we process the wakeup.
  2868. * We only need to hold hb (and not hb2) to ensure atomicity as the
  2869. * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
  2870. * It can't be requeued from uaddr2 to something else since we don't
  2871. * support a PI aware source futex for requeue.
  2872. */
  2873. if (!match_futex(&q->key, key2)) {
  2874. WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
  2875. /*
  2876. * We were woken prior to requeue by a timeout or a signal.
  2877. * Unqueue the futex_q and determine which it was.
  2878. */
  2879. plist_del(&q->list, &hb->chain);
  2880. hb_waiters_dec(hb);
  2881. /* Handle spurious wakeups gracefully */
  2882. ret = -EWOULDBLOCK;
  2883. if (timeout && !timeout->task)
  2884. ret = -ETIMEDOUT;
  2885. else if (signal_pending(current))
  2886. ret = -ERESTARTNOINTR;
  2887. }
  2888. return ret;
  2889. }
  2890. /**
  2891. * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
  2892. * @uaddr: the futex we initially wait on (non-pi)
  2893. * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
  2894. * the same type, no requeueing from private to shared, etc.
  2895. * @val: the expected value of uaddr
  2896. * @abs_time: absolute timeout
  2897. * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
  2898. * @uaddr2: the pi futex we will take prior to returning to user-space
  2899. *
  2900. * The caller will wait on uaddr and will be requeued by futex_requeue() to
  2901. * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
  2902. * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
  2903. * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
  2904. * without one, the pi logic would not know which task to boost/deboost, if
  2905. * there was a need to.
  2906. *
  2907. * We call schedule in futex_wait_queue_me() when we enqueue and return there
  2908. * via the following--
  2909. * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
  2910. * 2) wakeup on uaddr2 after a requeue
  2911. * 3) signal
  2912. * 4) timeout
  2913. *
  2914. * If 3, cleanup and return -ERESTARTNOINTR.
  2915. *
  2916. * If 2, we may then block on trying to take the rt_mutex and return via:
  2917. * 5) successful lock
  2918. * 6) signal
  2919. * 7) timeout
  2920. * 8) other lock acquisition failure
  2921. *
  2922. * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
  2923. *
  2924. * If 4 or 7, we cleanup and return with -ETIMEDOUT.
  2925. *
  2926. * Return:
  2927. * - 0 - On success;
  2928. * - <0 - On error
  2929. */
  2930. static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
  2931. u32 val, ktime_t *abs_time, u32 bitset,
  2932. u32 __user *uaddr2)
  2933. {
  2934. struct hrtimer_sleeper timeout, *to = NULL;
  2935. struct rt_mutex_waiter rt_waiter;
  2936. struct futex_hash_bucket *hb;
  2937. union futex_key key2 = FUTEX_KEY_INIT;
  2938. struct futex_q q = futex_q_init;
  2939. int res, ret;
  2940. if (!IS_ENABLED(CONFIG_FUTEX_PI))
  2941. return -ENOSYS;
  2942. if (uaddr == uaddr2)
  2943. return -EINVAL;
  2944. if (!bitset)
  2945. return -EINVAL;
  2946. if (abs_time) {
  2947. to = &timeout;
  2948. hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
  2949. CLOCK_REALTIME : CLOCK_MONOTONIC,
  2950. HRTIMER_MODE_ABS);
  2951. hrtimer_init_sleeper(to, current);
  2952. hrtimer_set_expires_range_ns(&to->timer, *abs_time,
  2953. current->timer_slack_ns);
  2954. }
  2955. /*
  2956. * The waiter is allocated on our stack, manipulated by the requeue
  2957. * code while we sleep on uaddr.
  2958. */
  2959. rt_mutex_init_waiter(&rt_waiter);
  2960. ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
  2961. if (unlikely(ret != 0))
  2962. goto out;
  2963. q.bitset = bitset;
  2964. q.rt_waiter = &rt_waiter;
  2965. q.requeue_pi_key = &key2;
  2966. /*
  2967. * Prepare to wait on uaddr. On success, increments q.key (key1) ref
  2968. * count.
  2969. */
  2970. ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
  2971. if (ret)
  2972. goto out_key2;
  2973. /*
  2974. * The check above which compares uaddrs is not sufficient for
  2975. * shared futexes. We need to compare the keys:
  2976. */
  2977. if (match_futex(&q.key, &key2)) {
  2978. queue_unlock(hb);
  2979. ret = -EINVAL;
  2980. goto out_put_keys;
  2981. }
  2982. /* Queue the futex_q, drop the hb lock, wait for wakeup. */
  2983. futex_wait_queue_me(hb, &q, to);
  2984. spin_lock(&hb->lock);
  2985. ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
  2986. spin_unlock(&hb->lock);
  2987. if (ret)
  2988. goto out_put_keys;
  2989. /*
  2990. * In order for us to be here, we know our q.key == key2, and since
  2991. * we took the hb->lock above, we also know that futex_requeue() has
  2992. * completed and we no longer have to concern ourselves with a wakeup
  2993. * race with the atomic proxy lock acquisition by the requeue code. The
  2994. * futex_requeue dropped our key1 reference and incremented our key2
  2995. * reference count.
  2996. */
  2997. /* Check if the requeue code acquired the second futex for us. */
  2998. if (!q.rt_waiter) {
  2999. /*
  3000. * Got the lock. We might not be the anticipated owner if we
  3001. * did a lock-steal - fix up the PI-state in that case.
  3002. */
  3003. if (q.pi_state && (q.pi_state->owner != current)) {
  3004. spin_lock(q.lock_ptr);
  3005. ret = fixup_pi_state_owner(uaddr2, &q, current);
  3006. /*
  3007. * Drop the reference to the pi state which
  3008. * the requeue_pi() code acquired for us.
  3009. */
  3010. put_pi_state(q.pi_state);
  3011. spin_unlock(q.lock_ptr);
  3012. /*
  3013. * Adjust the return value. It's either -EFAULT or
  3014. * success (1) but the caller expects 0 for success.
  3015. */
  3016. ret = ret < 0 ? ret : 0;
  3017. }
  3018. } else {
  3019. struct rt_mutex *pi_mutex;
  3020. /*
  3021. * We have been woken up by futex_unlock_pi(), a timeout, or a
  3022. * signal. futex_unlock_pi() will not destroy the lock_ptr nor
  3023. * the pi_state.
  3024. */
  3025. WARN_ON(!q.pi_state);
  3026. pi_mutex = &q.pi_state->pi_mutex;
  3027. ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
  3028. spin_lock(q.lock_ptr);
  3029. if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
  3030. ret = 0;
  3031. debug_rt_mutex_free_waiter(&rt_waiter);
  3032. /*
  3033. * Fixup the pi_state owner and possibly acquire the lock if we
  3034. * haven't already.
  3035. */
  3036. res = fixup_owner(uaddr2, &q, !ret);
  3037. /*
  3038. * If fixup_owner() returned an error, proprogate that. If it
  3039. * acquired the lock, clear -ETIMEDOUT or -EINTR.
  3040. */
  3041. if (res)
  3042. ret = (res < 0) ? res : 0;
  3043. /* Unqueue and drop the lock. */
  3044. unqueue_me_pi(&q);
  3045. }
  3046. if (ret == -EINTR) {
  3047. /*
  3048. * We've already been requeued, but cannot restart by calling
  3049. * futex_lock_pi() directly. We could restart this syscall, but
  3050. * it would detect that the user space "val" changed and return
  3051. * -EWOULDBLOCK. Save the overhead of the restart and return
  3052. * -EWOULDBLOCK directly.
  3053. */
  3054. ret = -EWOULDBLOCK;
  3055. }
  3056. out_put_keys:
  3057. put_futex_key(&q.key);
  3058. out_key2:
  3059. put_futex_key(&key2);
  3060. out:
  3061. if (to) {
  3062. hrtimer_cancel(&to->timer);
  3063. destroy_hrtimer_on_stack(&to->timer);
  3064. }
  3065. return ret;
  3066. }
  3067. /*
  3068. * Support for robust futexes: the kernel cleans up held futexes at
  3069. * thread exit time.
  3070. *
  3071. * Implementation: user-space maintains a per-thread list of locks it
  3072. * is holding. Upon do_exit(), the kernel carefully walks this list,
  3073. * and marks all locks that are owned by this thread with the
  3074. * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
  3075. * always manipulated with the lock held, so the list is private and
  3076. * per-thread. Userspace also maintains a per-thread 'list_op_pending'
  3077. * field, to allow the kernel to clean up if the thread dies after
  3078. * acquiring the lock, but just before it could have added itself to
  3079. * the list. There can only be one such pending lock.
  3080. */
  3081. /**
  3082. * sys_set_robust_list() - Set the robust-futex list head of a task
  3083. * @head: pointer to the list-head
  3084. * @len: length of the list-head, as userspace expects
  3085. */
  3086. SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
  3087. size_t, len)
  3088. {
  3089. if (!futex_cmpxchg_enabled)
  3090. return -ENOSYS;
  3091. /*
  3092. * The kernel knows only one size for now:
  3093. */
  3094. if (unlikely(len != sizeof(*head)))
  3095. return -EINVAL;
  3096. current->robust_list = head;
  3097. return 0;
  3098. }
  3099. /**
  3100. * sys_get_robust_list() - Get the robust-futex list head of a task
  3101. * @pid: pid of the process [zero for current task]
  3102. * @head_ptr: pointer to a list-head pointer, the kernel fills it in
  3103. * @len_ptr: pointer to a length field, the kernel fills in the header size
  3104. */
  3105. SYSCALL_DEFINE3(get_robust_list, int, pid,
  3106. struct robust_list_head __user * __user *, head_ptr,
  3107. size_t __user *, len_ptr)
  3108. {
  3109. struct robust_list_head __user *head;
  3110. unsigned long ret;
  3111. struct task_struct *p;
  3112. if (!futex_cmpxchg_enabled)
  3113. return -ENOSYS;
  3114. rcu_read_lock();
  3115. ret = -ESRCH;
  3116. if (!pid)
  3117. p = current;
  3118. else {
  3119. p = find_task_by_vpid(pid);
  3120. if (!p)
  3121. goto err_unlock;
  3122. }
  3123. ret = -EPERM;
  3124. if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
  3125. goto err_unlock;
  3126. head = p->robust_list;
  3127. rcu_read_unlock();
  3128. if (put_user(sizeof(*head), len_ptr))
  3129. return -EFAULT;
  3130. return put_user(head, head_ptr);
  3131. err_unlock:
  3132. rcu_read_unlock();
  3133. return ret;
  3134. }
  3135. /* Constants for the pending_op argument of handle_futex_death */
  3136. #define HANDLE_DEATH_PENDING true
  3137. #define HANDLE_DEATH_LIST false
  3138. /*
  3139. * Process a futex-list entry, check whether it's owned by the
  3140. * dying task, and do notification if so:
  3141. */
  3142. static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
  3143. bool pi, bool pending_op)
  3144. {
  3145. u32 uval, uninitialized_var(nval), mval;
  3146. int err;
  3147. /* Futex address must be 32bit aligned */
  3148. if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
  3149. return -1;
  3150. retry:
  3151. if (get_user(uval, uaddr))
  3152. return -1;
  3153. /*
  3154. * Special case for regular (non PI) futexes. The unlock path in
  3155. * user space has two race scenarios:
  3156. *
  3157. * 1. The unlock path releases the user space futex value and
  3158. * before it can execute the futex() syscall to wake up
  3159. * waiters it is killed.
  3160. *
  3161. * 2. A woken up waiter is killed before it can acquire the
  3162. * futex in user space.
  3163. *
  3164. * In both cases the TID validation below prevents a wakeup of
  3165. * potential waiters which can cause these waiters to block
  3166. * forever.
  3167. *
  3168. * In both cases the following conditions are met:
  3169. *
  3170. * 1) task->robust_list->list_op_pending != NULL
  3171. * @pending_op == true
  3172. * 2) User space futex value == 0
  3173. * 3) Regular futex: @pi == false
  3174. *
  3175. * If these conditions are met, it is safe to attempt waking up a
  3176. * potential waiter without touching the user space futex value and
  3177. * trying to set the OWNER_DIED bit. The user space futex value is
  3178. * uncontended and the rest of the user space mutex state is
  3179. * consistent, so a woken waiter will just take over the
  3180. * uncontended futex. Setting the OWNER_DIED bit would create
  3181. * inconsistent state and malfunction of the user space owner died
  3182. * handling.
  3183. */
  3184. if (pending_op && !pi && !uval) {
  3185. futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
  3186. return 0;
  3187. }
  3188. if ((uval & FUTEX_TID_MASK) != task_pid_vnr(curr))
  3189. return 0;
  3190. /*
  3191. * Ok, this dying thread is truly holding a futex
  3192. * of interest. Set the OWNER_DIED bit atomically
  3193. * via cmpxchg, and if the value had FUTEX_WAITERS
  3194. * set, wake up a waiter (if any). (We have to do a
  3195. * futex_wake() even if OWNER_DIED is already set -
  3196. * to handle the rare but possible case of recursive
  3197. * thread-death.) The rest of the cleanup is done in
  3198. * userspace.
  3199. */
  3200. mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
  3201. /*
  3202. * We are not holding a lock here, but we want to have
  3203. * the pagefault_disable/enable() protection because
  3204. * we want to handle the fault gracefully. If the
  3205. * access fails we try to fault in the futex with R/W
  3206. * verification via get_user_pages. get_user() above
  3207. * does not guarantee R/W access. If that fails we
  3208. * give up and leave the futex locked.
  3209. */
  3210. if ((err = cmpxchg_futex_value_locked(&nval, uaddr, uval, mval))) {
  3211. switch (err) {
  3212. case -EFAULT:
  3213. if (fault_in_user_writeable(uaddr))
  3214. return -1;
  3215. goto retry;
  3216. case -EAGAIN:
  3217. cond_resched();
  3218. goto retry;
  3219. default:
  3220. WARN_ON_ONCE(1);
  3221. return err;
  3222. }
  3223. }
  3224. if (nval != uval)
  3225. goto retry;
  3226. /*
  3227. * Wake robust non-PI futexes here. The wakeup of
  3228. * PI futexes happens in exit_pi_state():
  3229. */
  3230. if (!pi && (uval & FUTEX_WAITERS))
  3231. futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
  3232. return 0;
  3233. }
  3234. /*
  3235. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  3236. */
  3237. static inline int fetch_robust_entry(struct robust_list __user **entry,
  3238. struct robust_list __user * __user *head,
  3239. unsigned int *pi)
  3240. {
  3241. unsigned long uentry;
  3242. if (get_user(uentry, (unsigned long __user *)head))
  3243. return -EFAULT;
  3244. *entry = (void __user *)(uentry & ~1UL);
  3245. *pi = uentry & 1;
  3246. return 0;
  3247. }
  3248. /*
  3249. * Walk curr->robust_list (very carefully, it's a userspace list!)
  3250. * and mark any locks found there dead, and notify any waiters.
  3251. *
  3252. * We silently return on any sign of list-walking problem.
  3253. */
  3254. static void exit_robust_list(struct task_struct *curr)
  3255. {
  3256. struct robust_list_head __user *head = curr->robust_list;
  3257. struct robust_list __user *entry, *next_entry, *pending;
  3258. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  3259. unsigned int uninitialized_var(next_pi);
  3260. unsigned long futex_offset;
  3261. int rc;
  3262. if (!futex_cmpxchg_enabled)
  3263. return;
  3264. /*
  3265. * Fetch the list head (which was registered earlier, via
  3266. * sys_set_robust_list()):
  3267. */
  3268. if (fetch_robust_entry(&entry, &head->list.next, &pi))
  3269. return;
  3270. /*
  3271. * Fetch the relative futex offset:
  3272. */
  3273. if (get_user(futex_offset, &head->futex_offset))
  3274. return;
  3275. /*
  3276. * Fetch any possibly pending lock-add first, and handle it
  3277. * if it exists:
  3278. */
  3279. if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
  3280. return;
  3281. next_entry = NULL; /* avoid warning with gcc */
  3282. while (entry != &head->list) {
  3283. /*
  3284. * Fetch the next entry in the list before calling
  3285. * handle_futex_death:
  3286. */
  3287. rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
  3288. /*
  3289. * A pending lock might already be on the list, so
  3290. * don't process it twice:
  3291. */
  3292. if (entry != pending) {
  3293. if (handle_futex_death((void __user *)entry + futex_offset,
  3294. curr, pi, HANDLE_DEATH_LIST))
  3295. return;
  3296. }
  3297. if (rc)
  3298. return;
  3299. entry = next_entry;
  3300. pi = next_pi;
  3301. /*
  3302. * Avoid excessively long or circular lists:
  3303. */
  3304. if (!--limit)
  3305. break;
  3306. cond_resched();
  3307. }
  3308. if (pending) {
  3309. handle_futex_death((void __user *)pending + futex_offset,
  3310. curr, pip, HANDLE_DEATH_PENDING);
  3311. }
  3312. }
  3313. static void futex_cleanup(struct task_struct *tsk)
  3314. {
  3315. if (unlikely(tsk->robust_list)) {
  3316. exit_robust_list(tsk);
  3317. tsk->robust_list = NULL;
  3318. }
  3319. #ifdef CONFIG_COMPAT
  3320. if (unlikely(tsk->compat_robust_list)) {
  3321. compat_exit_robust_list(tsk);
  3322. tsk->compat_robust_list = NULL;
  3323. }
  3324. #endif
  3325. if (unlikely(!list_empty(&tsk->pi_state_list)))
  3326. exit_pi_state_list(tsk);
  3327. }
  3328. /**
  3329. * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
  3330. * @tsk: task to set the state on
  3331. *
  3332. * Set the futex exit state of the task lockless. The futex waiter code
  3333. * observes that state when a task is exiting and loops until the task has
  3334. * actually finished the futex cleanup. The worst case for this is that the
  3335. * waiter runs through the wait loop until the state becomes visible.
  3336. *
  3337. * This is called from the recursive fault handling path in do_exit().
  3338. *
  3339. * This is best effort. Either the futex exit code has run already or
  3340. * not. If the OWNER_DIED bit has been set on the futex then the waiter can
  3341. * take it over. If not, the problem is pushed back to user space. If the
  3342. * futex exit code did not run yet, then an already queued waiter might
  3343. * block forever, but there is nothing which can be done about that.
  3344. */
  3345. void futex_exit_recursive(struct task_struct *tsk)
  3346. {
  3347. /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
  3348. if (tsk->futex_state == FUTEX_STATE_EXITING)
  3349. mutex_unlock(&tsk->futex_exit_mutex);
  3350. tsk->futex_state = FUTEX_STATE_DEAD;
  3351. }
  3352. static void futex_cleanup_begin(struct task_struct *tsk)
  3353. {
  3354. /*
  3355. * Prevent various race issues against a concurrent incoming waiter
  3356. * including live locks by forcing the waiter to block on
  3357. * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
  3358. * attach_to_pi_owner().
  3359. */
  3360. mutex_lock(&tsk->futex_exit_mutex);
  3361. /*
  3362. * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
  3363. *
  3364. * This ensures that all subsequent checks of tsk->futex_state in
  3365. * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
  3366. * tsk->pi_lock held.
  3367. *
  3368. * It guarantees also that a pi_state which was queued right before
  3369. * the state change under tsk->pi_lock by a concurrent waiter must
  3370. * be observed in exit_pi_state_list().
  3371. */
  3372. raw_spin_lock_irq(&tsk->pi_lock);
  3373. tsk->futex_state = FUTEX_STATE_EXITING;
  3374. raw_spin_unlock_irq(&tsk->pi_lock);
  3375. }
  3376. static void futex_cleanup_end(struct task_struct *tsk, int state)
  3377. {
  3378. /*
  3379. * Lockless store. The only side effect is that an observer might
  3380. * take another loop until it becomes visible.
  3381. */
  3382. tsk->futex_state = state;
  3383. /*
  3384. * Drop the exit protection. This unblocks waiters which observed
  3385. * FUTEX_STATE_EXITING to reevaluate the state.
  3386. */
  3387. mutex_unlock(&tsk->futex_exit_mutex);
  3388. }
  3389. void futex_exec_release(struct task_struct *tsk)
  3390. {
  3391. /*
  3392. * The state handling is done for consistency, but in the case of
  3393. * exec() there is no way to prevent futher damage as the PID stays
  3394. * the same. But for the unlikely and arguably buggy case that a
  3395. * futex is held on exec(), this provides at least as much state
  3396. * consistency protection which is possible.
  3397. */
  3398. futex_cleanup_begin(tsk);
  3399. futex_cleanup(tsk);
  3400. /*
  3401. * Reset the state to FUTEX_STATE_OK. The task is alive and about
  3402. * exec a new binary.
  3403. */
  3404. futex_cleanup_end(tsk, FUTEX_STATE_OK);
  3405. }
  3406. void futex_exit_release(struct task_struct *tsk)
  3407. {
  3408. futex_cleanup_begin(tsk);
  3409. futex_cleanup(tsk);
  3410. futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
  3411. }
  3412. long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
  3413. u32 __user *uaddr2, u32 val2, u32 val3)
  3414. {
  3415. int cmd = op & FUTEX_CMD_MASK;
  3416. unsigned int flags = 0;
  3417. if (!(op & FUTEX_PRIVATE_FLAG))
  3418. flags |= FLAGS_SHARED;
  3419. if (op & FUTEX_CLOCK_REALTIME) {
  3420. flags |= FLAGS_CLOCKRT;
  3421. if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
  3422. return -ENOSYS;
  3423. }
  3424. switch (cmd) {
  3425. case FUTEX_LOCK_PI:
  3426. case FUTEX_UNLOCK_PI:
  3427. case FUTEX_TRYLOCK_PI:
  3428. case FUTEX_WAIT_REQUEUE_PI:
  3429. case FUTEX_CMP_REQUEUE_PI:
  3430. if (!futex_cmpxchg_enabled)
  3431. return -ENOSYS;
  3432. }
  3433. switch (cmd) {
  3434. case FUTEX_WAIT:
  3435. val3 = FUTEX_BITSET_MATCH_ANY;
  3436. /* fall through */
  3437. case FUTEX_WAIT_BITSET:
  3438. return futex_wait(uaddr, flags, val, timeout, val3);
  3439. case FUTEX_WAKE:
  3440. val3 = FUTEX_BITSET_MATCH_ANY;
  3441. /* fall through */
  3442. case FUTEX_WAKE_BITSET:
  3443. return futex_wake(uaddr, flags, val, val3);
  3444. case FUTEX_REQUEUE:
  3445. return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
  3446. case FUTEX_CMP_REQUEUE:
  3447. return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
  3448. case FUTEX_WAKE_OP:
  3449. return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
  3450. case FUTEX_LOCK_PI:
  3451. return futex_lock_pi(uaddr, flags, timeout, 0);
  3452. case FUTEX_UNLOCK_PI:
  3453. return futex_unlock_pi(uaddr, flags);
  3454. case FUTEX_TRYLOCK_PI:
  3455. return futex_lock_pi(uaddr, flags, NULL, 1);
  3456. case FUTEX_WAIT_REQUEUE_PI:
  3457. val3 = FUTEX_BITSET_MATCH_ANY;
  3458. return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
  3459. uaddr2);
  3460. case FUTEX_CMP_REQUEUE_PI:
  3461. return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
  3462. }
  3463. return -ENOSYS;
  3464. }
  3465. SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
  3466. struct timespec __user *, utime, u32 __user *, uaddr2,
  3467. u32, val3)
  3468. {
  3469. struct timespec ts;
  3470. ktime_t t, *tp = NULL;
  3471. u32 val2 = 0;
  3472. int cmd = op & FUTEX_CMD_MASK;
  3473. if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
  3474. cmd == FUTEX_WAIT_BITSET ||
  3475. cmd == FUTEX_WAIT_REQUEUE_PI)) {
  3476. if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
  3477. return -EFAULT;
  3478. if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
  3479. return -EFAULT;
  3480. if (!timespec_valid(&ts))
  3481. return -EINVAL;
  3482. t = timespec_to_ktime(ts);
  3483. if (cmd == FUTEX_WAIT)
  3484. t = ktime_add_safe(ktime_get(), t);
  3485. tp = &t;
  3486. }
  3487. /*
  3488. * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
  3489. * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
  3490. */
  3491. if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
  3492. cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
  3493. val2 = (u32) (unsigned long) utime;
  3494. return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
  3495. }
  3496. #ifdef CONFIG_COMPAT
  3497. /*
  3498. * Fetch a robust-list pointer. Bit 0 signals PI futexes:
  3499. */
  3500. static inline int
  3501. compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
  3502. compat_uptr_t __user *head, unsigned int *pi)
  3503. {
  3504. if (get_user(*uentry, head))
  3505. return -EFAULT;
  3506. *entry = compat_ptr((*uentry) & ~1);
  3507. *pi = (unsigned int)(*uentry) & 1;
  3508. return 0;
  3509. }
  3510. static void __user *futex_uaddr(struct robust_list __user *entry,
  3511. compat_long_t futex_offset)
  3512. {
  3513. compat_uptr_t base = ptr_to_compat(entry);
  3514. void __user *uaddr = compat_ptr(base + futex_offset);
  3515. return uaddr;
  3516. }
  3517. /*
  3518. * Walk curr->robust_list (very carefully, it's a userspace list!)
  3519. * and mark any locks found there dead, and notify any waiters.
  3520. *
  3521. * We silently return on any sign of list-walking problem.
  3522. */
  3523. static void compat_exit_robust_list(struct task_struct *curr)
  3524. {
  3525. struct compat_robust_list_head __user *head = curr->compat_robust_list;
  3526. struct robust_list __user *entry, *next_entry, *pending;
  3527. unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
  3528. unsigned int uninitialized_var(next_pi);
  3529. compat_uptr_t uentry, next_uentry, upending;
  3530. compat_long_t futex_offset;
  3531. int rc;
  3532. if (!futex_cmpxchg_enabled)
  3533. return;
  3534. /*
  3535. * Fetch the list head (which was registered earlier, via
  3536. * sys_set_robust_list()):
  3537. */
  3538. if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
  3539. return;
  3540. /*
  3541. * Fetch the relative futex offset:
  3542. */
  3543. if (get_user(futex_offset, &head->futex_offset))
  3544. return;
  3545. /*
  3546. * Fetch any possibly pending lock-add first, and handle it
  3547. * if it exists:
  3548. */
  3549. if (compat_fetch_robust_entry(&upending, &pending,
  3550. &head->list_op_pending, &pip))
  3551. return;
  3552. next_entry = NULL; /* avoid warning with gcc */
  3553. while (entry != (struct robust_list __user *) &head->list) {
  3554. /*
  3555. * Fetch the next entry in the list before calling
  3556. * handle_futex_death:
  3557. */
  3558. rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
  3559. (compat_uptr_t __user *)&entry->next, &next_pi);
  3560. /*
  3561. * A pending lock might already be on the list, so
  3562. * dont process it twice:
  3563. */
  3564. if (entry != pending) {
  3565. void __user *uaddr = futex_uaddr(entry, futex_offset);
  3566. if (handle_futex_death(uaddr, curr, pi,
  3567. HANDLE_DEATH_LIST))
  3568. return;
  3569. }
  3570. if (rc)
  3571. return;
  3572. uentry = next_uentry;
  3573. entry = next_entry;
  3574. pi = next_pi;
  3575. /*
  3576. * Avoid excessively long or circular lists:
  3577. */
  3578. if (!--limit)
  3579. break;
  3580. cond_resched();
  3581. }
  3582. if (pending) {
  3583. void __user *uaddr = futex_uaddr(pending, futex_offset);
  3584. handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
  3585. }
  3586. }
  3587. COMPAT_SYSCALL_DEFINE2(set_robust_list,
  3588. struct compat_robust_list_head __user *, head,
  3589. compat_size_t, len)
  3590. {
  3591. if (!futex_cmpxchg_enabled)
  3592. return -ENOSYS;
  3593. if (unlikely(len != sizeof(*head)))
  3594. return -EINVAL;
  3595. current->compat_robust_list = head;
  3596. return 0;
  3597. }
  3598. COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid,
  3599. compat_uptr_t __user *, head_ptr,
  3600. compat_size_t __user *, len_ptr)
  3601. {
  3602. struct compat_robust_list_head __user *head;
  3603. unsigned long ret;
  3604. struct task_struct *p;
  3605. if (!futex_cmpxchg_enabled)
  3606. return -ENOSYS;
  3607. rcu_read_lock();
  3608. ret = -ESRCH;
  3609. if (!pid)
  3610. p = current;
  3611. else {
  3612. p = find_task_by_vpid(pid);
  3613. if (!p)
  3614. goto err_unlock;
  3615. }
  3616. ret = -EPERM;
  3617. if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
  3618. goto err_unlock;
  3619. head = p->compat_robust_list;
  3620. rcu_read_unlock();
  3621. if (put_user(sizeof(*head), len_ptr))
  3622. return -EFAULT;
  3623. return put_user(ptr_to_compat(head), head_ptr);
  3624. err_unlock:
  3625. rcu_read_unlock();
  3626. return ret;
  3627. }
  3628. COMPAT_SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
  3629. struct old_timespec32 __user *, utime, u32 __user *, uaddr2,
  3630. u32, val3)
  3631. {
  3632. struct timespec ts;
  3633. ktime_t t, *tp = NULL;
  3634. int val2 = 0;
  3635. int cmd = op & FUTEX_CMD_MASK;
  3636. if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
  3637. cmd == FUTEX_WAIT_BITSET ||
  3638. cmd == FUTEX_WAIT_REQUEUE_PI)) {
  3639. if (compat_get_timespec(&ts, utime))
  3640. return -EFAULT;
  3641. if (!timespec_valid(&ts))
  3642. return -EINVAL;
  3643. t = timespec_to_ktime(ts);
  3644. if (cmd == FUTEX_WAIT)
  3645. t = ktime_add_safe(ktime_get(), t);
  3646. tp = &t;
  3647. }
  3648. if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
  3649. cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
  3650. val2 = (int) (unsigned long) utime;
  3651. return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
  3652. }
  3653. #endif /* CONFIG_COMPAT */
  3654. static void __init futex_detect_cmpxchg(void)
  3655. {
  3656. #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
  3657. u32 curval;
  3658. /*
  3659. * This will fail and we want it. Some arch implementations do
  3660. * runtime detection of the futex_atomic_cmpxchg_inatomic()
  3661. * functionality. We want to know that before we call in any
  3662. * of the complex code paths. Also we want to prevent
  3663. * registration of robust lists in that case. NULL is
  3664. * guaranteed to fault and we get -EFAULT on functional
  3665. * implementation, the non-functional ones will return
  3666. * -ENOSYS.
  3667. */
  3668. if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
  3669. futex_cmpxchg_enabled = 1;
  3670. #endif
  3671. }
  3672. static int __init futex_init(void)
  3673. {
  3674. unsigned int futex_shift;
  3675. unsigned long i;
  3676. #if CONFIG_BASE_SMALL
  3677. futex_hashsize = 16;
  3678. #else
  3679. futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
  3680. #endif
  3681. futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
  3682. futex_hashsize, 0,
  3683. futex_hashsize < 256 ? HASH_SMALL : 0,
  3684. &futex_shift, NULL,
  3685. futex_hashsize, futex_hashsize);
  3686. futex_hashsize = 1UL << futex_shift;
  3687. futex_detect_cmpxchg();
  3688. for (i = 0; i < futex_hashsize; i++) {
  3689. atomic_set(&futex_queues[i].waiters, 0);
  3690. plist_head_init(&futex_queues[i].chain);
  3691. spin_lock_init(&futex_queues[i].lock);
  3692. }
  3693. return 0;
  3694. }
  3695. core_initcall(futex_init);