userfaultfd.c 37 KB

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