userfaultfd.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. /*
  2. * fs/userfaultfd.c
  3. *
  4. * Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
  5. * Copyright (C) 2008-2009 Red Hat, Inc.
  6. * Copyright (C) 2015 Red Hat, Inc.
  7. *
  8. * This work is licensed under the terms of the GNU GPL, version 2. See
  9. * the COPYING file in the top-level directory.
  10. *
  11. * Some part derived from fs/eventfd.c (anon inode setup) and
  12. * mm/ksm.c (mm hashing).
  13. */
  14. #include <linux/list.h>
  15. #include <linux/hashtable.h>
  16. #include <linux/sched.h>
  17. #include <linux/mm.h>
  18. #include <linux/poll.h>
  19. #include <linux/slab.h>
  20. #include <linux/seq_file.h>
  21. #include <linux/file.h>
  22. #include <linux/bug.h>
  23. #include <linux/anon_inodes.h>
  24. #include <linux/syscalls.h>
  25. #include <linux/userfaultfd_k.h>
  26. #include <linux/mempolicy.h>
  27. #include <linux/ioctl.h>
  28. #include <linux/security.h>
  29. #include <linux/hugetlb.h>
  30. static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
  31. enum userfaultfd_state {
  32. UFFD_STATE_WAIT_API,
  33. UFFD_STATE_RUNNING,
  34. };
  35. /*
  36. * Start with fault_pending_wqh and fault_wqh so they're more likely
  37. * to be in the same cacheline.
  38. */
  39. struct userfaultfd_ctx {
  40. /* waitqueue head for the pending (i.e. not read) userfaults */
  41. wait_queue_head_t fault_pending_wqh;
  42. /* waitqueue head for the userfaults */
  43. wait_queue_head_t fault_wqh;
  44. /* waitqueue head for the pseudo fd to wakeup poll/read */
  45. wait_queue_head_t fd_wqh;
  46. /* waitqueue head for events */
  47. wait_queue_head_t event_wqh;
  48. /* a refile sequence protected by fault_pending_wqh lock */
  49. struct seqcount refile_seq;
  50. /* pseudo fd refcounting */
  51. atomic_t refcount;
  52. /* userfaultfd syscall flags */
  53. unsigned int flags;
  54. /* features requested from the userspace */
  55. unsigned int features;
  56. /* state machine */
  57. enum userfaultfd_state state;
  58. /* released */
  59. bool released;
  60. /* mm with one ore more vmas attached to this userfaultfd_ctx */
  61. struct mm_struct *mm;
  62. };
  63. struct userfaultfd_fork_ctx {
  64. struct userfaultfd_ctx *orig;
  65. struct userfaultfd_ctx *new;
  66. struct list_head list;
  67. };
  68. struct userfaultfd_wait_queue {
  69. struct uffd_msg msg;
  70. wait_queue_t wq;
  71. struct userfaultfd_ctx *ctx;
  72. bool waken;
  73. };
  74. struct userfaultfd_wake_range {
  75. unsigned long start;
  76. unsigned long len;
  77. };
  78. static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
  79. int wake_flags, void *key)
  80. {
  81. struct userfaultfd_wake_range *range = key;
  82. int ret;
  83. struct userfaultfd_wait_queue *uwq;
  84. unsigned long start, len;
  85. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  86. ret = 0;
  87. /* len == 0 means wake all */
  88. start = range->start;
  89. len = range->len;
  90. if (len && (start > uwq->msg.arg.pagefault.address ||
  91. start + len <= uwq->msg.arg.pagefault.address))
  92. goto out;
  93. WRITE_ONCE(uwq->waken, true);
  94. /*
  95. * The implicit smp_mb__before_spinlock in try_to_wake_up()
  96. * renders uwq->waken visible to other CPUs before the task is
  97. * waken.
  98. */
  99. ret = wake_up_state(wq->private, mode);
  100. if (ret)
  101. /*
  102. * Wake only once, autoremove behavior.
  103. *
  104. * After the effect of list_del_init is visible to the
  105. * other CPUs, the waitqueue may disappear from under
  106. * us, see the !list_empty_careful() in
  107. * handle_userfault(). try_to_wake_up() has an
  108. * implicit smp_mb__before_spinlock, and the
  109. * wq->private is read before calling the extern
  110. * function "wake_up_state" (which in turns calls
  111. * try_to_wake_up). While the spin_lock;spin_unlock;
  112. * wouldn't be enough, the smp_mb__before_spinlock is
  113. * enough to avoid an explicit smp_mb() here.
  114. */
  115. list_del_init(&wq->task_list);
  116. out:
  117. return ret;
  118. }
  119. /**
  120. * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
  121. * context.
  122. * @ctx: [in] Pointer to the userfaultfd context.
  123. *
  124. * Returns: In case of success, returns not zero.
  125. */
  126. static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
  127. {
  128. if (!atomic_inc_not_zero(&ctx->refcount))
  129. BUG();
  130. }
  131. /**
  132. * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
  133. * context.
  134. * @ctx: [in] Pointer to userfaultfd context.
  135. *
  136. * The userfaultfd context reference must have been previously acquired either
  137. * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
  138. */
  139. static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
  140. {
  141. if (atomic_dec_and_test(&ctx->refcount)) {
  142. VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
  143. VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
  144. VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
  145. VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
  146. VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
  147. VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
  148. VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
  149. VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
  150. mmdrop(ctx->mm);
  151. kmem_cache_free(userfaultfd_ctx_cachep, ctx);
  152. }
  153. }
  154. static inline void msg_init(struct uffd_msg *msg)
  155. {
  156. BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
  157. /*
  158. * Must use memset to zero out the paddings or kernel data is
  159. * leaked to userland.
  160. */
  161. memset(msg, 0, sizeof(struct uffd_msg));
  162. }
  163. static inline struct uffd_msg userfault_msg(unsigned long address,
  164. unsigned int flags,
  165. unsigned long reason)
  166. {
  167. struct uffd_msg msg;
  168. msg_init(&msg);
  169. msg.event = UFFD_EVENT_PAGEFAULT;
  170. msg.arg.pagefault.address = address;
  171. if (flags & FAULT_FLAG_WRITE)
  172. /*
  173. * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
  174. * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
  175. * was not set in a UFFD_EVENT_PAGEFAULT, it means it
  176. * was a read fault, otherwise if set it means it's
  177. * a write fault.
  178. */
  179. msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
  180. if (reason & VM_UFFD_WP)
  181. /*
  182. * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
  183. * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
  184. * not set in a UFFD_EVENT_PAGEFAULT, it means it was
  185. * a missing fault, otherwise if set it means it's a
  186. * write protect fault.
  187. */
  188. msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
  189. return msg;
  190. }
  191. #ifdef CONFIG_HUGETLB_PAGE
  192. /*
  193. * Same functionality as userfaultfd_must_wait below with modifications for
  194. * hugepmd ranges.
  195. */
  196. static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
  197. unsigned long address,
  198. unsigned long flags,
  199. unsigned long reason)
  200. {
  201. struct mm_struct *mm = ctx->mm;
  202. pte_t *pte;
  203. bool ret = true;
  204. VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
  205. pte = huge_pte_offset(mm, address);
  206. if (!pte)
  207. goto out;
  208. ret = false;
  209. /*
  210. * Lockless access: we're in a wait_event so it's ok if it
  211. * changes under us.
  212. */
  213. if (huge_pte_none(*pte))
  214. ret = true;
  215. if (!huge_pte_write(*pte) && (reason & VM_UFFD_WP))
  216. ret = true;
  217. out:
  218. return ret;
  219. }
  220. #else
  221. static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
  222. unsigned long address,
  223. unsigned long flags,
  224. unsigned long reason)
  225. {
  226. return false; /* should never get here */
  227. }
  228. #endif /* CONFIG_HUGETLB_PAGE */
  229. /*
  230. * Verify the pagetables are still not ok after having reigstered into
  231. * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
  232. * userfault that has already been resolved, if userfaultfd_read and
  233. * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
  234. * threads.
  235. */
  236. static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
  237. unsigned long address,
  238. unsigned long flags,
  239. unsigned long reason)
  240. {
  241. struct mm_struct *mm = ctx->mm;
  242. pgd_t *pgd;
  243. pud_t *pud;
  244. pmd_t *pmd, _pmd;
  245. pte_t *pte;
  246. bool ret = true;
  247. VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
  248. pgd = pgd_offset(mm, address);
  249. if (!pgd_present(*pgd))
  250. goto out;
  251. pud = pud_offset(pgd, address);
  252. if (!pud_present(*pud))
  253. goto out;
  254. pmd = pmd_offset(pud, address);
  255. /*
  256. * READ_ONCE must function as a barrier with narrower scope
  257. * and it must be equivalent to:
  258. * _pmd = *pmd; barrier();
  259. *
  260. * This is to deal with the instability (as in
  261. * pmd_trans_unstable) of the pmd.
  262. */
  263. _pmd = READ_ONCE(*pmd);
  264. if (!pmd_present(_pmd))
  265. goto out;
  266. ret = false;
  267. if (pmd_trans_huge(_pmd))
  268. goto out;
  269. /*
  270. * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
  271. * and use the standard pte_offset_map() instead of parsing _pmd.
  272. */
  273. pte = pte_offset_map(pmd, address);
  274. /*
  275. * Lockless access: we're in a wait_event so it's ok if it
  276. * changes under us.
  277. */
  278. if (pte_none(*pte))
  279. ret = true;
  280. pte_unmap(pte);
  281. out:
  282. return ret;
  283. }
  284. /*
  285. * The locking rules involved in returning VM_FAULT_RETRY depending on
  286. * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
  287. * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
  288. * recommendation in __lock_page_or_retry is not an understatement.
  289. *
  290. * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
  291. * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
  292. * not set.
  293. *
  294. * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
  295. * set, VM_FAULT_RETRY can still be returned if and only if there are
  296. * fatal_signal_pending()s, and the mmap_sem must be released before
  297. * returning it.
  298. */
  299. int handle_userfault(struct vm_fault *vmf, unsigned long reason)
  300. {
  301. struct mm_struct *mm = vmf->vma->vm_mm;
  302. struct userfaultfd_ctx *ctx;
  303. struct userfaultfd_wait_queue uwq;
  304. int ret;
  305. bool must_wait, return_to_userland;
  306. long blocking_state;
  307. BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
  308. ret = VM_FAULT_SIGBUS;
  309. ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
  310. if (!ctx)
  311. goto out;
  312. BUG_ON(ctx->mm != mm);
  313. VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
  314. VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
  315. /*
  316. * If it's already released don't get it. This avoids to loop
  317. * in __get_user_pages if userfaultfd_release waits on the
  318. * caller of handle_userfault to release the mmap_sem.
  319. */
  320. if (unlikely(ACCESS_ONCE(ctx->released)))
  321. goto out;
  322. /*
  323. * We don't do userfault handling for the final child pid update.
  324. */
  325. if (current->flags & PF_EXITING)
  326. goto out;
  327. /*
  328. * Check that we can return VM_FAULT_RETRY.
  329. *
  330. * NOTE: it should become possible to return VM_FAULT_RETRY
  331. * even if FAULT_FLAG_TRIED is set without leading to gup()
  332. * -EBUSY failures, if the userfaultfd is to be extended for
  333. * VM_UFFD_WP tracking and we intend to arm the userfault
  334. * without first stopping userland access to the memory. For
  335. * VM_UFFD_MISSING userfaults this is enough for now.
  336. */
  337. if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
  338. /*
  339. * Validate the invariant that nowait must allow retry
  340. * to be sure not to return SIGBUS erroneously on
  341. * nowait invocations.
  342. */
  343. BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
  344. #ifdef CONFIG_DEBUG_VM
  345. if (printk_ratelimit()) {
  346. printk(KERN_WARNING
  347. "FAULT_FLAG_ALLOW_RETRY missing %x\n",
  348. vmf->flags);
  349. dump_stack();
  350. }
  351. #endif
  352. goto out;
  353. }
  354. /*
  355. * Handle nowait, not much to do other than tell it to retry
  356. * and wait.
  357. */
  358. ret = VM_FAULT_RETRY;
  359. if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
  360. goto out;
  361. /* take the reference before dropping the mmap_sem */
  362. userfaultfd_ctx_get(ctx);
  363. init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
  364. uwq.wq.private = current;
  365. uwq.msg = userfault_msg(vmf->address, vmf->flags, reason);
  366. uwq.ctx = ctx;
  367. uwq.waken = false;
  368. return_to_userland =
  369. (vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
  370. (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
  371. blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
  372. TASK_KILLABLE;
  373. spin_lock(&ctx->fault_pending_wqh.lock);
  374. /*
  375. * After the __add_wait_queue the uwq is visible to userland
  376. * through poll/read().
  377. */
  378. __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
  379. /*
  380. * The smp_mb() after __set_current_state prevents the reads
  381. * following the spin_unlock to happen before the list_add in
  382. * __add_wait_queue.
  383. */
  384. set_current_state(blocking_state);
  385. spin_unlock(&ctx->fault_pending_wqh.lock);
  386. if (!is_vm_hugetlb_page(vmf->vma))
  387. must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
  388. reason);
  389. else
  390. must_wait = userfaultfd_huge_must_wait(ctx, vmf->address,
  391. vmf->flags, reason);
  392. up_read(&mm->mmap_sem);
  393. if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
  394. (return_to_userland ? !signal_pending(current) :
  395. !fatal_signal_pending(current)))) {
  396. wake_up_poll(&ctx->fd_wqh, POLLIN);
  397. schedule();
  398. ret |= VM_FAULT_MAJOR;
  399. /*
  400. * False wakeups can orginate even from rwsem before
  401. * up_read() however userfaults will wait either for a
  402. * targeted wakeup on the specific uwq waitqueue from
  403. * wake_userfault() or for signals or for uffd
  404. * release.
  405. */
  406. while (!READ_ONCE(uwq.waken)) {
  407. /*
  408. * This needs the full smp_store_mb()
  409. * guarantee as the state write must be
  410. * visible to other CPUs before reading
  411. * uwq.waken from other CPUs.
  412. */
  413. set_current_state(blocking_state);
  414. if (READ_ONCE(uwq.waken) ||
  415. READ_ONCE(ctx->released) ||
  416. (return_to_userland ? signal_pending(current) :
  417. fatal_signal_pending(current)))
  418. break;
  419. schedule();
  420. }
  421. }
  422. __set_current_state(TASK_RUNNING);
  423. if (return_to_userland) {
  424. if (signal_pending(current) &&
  425. !fatal_signal_pending(current)) {
  426. /*
  427. * If we got a SIGSTOP or SIGCONT and this is
  428. * a normal userland page fault, just let
  429. * userland return so the signal will be
  430. * handled and gdb debugging works. The page
  431. * fault code immediately after we return from
  432. * this function is going to release the
  433. * mmap_sem and it's not depending on it
  434. * (unlike gup would if we were not to return
  435. * VM_FAULT_RETRY).
  436. *
  437. * If a fatal signal is pending we still take
  438. * the streamlined VM_FAULT_RETRY failure path
  439. * and there's no need to retake the mmap_sem
  440. * in such case.
  441. */
  442. down_read(&mm->mmap_sem);
  443. ret = 0;
  444. }
  445. }
  446. /*
  447. * Here we race with the list_del; list_add in
  448. * userfaultfd_ctx_read(), however because we don't ever run
  449. * list_del_init() to refile across the two lists, the prev
  450. * and next pointers will never point to self. list_add also
  451. * would never let any of the two pointers to point to
  452. * self. So list_empty_careful won't risk to see both pointers
  453. * pointing to self at any time during the list refile. The
  454. * only case where list_del_init() is called is the full
  455. * removal in the wake function and there we don't re-list_add
  456. * and it's fine not to block on the spinlock. The uwq on this
  457. * kernel stack can be released after the list_del_init.
  458. */
  459. if (!list_empty_careful(&uwq.wq.task_list)) {
  460. spin_lock(&ctx->fault_pending_wqh.lock);
  461. /*
  462. * No need of list_del_init(), the uwq on the stack
  463. * will be freed shortly anyway.
  464. */
  465. list_del(&uwq.wq.task_list);
  466. spin_unlock(&ctx->fault_pending_wqh.lock);
  467. }
  468. /*
  469. * ctx may go away after this if the userfault pseudo fd is
  470. * already released.
  471. */
  472. userfaultfd_ctx_put(ctx);
  473. out:
  474. return ret;
  475. }
  476. static int userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
  477. struct userfaultfd_wait_queue *ewq)
  478. {
  479. int ret = 0;
  480. ewq->ctx = ctx;
  481. init_waitqueue_entry(&ewq->wq, current);
  482. spin_lock(&ctx->event_wqh.lock);
  483. /*
  484. * After the __add_wait_queue the uwq is visible to userland
  485. * through poll/read().
  486. */
  487. __add_wait_queue(&ctx->event_wqh, &ewq->wq);
  488. for (;;) {
  489. set_current_state(TASK_KILLABLE);
  490. if (ewq->msg.event == 0)
  491. break;
  492. if (ACCESS_ONCE(ctx->released) ||
  493. fatal_signal_pending(current)) {
  494. ret = -1;
  495. __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
  496. break;
  497. }
  498. spin_unlock(&ctx->event_wqh.lock);
  499. wake_up_poll(&ctx->fd_wqh, POLLIN);
  500. schedule();
  501. spin_lock(&ctx->event_wqh.lock);
  502. }
  503. __set_current_state(TASK_RUNNING);
  504. spin_unlock(&ctx->event_wqh.lock);
  505. /*
  506. * ctx may go away after this if the userfault pseudo fd is
  507. * already released.
  508. */
  509. userfaultfd_ctx_put(ctx);
  510. return ret;
  511. }
  512. static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
  513. struct userfaultfd_wait_queue *ewq)
  514. {
  515. ewq->msg.event = 0;
  516. wake_up_locked(&ctx->event_wqh);
  517. __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
  518. }
  519. int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
  520. {
  521. struct userfaultfd_ctx *ctx = NULL, *octx;
  522. struct userfaultfd_fork_ctx *fctx;
  523. octx = vma->vm_userfaultfd_ctx.ctx;
  524. if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
  525. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  526. vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
  527. return 0;
  528. }
  529. list_for_each_entry(fctx, fcs, list)
  530. if (fctx->orig == octx) {
  531. ctx = fctx->new;
  532. break;
  533. }
  534. if (!ctx) {
  535. fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
  536. if (!fctx)
  537. return -ENOMEM;
  538. ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
  539. if (!ctx) {
  540. kfree(fctx);
  541. return -ENOMEM;
  542. }
  543. atomic_set(&ctx->refcount, 1);
  544. ctx->flags = octx->flags;
  545. ctx->state = UFFD_STATE_RUNNING;
  546. ctx->features = octx->features;
  547. ctx->released = false;
  548. ctx->mm = vma->vm_mm;
  549. atomic_inc(&ctx->mm->mm_count);
  550. userfaultfd_ctx_get(octx);
  551. fctx->orig = octx;
  552. fctx->new = ctx;
  553. list_add_tail(&fctx->list, fcs);
  554. }
  555. vma->vm_userfaultfd_ctx.ctx = ctx;
  556. return 0;
  557. }
  558. static int dup_fctx(struct userfaultfd_fork_ctx *fctx)
  559. {
  560. struct userfaultfd_ctx *ctx = fctx->orig;
  561. struct userfaultfd_wait_queue ewq;
  562. msg_init(&ewq.msg);
  563. ewq.msg.event = UFFD_EVENT_FORK;
  564. ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
  565. return userfaultfd_event_wait_completion(ctx, &ewq);
  566. }
  567. void dup_userfaultfd_complete(struct list_head *fcs)
  568. {
  569. int ret = 0;
  570. struct userfaultfd_fork_ctx *fctx, *n;
  571. list_for_each_entry_safe(fctx, n, fcs, list) {
  572. if (!ret)
  573. ret = dup_fctx(fctx);
  574. list_del(&fctx->list);
  575. kfree(fctx);
  576. }
  577. }
  578. void mremap_userfaultfd_prep(struct vm_area_struct *vma,
  579. struct vm_userfaultfd_ctx *vm_ctx)
  580. {
  581. struct userfaultfd_ctx *ctx;
  582. ctx = vma->vm_userfaultfd_ctx.ctx;
  583. if (ctx && (ctx->features & UFFD_FEATURE_EVENT_REMAP)) {
  584. vm_ctx->ctx = ctx;
  585. userfaultfd_ctx_get(ctx);
  586. }
  587. }
  588. void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
  589. unsigned long from, unsigned long to,
  590. unsigned long len)
  591. {
  592. struct userfaultfd_ctx *ctx = vm_ctx->ctx;
  593. struct userfaultfd_wait_queue ewq;
  594. if (!ctx)
  595. return;
  596. if (to & ~PAGE_MASK) {
  597. userfaultfd_ctx_put(ctx);
  598. return;
  599. }
  600. msg_init(&ewq.msg);
  601. ewq.msg.event = UFFD_EVENT_REMAP;
  602. ewq.msg.arg.remap.from = from;
  603. ewq.msg.arg.remap.to = to;
  604. ewq.msg.arg.remap.len = len;
  605. userfaultfd_event_wait_completion(ctx, &ewq);
  606. }
  607. void madvise_userfault_dontneed(struct vm_area_struct *vma,
  608. struct vm_area_struct **prev,
  609. unsigned long start, unsigned long end)
  610. {
  611. struct mm_struct *mm = vma->vm_mm;
  612. struct userfaultfd_ctx *ctx;
  613. struct userfaultfd_wait_queue ewq;
  614. ctx = vma->vm_userfaultfd_ctx.ctx;
  615. if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_MADVDONTNEED))
  616. return;
  617. userfaultfd_ctx_get(ctx);
  618. up_read(&mm->mmap_sem);
  619. *prev = NULL; /* We wait for ACK w/o the mmap semaphore */
  620. msg_init(&ewq.msg);
  621. ewq.msg.event = UFFD_EVENT_MADVDONTNEED;
  622. ewq.msg.arg.madv_dn.start = start;
  623. ewq.msg.arg.madv_dn.end = end;
  624. userfaultfd_event_wait_completion(ctx, &ewq);
  625. down_read(&mm->mmap_sem);
  626. }
  627. static int userfaultfd_release(struct inode *inode, struct file *file)
  628. {
  629. struct userfaultfd_ctx *ctx = file->private_data;
  630. struct mm_struct *mm = ctx->mm;
  631. struct vm_area_struct *vma, *prev;
  632. /* len == 0 means wake all */
  633. struct userfaultfd_wake_range range = { .len = 0, };
  634. unsigned long new_flags;
  635. ACCESS_ONCE(ctx->released) = true;
  636. if (!mmget_not_zero(mm))
  637. goto wakeup;
  638. /*
  639. * Flush page faults out of all CPUs. NOTE: all page faults
  640. * must be retried without returning VM_FAULT_SIGBUS if
  641. * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
  642. * changes while handle_userfault released the mmap_sem. So
  643. * it's critical that released is set to true (above), before
  644. * taking the mmap_sem for writing.
  645. */
  646. down_write(&mm->mmap_sem);
  647. prev = NULL;
  648. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  649. cond_resched();
  650. BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
  651. !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
  652. if (vma->vm_userfaultfd_ctx.ctx != ctx) {
  653. prev = vma;
  654. continue;
  655. }
  656. new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
  657. prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
  658. new_flags, vma->anon_vma,
  659. vma->vm_file, vma->vm_pgoff,
  660. vma_policy(vma),
  661. NULL_VM_UFFD_CTX);
  662. if (prev)
  663. vma = prev;
  664. else
  665. prev = vma;
  666. vma->vm_flags = new_flags;
  667. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  668. }
  669. up_write(&mm->mmap_sem);
  670. mmput(mm);
  671. wakeup:
  672. /*
  673. * After no new page faults can wait on this fault_*wqh, flush
  674. * the last page faults that may have been already waiting on
  675. * the fault_*wqh.
  676. */
  677. spin_lock(&ctx->fault_pending_wqh.lock);
  678. __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
  679. __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
  680. spin_unlock(&ctx->fault_pending_wqh.lock);
  681. wake_up_poll(&ctx->fd_wqh, POLLHUP);
  682. userfaultfd_ctx_put(ctx);
  683. return 0;
  684. }
  685. /* fault_pending_wqh.lock must be hold by the caller */
  686. static inline struct userfaultfd_wait_queue *find_userfault_in(
  687. wait_queue_head_t *wqh)
  688. {
  689. wait_queue_t *wq;
  690. struct userfaultfd_wait_queue *uwq;
  691. VM_BUG_ON(!spin_is_locked(&wqh->lock));
  692. uwq = NULL;
  693. if (!waitqueue_active(wqh))
  694. goto out;
  695. /* walk in reverse to provide FIFO behavior to read userfaults */
  696. wq = list_last_entry(&wqh->task_list, typeof(*wq), task_list);
  697. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  698. out:
  699. return uwq;
  700. }
  701. static inline struct userfaultfd_wait_queue *find_userfault(
  702. struct userfaultfd_ctx *ctx)
  703. {
  704. return find_userfault_in(&ctx->fault_pending_wqh);
  705. }
  706. static inline struct userfaultfd_wait_queue *find_userfault_evt(
  707. struct userfaultfd_ctx *ctx)
  708. {
  709. return find_userfault_in(&ctx->event_wqh);
  710. }
  711. static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
  712. {
  713. struct userfaultfd_ctx *ctx = file->private_data;
  714. unsigned int ret;
  715. poll_wait(file, &ctx->fd_wqh, wait);
  716. switch (ctx->state) {
  717. case UFFD_STATE_WAIT_API:
  718. return POLLERR;
  719. case UFFD_STATE_RUNNING:
  720. /*
  721. * poll() never guarantees that read won't block.
  722. * userfaults can be waken before they're read().
  723. */
  724. if (unlikely(!(file->f_flags & O_NONBLOCK)))
  725. return POLLERR;
  726. /*
  727. * lockless access to see if there are pending faults
  728. * __pollwait last action is the add_wait_queue but
  729. * the spin_unlock would allow the waitqueue_active to
  730. * pass above the actual list_add inside
  731. * add_wait_queue critical section. So use a full
  732. * memory barrier to serialize the list_add write of
  733. * add_wait_queue() with the waitqueue_active read
  734. * below.
  735. */
  736. ret = 0;
  737. smp_mb();
  738. if (waitqueue_active(&ctx->fault_pending_wqh))
  739. ret = POLLIN;
  740. else if (waitqueue_active(&ctx->event_wqh))
  741. ret = POLLIN;
  742. return ret;
  743. default:
  744. WARN_ON_ONCE(1);
  745. return POLLERR;
  746. }
  747. }
  748. static const struct file_operations userfaultfd_fops;
  749. static int resolve_userfault_fork(struct userfaultfd_ctx *ctx,
  750. struct userfaultfd_ctx *new,
  751. struct uffd_msg *msg)
  752. {
  753. int fd;
  754. struct file *file;
  755. unsigned int flags = new->flags & UFFD_SHARED_FCNTL_FLAGS;
  756. fd = get_unused_fd_flags(flags);
  757. if (fd < 0)
  758. return fd;
  759. file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, new,
  760. O_RDWR | flags);
  761. if (IS_ERR(file)) {
  762. put_unused_fd(fd);
  763. return PTR_ERR(file);
  764. }
  765. fd_install(fd, file);
  766. msg->arg.reserved.reserved1 = 0;
  767. msg->arg.fork.ufd = fd;
  768. return 0;
  769. }
  770. static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
  771. struct uffd_msg *msg)
  772. {
  773. ssize_t ret;
  774. DECLARE_WAITQUEUE(wait, current);
  775. struct userfaultfd_wait_queue *uwq;
  776. /*
  777. * Handling fork event requires sleeping operations, so
  778. * we drop the event_wqh lock, then do these ops, then
  779. * lock it back and wake up the waiter. While the lock is
  780. * dropped the ewq may go away so we keep track of it
  781. * carefully.
  782. */
  783. LIST_HEAD(fork_event);
  784. struct userfaultfd_ctx *fork_nctx = NULL;
  785. /* always take the fd_wqh lock before the fault_pending_wqh lock */
  786. spin_lock(&ctx->fd_wqh.lock);
  787. __add_wait_queue(&ctx->fd_wqh, &wait);
  788. for (;;) {
  789. set_current_state(TASK_INTERRUPTIBLE);
  790. spin_lock(&ctx->fault_pending_wqh.lock);
  791. uwq = find_userfault(ctx);
  792. if (uwq) {
  793. /*
  794. * Use a seqcount to repeat the lockless check
  795. * in wake_userfault() to avoid missing
  796. * wakeups because during the refile both
  797. * waitqueue could become empty if this is the
  798. * only userfault.
  799. */
  800. write_seqcount_begin(&ctx->refile_seq);
  801. /*
  802. * The fault_pending_wqh.lock prevents the uwq
  803. * to disappear from under us.
  804. *
  805. * Refile this userfault from
  806. * fault_pending_wqh to fault_wqh, it's not
  807. * pending anymore after we read it.
  808. *
  809. * Use list_del() by hand (as
  810. * userfaultfd_wake_function also uses
  811. * list_del_init() by hand) to be sure nobody
  812. * changes __remove_wait_queue() to use
  813. * list_del_init() in turn breaking the
  814. * !list_empty_careful() check in
  815. * handle_userfault(). The uwq->wq.task_list
  816. * must never be empty at any time during the
  817. * refile, or the waitqueue could disappear
  818. * from under us. The "wait_queue_head_t"
  819. * parameter of __remove_wait_queue() is unused
  820. * anyway.
  821. */
  822. list_del(&uwq->wq.task_list);
  823. __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
  824. write_seqcount_end(&ctx->refile_seq);
  825. /* careful to always initialize msg if ret == 0 */
  826. *msg = uwq->msg;
  827. spin_unlock(&ctx->fault_pending_wqh.lock);
  828. ret = 0;
  829. break;
  830. }
  831. spin_unlock(&ctx->fault_pending_wqh.lock);
  832. spin_lock(&ctx->event_wqh.lock);
  833. uwq = find_userfault_evt(ctx);
  834. if (uwq) {
  835. *msg = uwq->msg;
  836. if (uwq->msg.event == UFFD_EVENT_FORK) {
  837. fork_nctx = (struct userfaultfd_ctx *)
  838. (unsigned long)
  839. uwq->msg.arg.reserved.reserved1;
  840. list_move(&uwq->wq.task_list, &fork_event);
  841. spin_unlock(&ctx->event_wqh.lock);
  842. ret = 0;
  843. break;
  844. }
  845. userfaultfd_event_complete(ctx, uwq);
  846. spin_unlock(&ctx->event_wqh.lock);
  847. ret = 0;
  848. break;
  849. }
  850. spin_unlock(&ctx->event_wqh.lock);
  851. if (signal_pending(current)) {
  852. ret = -ERESTARTSYS;
  853. break;
  854. }
  855. if (no_wait) {
  856. ret = -EAGAIN;
  857. break;
  858. }
  859. spin_unlock(&ctx->fd_wqh.lock);
  860. schedule();
  861. spin_lock(&ctx->fd_wqh.lock);
  862. }
  863. __remove_wait_queue(&ctx->fd_wqh, &wait);
  864. __set_current_state(TASK_RUNNING);
  865. spin_unlock(&ctx->fd_wqh.lock);
  866. if (!ret && msg->event == UFFD_EVENT_FORK) {
  867. ret = resolve_userfault_fork(ctx, fork_nctx, msg);
  868. if (!ret) {
  869. spin_lock(&ctx->event_wqh.lock);
  870. if (!list_empty(&fork_event)) {
  871. uwq = list_first_entry(&fork_event,
  872. typeof(*uwq),
  873. wq.task_list);
  874. list_del(&uwq->wq.task_list);
  875. __add_wait_queue(&ctx->event_wqh, &uwq->wq);
  876. userfaultfd_event_complete(ctx, uwq);
  877. }
  878. spin_unlock(&ctx->event_wqh.lock);
  879. }
  880. }
  881. return ret;
  882. }
  883. static ssize_t userfaultfd_read(struct file *file, char __user *buf,
  884. size_t count, loff_t *ppos)
  885. {
  886. struct userfaultfd_ctx *ctx = file->private_data;
  887. ssize_t _ret, ret = 0;
  888. struct uffd_msg msg;
  889. int no_wait = file->f_flags & O_NONBLOCK;
  890. if (ctx->state == UFFD_STATE_WAIT_API)
  891. return -EINVAL;
  892. for (;;) {
  893. if (count < sizeof(msg))
  894. return ret ? ret : -EINVAL;
  895. _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
  896. if (_ret < 0)
  897. return ret ? ret : _ret;
  898. if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
  899. return ret ? ret : -EFAULT;
  900. ret += sizeof(msg);
  901. buf += sizeof(msg);
  902. count -= sizeof(msg);
  903. /*
  904. * Allow to read more than one fault at time but only
  905. * block if waiting for the very first one.
  906. */
  907. no_wait = O_NONBLOCK;
  908. }
  909. }
  910. static void __wake_userfault(struct userfaultfd_ctx *ctx,
  911. struct userfaultfd_wake_range *range)
  912. {
  913. unsigned long start, end;
  914. start = range->start;
  915. end = range->start + range->len;
  916. spin_lock(&ctx->fault_pending_wqh.lock);
  917. /* wake all in the range and autoremove */
  918. if (waitqueue_active(&ctx->fault_pending_wqh))
  919. __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
  920. range);
  921. if (waitqueue_active(&ctx->fault_wqh))
  922. __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
  923. spin_unlock(&ctx->fault_pending_wqh.lock);
  924. }
  925. static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
  926. struct userfaultfd_wake_range *range)
  927. {
  928. unsigned seq;
  929. bool need_wakeup;
  930. /*
  931. * To be sure waitqueue_active() is not reordered by the CPU
  932. * before the pagetable update, use an explicit SMP memory
  933. * barrier here. PT lock release or up_read(mmap_sem) still
  934. * have release semantics that can allow the
  935. * waitqueue_active() to be reordered before the pte update.
  936. */
  937. smp_mb();
  938. /*
  939. * Use waitqueue_active because it's very frequent to
  940. * change the address space atomically even if there are no
  941. * userfaults yet. So we take the spinlock only when we're
  942. * sure we've userfaults to wake.
  943. */
  944. do {
  945. seq = read_seqcount_begin(&ctx->refile_seq);
  946. need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
  947. waitqueue_active(&ctx->fault_wqh);
  948. cond_resched();
  949. } while (read_seqcount_retry(&ctx->refile_seq, seq));
  950. if (need_wakeup)
  951. __wake_userfault(ctx, range);
  952. }
  953. static __always_inline int validate_range(struct mm_struct *mm,
  954. __u64 start, __u64 len)
  955. {
  956. __u64 task_size = mm->task_size;
  957. if (start & ~PAGE_MASK)
  958. return -EINVAL;
  959. if (len & ~PAGE_MASK)
  960. return -EINVAL;
  961. if (!len)
  962. return -EINVAL;
  963. if (start < mmap_min_addr)
  964. return -EINVAL;
  965. if (start >= task_size)
  966. return -EINVAL;
  967. if (len > task_size - start)
  968. return -EINVAL;
  969. return 0;
  970. }
  971. static int userfaultfd_register(struct userfaultfd_ctx *ctx,
  972. unsigned long arg)
  973. {
  974. struct mm_struct *mm = ctx->mm;
  975. struct vm_area_struct *vma, *prev, *cur;
  976. int ret;
  977. struct uffdio_register uffdio_register;
  978. struct uffdio_register __user *user_uffdio_register;
  979. unsigned long vm_flags, new_flags;
  980. bool found;
  981. bool huge_pages;
  982. unsigned long start, end, vma_end;
  983. user_uffdio_register = (struct uffdio_register __user *) arg;
  984. ret = -EFAULT;
  985. if (copy_from_user(&uffdio_register, user_uffdio_register,
  986. sizeof(uffdio_register)-sizeof(__u64)))
  987. goto out;
  988. ret = -EINVAL;
  989. if (!uffdio_register.mode)
  990. goto out;
  991. if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
  992. UFFDIO_REGISTER_MODE_WP))
  993. goto out;
  994. vm_flags = 0;
  995. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
  996. vm_flags |= VM_UFFD_MISSING;
  997. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
  998. vm_flags |= VM_UFFD_WP;
  999. /*
  1000. * FIXME: remove the below error constraint by
  1001. * implementing the wprotect tracking mode.
  1002. */
  1003. ret = -EINVAL;
  1004. goto out;
  1005. }
  1006. ret = validate_range(mm, uffdio_register.range.start,
  1007. uffdio_register.range.len);
  1008. if (ret)
  1009. goto out;
  1010. start = uffdio_register.range.start;
  1011. end = start + uffdio_register.range.len;
  1012. ret = -ENOMEM;
  1013. if (!mmget_not_zero(mm))
  1014. goto out;
  1015. down_write(&mm->mmap_sem);
  1016. vma = find_vma_prev(mm, start, &prev);
  1017. if (!vma)
  1018. goto out_unlock;
  1019. /* check that there's at least one vma in the range */
  1020. ret = -EINVAL;
  1021. if (vma->vm_start >= end)
  1022. goto out_unlock;
  1023. /*
  1024. * If the first vma contains huge pages, make sure start address
  1025. * is aligned to huge page size.
  1026. */
  1027. if (is_vm_hugetlb_page(vma)) {
  1028. unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
  1029. if (start & (vma_hpagesize - 1))
  1030. goto out_unlock;
  1031. }
  1032. /*
  1033. * Search for not compatible vmas.
  1034. *
  1035. * FIXME: this shall be relaxed later so that it doesn't fail
  1036. * on tmpfs backed vmas (in addition to the current allowance
  1037. * on anonymous vmas).
  1038. */
  1039. found = false;
  1040. huge_pages = false;
  1041. for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
  1042. cond_resched();
  1043. BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
  1044. !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
  1045. /* check not compatible vmas */
  1046. ret = -EINVAL;
  1047. if (!vma_is_anonymous(cur) && !is_vm_hugetlb_page(cur))
  1048. goto out_unlock;
  1049. /*
  1050. * If this vma contains ending address, and huge pages
  1051. * check alignment.
  1052. */
  1053. if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
  1054. end > cur->vm_start) {
  1055. unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
  1056. ret = -EINVAL;
  1057. if (end & (vma_hpagesize - 1))
  1058. goto out_unlock;
  1059. }
  1060. /*
  1061. * Check that this vma isn't already owned by a
  1062. * different userfaultfd. We can't allow more than one
  1063. * userfaultfd to own a single vma simultaneously or we
  1064. * wouldn't know which one to deliver the userfaults to.
  1065. */
  1066. ret = -EBUSY;
  1067. if (cur->vm_userfaultfd_ctx.ctx &&
  1068. cur->vm_userfaultfd_ctx.ctx != ctx)
  1069. goto out_unlock;
  1070. /*
  1071. * Note vmas containing huge pages
  1072. */
  1073. if (is_vm_hugetlb_page(cur))
  1074. huge_pages = true;
  1075. found = true;
  1076. }
  1077. BUG_ON(!found);
  1078. if (vma->vm_start < start)
  1079. prev = vma;
  1080. ret = 0;
  1081. do {
  1082. cond_resched();
  1083. BUG_ON(!vma_is_anonymous(vma) && !is_vm_hugetlb_page(vma));
  1084. BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
  1085. vma->vm_userfaultfd_ctx.ctx != ctx);
  1086. /*
  1087. * Nothing to do: this vma is already registered into this
  1088. * userfaultfd and with the right tracking mode too.
  1089. */
  1090. if (vma->vm_userfaultfd_ctx.ctx == ctx &&
  1091. (vma->vm_flags & vm_flags) == vm_flags)
  1092. goto skip;
  1093. if (vma->vm_start > start)
  1094. start = vma->vm_start;
  1095. vma_end = min(end, vma->vm_end);
  1096. new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
  1097. prev = vma_merge(mm, prev, start, vma_end, new_flags,
  1098. vma->anon_vma, vma->vm_file, vma->vm_pgoff,
  1099. vma_policy(vma),
  1100. ((struct vm_userfaultfd_ctx){ ctx }));
  1101. if (prev) {
  1102. vma = prev;
  1103. goto next;
  1104. }
  1105. if (vma->vm_start < start) {
  1106. ret = split_vma(mm, vma, start, 1);
  1107. if (ret)
  1108. break;
  1109. }
  1110. if (vma->vm_end > end) {
  1111. ret = split_vma(mm, vma, end, 0);
  1112. if (ret)
  1113. break;
  1114. }
  1115. next:
  1116. /*
  1117. * In the vma_merge() successful mprotect-like case 8:
  1118. * the next vma was merged into the current one and
  1119. * the current one has not been updated yet.
  1120. */
  1121. vma->vm_flags = new_flags;
  1122. vma->vm_userfaultfd_ctx.ctx = ctx;
  1123. skip:
  1124. prev = vma;
  1125. start = vma->vm_end;
  1126. vma = vma->vm_next;
  1127. } while (vma && vma->vm_start < end);
  1128. out_unlock:
  1129. up_write(&mm->mmap_sem);
  1130. mmput(mm);
  1131. if (!ret) {
  1132. /*
  1133. * Now that we scanned all vmas we can already tell
  1134. * userland which ioctls methods are guaranteed to
  1135. * succeed on this range.
  1136. */
  1137. if (put_user(huge_pages ? UFFD_API_RANGE_IOCTLS_HPAGE :
  1138. UFFD_API_RANGE_IOCTLS,
  1139. &user_uffdio_register->ioctls))
  1140. ret = -EFAULT;
  1141. }
  1142. out:
  1143. return ret;
  1144. }
  1145. static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
  1146. unsigned long arg)
  1147. {
  1148. struct mm_struct *mm = ctx->mm;
  1149. struct vm_area_struct *vma, *prev, *cur;
  1150. int ret;
  1151. struct uffdio_range uffdio_unregister;
  1152. unsigned long new_flags;
  1153. bool found;
  1154. unsigned long start, end, vma_end;
  1155. const void __user *buf = (void __user *)arg;
  1156. ret = -EFAULT;
  1157. if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
  1158. goto out;
  1159. ret = validate_range(mm, uffdio_unregister.start,
  1160. uffdio_unregister.len);
  1161. if (ret)
  1162. goto out;
  1163. start = uffdio_unregister.start;
  1164. end = start + uffdio_unregister.len;
  1165. ret = -ENOMEM;
  1166. if (!mmget_not_zero(mm))
  1167. goto out;
  1168. down_write(&mm->mmap_sem);
  1169. vma = find_vma_prev(mm, start, &prev);
  1170. if (!vma)
  1171. goto out_unlock;
  1172. /* check that there's at least one vma in the range */
  1173. ret = -EINVAL;
  1174. if (vma->vm_start >= end)
  1175. goto out_unlock;
  1176. /*
  1177. * If the first vma contains huge pages, make sure start address
  1178. * is aligned to huge page size.
  1179. */
  1180. if (is_vm_hugetlb_page(vma)) {
  1181. unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
  1182. if (start & (vma_hpagesize - 1))
  1183. goto out_unlock;
  1184. }
  1185. /*
  1186. * Search for not compatible vmas.
  1187. *
  1188. * FIXME: this shall be relaxed later so that it doesn't fail
  1189. * on tmpfs backed vmas (in addition to the current allowance
  1190. * on anonymous vmas).
  1191. */
  1192. found = false;
  1193. ret = -EINVAL;
  1194. for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
  1195. cond_resched();
  1196. BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
  1197. !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
  1198. /*
  1199. * Check not compatible vmas, not strictly required
  1200. * here as not compatible vmas cannot have an
  1201. * userfaultfd_ctx registered on them, but this
  1202. * provides for more strict behavior to notice
  1203. * unregistration errors.
  1204. */
  1205. if (!vma_is_anonymous(cur) && !is_vm_hugetlb_page(cur))
  1206. goto out_unlock;
  1207. found = true;
  1208. }
  1209. BUG_ON(!found);
  1210. if (vma->vm_start < start)
  1211. prev = vma;
  1212. ret = 0;
  1213. do {
  1214. cond_resched();
  1215. BUG_ON(!vma_is_anonymous(vma) && !is_vm_hugetlb_page(vma));
  1216. /*
  1217. * Nothing to do: this vma is already registered into this
  1218. * userfaultfd and with the right tracking mode too.
  1219. */
  1220. if (!vma->vm_userfaultfd_ctx.ctx)
  1221. goto skip;
  1222. if (vma->vm_start > start)
  1223. start = vma->vm_start;
  1224. vma_end = min(end, vma->vm_end);
  1225. if (userfaultfd_missing(vma)) {
  1226. /*
  1227. * Wake any concurrent pending userfault while
  1228. * we unregister, so they will not hang
  1229. * permanently and it avoids userland to call
  1230. * UFFDIO_WAKE explicitly.
  1231. */
  1232. struct userfaultfd_wake_range range;
  1233. range.start = start;
  1234. range.len = vma_end - start;
  1235. wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
  1236. }
  1237. new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
  1238. prev = vma_merge(mm, prev, start, vma_end, new_flags,
  1239. vma->anon_vma, vma->vm_file, vma->vm_pgoff,
  1240. vma_policy(vma),
  1241. NULL_VM_UFFD_CTX);
  1242. if (prev) {
  1243. vma = prev;
  1244. goto next;
  1245. }
  1246. if (vma->vm_start < start) {
  1247. ret = split_vma(mm, vma, start, 1);
  1248. if (ret)
  1249. break;
  1250. }
  1251. if (vma->vm_end > end) {
  1252. ret = split_vma(mm, vma, end, 0);
  1253. if (ret)
  1254. break;
  1255. }
  1256. next:
  1257. /*
  1258. * In the vma_merge() successful mprotect-like case 8:
  1259. * the next vma was merged into the current one and
  1260. * the current one has not been updated yet.
  1261. */
  1262. vma->vm_flags = new_flags;
  1263. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  1264. skip:
  1265. prev = vma;
  1266. start = vma->vm_end;
  1267. vma = vma->vm_next;
  1268. } while (vma && vma->vm_start < end);
  1269. out_unlock:
  1270. up_write(&mm->mmap_sem);
  1271. mmput(mm);
  1272. out:
  1273. return ret;
  1274. }
  1275. /*
  1276. * userfaultfd_wake may be used in combination with the
  1277. * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
  1278. */
  1279. static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
  1280. unsigned long arg)
  1281. {
  1282. int ret;
  1283. struct uffdio_range uffdio_wake;
  1284. struct userfaultfd_wake_range range;
  1285. const void __user *buf = (void __user *)arg;
  1286. ret = -EFAULT;
  1287. if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
  1288. goto out;
  1289. ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
  1290. if (ret)
  1291. goto out;
  1292. range.start = uffdio_wake.start;
  1293. range.len = uffdio_wake.len;
  1294. /*
  1295. * len == 0 means wake all and we don't want to wake all here,
  1296. * so check it again to be sure.
  1297. */
  1298. VM_BUG_ON(!range.len);
  1299. wake_userfault(ctx, &range);
  1300. ret = 0;
  1301. out:
  1302. return ret;
  1303. }
  1304. static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
  1305. unsigned long arg)
  1306. {
  1307. __s64 ret;
  1308. struct uffdio_copy uffdio_copy;
  1309. struct uffdio_copy __user *user_uffdio_copy;
  1310. struct userfaultfd_wake_range range;
  1311. user_uffdio_copy = (struct uffdio_copy __user *) arg;
  1312. ret = -EFAULT;
  1313. if (copy_from_user(&uffdio_copy, user_uffdio_copy,
  1314. /* don't copy "copy" last field */
  1315. sizeof(uffdio_copy)-sizeof(__s64)))
  1316. goto out;
  1317. ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
  1318. if (ret)
  1319. goto out;
  1320. /*
  1321. * double check for wraparound just in case. copy_from_user()
  1322. * will later check uffdio_copy.src + uffdio_copy.len to fit
  1323. * in the userland range.
  1324. */
  1325. ret = -EINVAL;
  1326. if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
  1327. goto out;
  1328. if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
  1329. goto out;
  1330. if (mmget_not_zero(ctx->mm)) {
  1331. ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
  1332. uffdio_copy.len);
  1333. mmput(ctx->mm);
  1334. }
  1335. if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
  1336. return -EFAULT;
  1337. if (ret < 0)
  1338. goto out;
  1339. BUG_ON(!ret);
  1340. /* len == 0 would wake all */
  1341. range.len = ret;
  1342. if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
  1343. range.start = uffdio_copy.dst;
  1344. wake_userfault(ctx, &range);
  1345. }
  1346. ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
  1347. out:
  1348. return ret;
  1349. }
  1350. static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
  1351. unsigned long arg)
  1352. {
  1353. __s64 ret;
  1354. struct uffdio_zeropage uffdio_zeropage;
  1355. struct uffdio_zeropage __user *user_uffdio_zeropage;
  1356. struct userfaultfd_wake_range range;
  1357. user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
  1358. ret = -EFAULT;
  1359. if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
  1360. /* don't copy "zeropage" last field */
  1361. sizeof(uffdio_zeropage)-sizeof(__s64)))
  1362. goto out;
  1363. ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
  1364. uffdio_zeropage.range.len);
  1365. if (ret)
  1366. goto out;
  1367. ret = -EINVAL;
  1368. if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
  1369. goto out;
  1370. if (mmget_not_zero(ctx->mm)) {
  1371. ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
  1372. uffdio_zeropage.range.len);
  1373. mmput(ctx->mm);
  1374. }
  1375. if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
  1376. return -EFAULT;
  1377. if (ret < 0)
  1378. goto out;
  1379. /* len == 0 would wake all */
  1380. BUG_ON(!ret);
  1381. range.len = ret;
  1382. if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
  1383. range.start = uffdio_zeropage.range.start;
  1384. wake_userfault(ctx, &range);
  1385. }
  1386. ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
  1387. out:
  1388. return ret;
  1389. }
  1390. static inline unsigned int uffd_ctx_features(__u64 user_features)
  1391. {
  1392. /*
  1393. * For the current set of features the bits just coincide
  1394. */
  1395. return (unsigned int)user_features;
  1396. }
  1397. /*
  1398. * userland asks for a certain API version and we return which bits
  1399. * and ioctl commands are implemented in this kernel for such API
  1400. * version or -EINVAL if unknown.
  1401. */
  1402. static int userfaultfd_api(struct userfaultfd_ctx *ctx,
  1403. unsigned long arg)
  1404. {
  1405. struct uffdio_api uffdio_api;
  1406. void __user *buf = (void __user *)arg;
  1407. int ret;
  1408. __u64 features;
  1409. ret = -EINVAL;
  1410. if (ctx->state != UFFD_STATE_WAIT_API)
  1411. goto out;
  1412. ret = -EFAULT;
  1413. if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
  1414. goto out;
  1415. features = uffdio_api.features;
  1416. if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES)) {
  1417. memset(&uffdio_api, 0, sizeof(uffdio_api));
  1418. if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
  1419. goto out;
  1420. ret = -EINVAL;
  1421. goto out;
  1422. }
  1423. /* report all available features and ioctls to userland */
  1424. uffdio_api.features = UFFD_API_FEATURES;
  1425. uffdio_api.ioctls = UFFD_API_IOCTLS;
  1426. ret = -EFAULT;
  1427. if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
  1428. goto out;
  1429. ctx->state = UFFD_STATE_RUNNING;
  1430. /* only enable the requested features for this uffd context */
  1431. ctx->features = uffd_ctx_features(features);
  1432. ret = 0;
  1433. out:
  1434. return ret;
  1435. }
  1436. static long userfaultfd_ioctl(struct file *file, unsigned cmd,
  1437. unsigned long arg)
  1438. {
  1439. int ret = -EINVAL;
  1440. struct userfaultfd_ctx *ctx = file->private_data;
  1441. if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
  1442. return -EINVAL;
  1443. switch(cmd) {
  1444. case UFFDIO_API:
  1445. ret = userfaultfd_api(ctx, arg);
  1446. break;
  1447. case UFFDIO_REGISTER:
  1448. ret = userfaultfd_register(ctx, arg);
  1449. break;
  1450. case UFFDIO_UNREGISTER:
  1451. ret = userfaultfd_unregister(ctx, arg);
  1452. break;
  1453. case UFFDIO_WAKE:
  1454. ret = userfaultfd_wake(ctx, arg);
  1455. break;
  1456. case UFFDIO_COPY:
  1457. ret = userfaultfd_copy(ctx, arg);
  1458. break;
  1459. case UFFDIO_ZEROPAGE:
  1460. ret = userfaultfd_zeropage(ctx, arg);
  1461. break;
  1462. }
  1463. return ret;
  1464. }
  1465. #ifdef CONFIG_PROC_FS
  1466. static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
  1467. {
  1468. struct userfaultfd_ctx *ctx = f->private_data;
  1469. wait_queue_t *wq;
  1470. struct userfaultfd_wait_queue *uwq;
  1471. unsigned long pending = 0, total = 0;
  1472. spin_lock(&ctx->fault_pending_wqh.lock);
  1473. list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
  1474. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  1475. pending++;
  1476. total++;
  1477. }
  1478. list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
  1479. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  1480. total++;
  1481. }
  1482. spin_unlock(&ctx->fault_pending_wqh.lock);
  1483. /*
  1484. * If more protocols will be added, there will be all shown
  1485. * separated by a space. Like this:
  1486. * protocols: aa:... bb:...
  1487. */
  1488. seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
  1489. pending, total, UFFD_API, UFFD_API_FEATURES,
  1490. UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
  1491. }
  1492. #endif
  1493. static const struct file_operations userfaultfd_fops = {
  1494. #ifdef CONFIG_PROC_FS
  1495. .show_fdinfo = userfaultfd_show_fdinfo,
  1496. #endif
  1497. .release = userfaultfd_release,
  1498. .poll = userfaultfd_poll,
  1499. .read = userfaultfd_read,
  1500. .unlocked_ioctl = userfaultfd_ioctl,
  1501. .compat_ioctl = userfaultfd_ioctl,
  1502. .llseek = noop_llseek,
  1503. };
  1504. static void init_once_userfaultfd_ctx(void *mem)
  1505. {
  1506. struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
  1507. init_waitqueue_head(&ctx->fault_pending_wqh);
  1508. init_waitqueue_head(&ctx->fault_wqh);
  1509. init_waitqueue_head(&ctx->event_wqh);
  1510. init_waitqueue_head(&ctx->fd_wqh);
  1511. seqcount_init(&ctx->refile_seq);
  1512. }
  1513. /**
  1514. * userfaultfd_file_create - Creates an userfaultfd file pointer.
  1515. * @flags: Flags for the userfaultfd file.
  1516. *
  1517. * This function creates an userfaultfd file pointer, w/out installing
  1518. * it into the fd table. This is useful when the userfaultfd file is
  1519. * used during the initialization of data structures that require
  1520. * extra setup after the userfaultfd creation. So the userfaultfd
  1521. * creation is split into the file pointer creation phase, and the
  1522. * file descriptor installation phase. In this way races with
  1523. * userspace closing the newly installed file descriptor can be
  1524. * avoided. Returns an userfaultfd file pointer, or a proper error
  1525. * pointer.
  1526. */
  1527. static struct file *userfaultfd_file_create(int flags)
  1528. {
  1529. struct file *file;
  1530. struct userfaultfd_ctx *ctx;
  1531. BUG_ON(!current->mm);
  1532. /* Check the UFFD_* constants for consistency. */
  1533. BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
  1534. BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
  1535. file = ERR_PTR(-EINVAL);
  1536. if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
  1537. goto out;
  1538. file = ERR_PTR(-ENOMEM);
  1539. ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
  1540. if (!ctx)
  1541. goto out;
  1542. atomic_set(&ctx->refcount, 1);
  1543. ctx->flags = flags;
  1544. ctx->features = 0;
  1545. ctx->state = UFFD_STATE_WAIT_API;
  1546. ctx->released = false;
  1547. ctx->mm = current->mm;
  1548. /* prevent the mm struct to be freed */
  1549. atomic_inc(&ctx->mm->mm_count);
  1550. file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
  1551. O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
  1552. if (IS_ERR(file)) {
  1553. mmdrop(ctx->mm);
  1554. kmem_cache_free(userfaultfd_ctx_cachep, ctx);
  1555. }
  1556. out:
  1557. return file;
  1558. }
  1559. SYSCALL_DEFINE1(userfaultfd, int, flags)
  1560. {
  1561. int fd, error;
  1562. struct file *file;
  1563. error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
  1564. if (error < 0)
  1565. return error;
  1566. fd = error;
  1567. file = userfaultfd_file_create(flags);
  1568. if (IS_ERR(file)) {
  1569. error = PTR_ERR(file);
  1570. goto err_put_unused_fd;
  1571. }
  1572. fd_install(fd, file);
  1573. return fd;
  1574. err_put_unused_fd:
  1575. put_unused_fd(fd);
  1576. return error;
  1577. }
  1578. static int __init userfaultfd_init(void)
  1579. {
  1580. userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
  1581. sizeof(struct userfaultfd_ctx),
  1582. 0,
  1583. SLAB_HWCACHE_ALIGN|SLAB_PANIC,
  1584. init_once_userfaultfd_ctx);
  1585. return 0;
  1586. }
  1587. __initcall(userfaultfd_init);