futex.c 114 KB

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