futex.c 96 KB

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