futex.c 78 KB

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