futex.c 76 KB

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