futex.c 85 KB

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