futex.c 88 KB

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