futex.c 77 KB

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