futex.c 78 KB

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