futex.c 94 KB

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