futex.c 82 KB

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