futex.c 77 KB

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