futex.c 85 KB

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