futex.c 86 KB

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