userfaultfd.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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/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. ACCESS_ONCE(ctx->released) = true;
  428. if (!mmget_not_zero(mm))
  429. goto wakeup;
  430. /*
  431. * Flush page faults out of all CPUs. NOTE: all page faults
  432. * must be retried without returning VM_FAULT_SIGBUS if
  433. * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
  434. * changes while handle_userfault released the mmap_sem. So
  435. * it's critical that released is set to true (above), before
  436. * taking the mmap_sem for writing.
  437. */
  438. down_write(&mm->mmap_sem);
  439. prev = NULL;
  440. for (vma = mm->mmap; vma; vma = vma->vm_next) {
  441. cond_resched();
  442. BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
  443. !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
  444. if (vma->vm_userfaultfd_ctx.ctx != ctx) {
  445. prev = vma;
  446. continue;
  447. }
  448. new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
  449. prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
  450. new_flags, vma->anon_vma,
  451. vma->vm_file, vma->vm_pgoff,
  452. vma_policy(vma),
  453. NULL_VM_UFFD_CTX);
  454. if (prev)
  455. vma = prev;
  456. else
  457. prev = vma;
  458. vma->vm_flags = new_flags;
  459. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  460. }
  461. up_write(&mm->mmap_sem);
  462. mmput(mm);
  463. wakeup:
  464. /*
  465. * After no new page faults can wait on this fault_*wqh, flush
  466. * the last page faults that may have been already waiting on
  467. * the fault_*wqh.
  468. */
  469. spin_lock(&ctx->fault_pending_wqh.lock);
  470. __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
  471. __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
  472. spin_unlock(&ctx->fault_pending_wqh.lock);
  473. wake_up_poll(&ctx->fd_wqh, POLLHUP);
  474. userfaultfd_ctx_put(ctx);
  475. return 0;
  476. }
  477. /* fault_pending_wqh.lock must be hold by the caller */
  478. static inline struct userfaultfd_wait_queue *find_userfault(
  479. struct userfaultfd_ctx *ctx)
  480. {
  481. wait_queue_t *wq;
  482. struct userfaultfd_wait_queue *uwq;
  483. VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock));
  484. uwq = NULL;
  485. if (!waitqueue_active(&ctx->fault_pending_wqh))
  486. goto out;
  487. /* walk in reverse to provide FIFO behavior to read userfaults */
  488. wq = list_last_entry(&ctx->fault_pending_wqh.task_list,
  489. typeof(*wq), task_list);
  490. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  491. out:
  492. return uwq;
  493. }
  494. static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
  495. {
  496. struct userfaultfd_ctx *ctx = file->private_data;
  497. unsigned int ret;
  498. poll_wait(file, &ctx->fd_wqh, wait);
  499. switch (ctx->state) {
  500. case UFFD_STATE_WAIT_API:
  501. return POLLERR;
  502. case UFFD_STATE_RUNNING:
  503. /*
  504. * poll() never guarantees that read won't block.
  505. * userfaults can be waken before they're read().
  506. */
  507. if (unlikely(!(file->f_flags & O_NONBLOCK)))
  508. return POLLERR;
  509. /*
  510. * lockless access to see if there are pending faults
  511. * __pollwait last action is the add_wait_queue but
  512. * the spin_unlock would allow the waitqueue_active to
  513. * pass above the actual list_add inside
  514. * add_wait_queue critical section. So use a full
  515. * memory barrier to serialize the list_add write of
  516. * add_wait_queue() with the waitqueue_active read
  517. * below.
  518. */
  519. ret = 0;
  520. smp_mb();
  521. if (waitqueue_active(&ctx->fault_pending_wqh))
  522. ret = POLLIN;
  523. return ret;
  524. default:
  525. BUG();
  526. }
  527. }
  528. static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
  529. struct uffd_msg *msg)
  530. {
  531. ssize_t ret;
  532. DECLARE_WAITQUEUE(wait, current);
  533. struct userfaultfd_wait_queue *uwq;
  534. /* always take the fd_wqh lock before the fault_pending_wqh lock */
  535. spin_lock(&ctx->fd_wqh.lock);
  536. __add_wait_queue(&ctx->fd_wqh, &wait);
  537. for (;;) {
  538. set_current_state(TASK_INTERRUPTIBLE);
  539. spin_lock(&ctx->fault_pending_wqh.lock);
  540. uwq = find_userfault(ctx);
  541. if (uwq) {
  542. /*
  543. * Use a seqcount to repeat the lockless check
  544. * in wake_userfault() to avoid missing
  545. * wakeups because during the refile both
  546. * waitqueue could become empty if this is the
  547. * only userfault.
  548. */
  549. write_seqcount_begin(&ctx->refile_seq);
  550. /*
  551. * The fault_pending_wqh.lock prevents the uwq
  552. * to disappear from under us.
  553. *
  554. * Refile this userfault from
  555. * fault_pending_wqh to fault_wqh, it's not
  556. * pending anymore after we read it.
  557. *
  558. * Use list_del() by hand (as
  559. * userfaultfd_wake_function also uses
  560. * list_del_init() by hand) to be sure nobody
  561. * changes __remove_wait_queue() to use
  562. * list_del_init() in turn breaking the
  563. * !list_empty_careful() check in
  564. * handle_userfault(). The uwq->wq.task_list
  565. * must never be empty at any time during the
  566. * refile, or the waitqueue could disappear
  567. * from under us. The "wait_queue_head_t"
  568. * parameter of __remove_wait_queue() is unused
  569. * anyway.
  570. */
  571. list_del(&uwq->wq.task_list);
  572. __add_wait_queue(&ctx->fault_wqh, &uwq->wq);
  573. write_seqcount_end(&ctx->refile_seq);
  574. /* careful to always initialize msg if ret == 0 */
  575. *msg = uwq->msg;
  576. spin_unlock(&ctx->fault_pending_wqh.lock);
  577. ret = 0;
  578. break;
  579. }
  580. spin_unlock(&ctx->fault_pending_wqh.lock);
  581. if (signal_pending(current)) {
  582. ret = -ERESTARTSYS;
  583. break;
  584. }
  585. if (no_wait) {
  586. ret = -EAGAIN;
  587. break;
  588. }
  589. spin_unlock(&ctx->fd_wqh.lock);
  590. schedule();
  591. spin_lock(&ctx->fd_wqh.lock);
  592. }
  593. __remove_wait_queue(&ctx->fd_wqh, &wait);
  594. __set_current_state(TASK_RUNNING);
  595. spin_unlock(&ctx->fd_wqh.lock);
  596. return ret;
  597. }
  598. static ssize_t userfaultfd_read(struct file *file, char __user *buf,
  599. size_t count, loff_t *ppos)
  600. {
  601. struct userfaultfd_ctx *ctx = file->private_data;
  602. ssize_t _ret, ret = 0;
  603. struct uffd_msg msg;
  604. int no_wait = file->f_flags & O_NONBLOCK;
  605. if (ctx->state == UFFD_STATE_WAIT_API)
  606. return -EINVAL;
  607. for (;;) {
  608. if (count < sizeof(msg))
  609. return ret ? ret : -EINVAL;
  610. _ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
  611. if (_ret < 0)
  612. return ret ? ret : _ret;
  613. if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
  614. return ret ? ret : -EFAULT;
  615. ret += sizeof(msg);
  616. buf += sizeof(msg);
  617. count -= sizeof(msg);
  618. /*
  619. * Allow to read more than one fault at time but only
  620. * block if waiting for the very first one.
  621. */
  622. no_wait = O_NONBLOCK;
  623. }
  624. }
  625. static void __wake_userfault(struct userfaultfd_ctx *ctx,
  626. struct userfaultfd_wake_range *range)
  627. {
  628. unsigned long start, end;
  629. start = range->start;
  630. end = range->start + range->len;
  631. spin_lock(&ctx->fault_pending_wqh.lock);
  632. /* wake all in the range and autoremove */
  633. if (waitqueue_active(&ctx->fault_pending_wqh))
  634. __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
  635. range);
  636. if (waitqueue_active(&ctx->fault_wqh))
  637. __wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
  638. spin_unlock(&ctx->fault_pending_wqh.lock);
  639. }
  640. static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
  641. struct userfaultfd_wake_range *range)
  642. {
  643. unsigned seq;
  644. bool need_wakeup;
  645. /*
  646. * To be sure waitqueue_active() is not reordered by the CPU
  647. * before the pagetable update, use an explicit SMP memory
  648. * barrier here. PT lock release or up_read(mmap_sem) still
  649. * have release semantics that can allow the
  650. * waitqueue_active() to be reordered before the pte update.
  651. */
  652. smp_mb();
  653. /*
  654. * Use waitqueue_active because it's very frequent to
  655. * change the address space atomically even if there are no
  656. * userfaults yet. So we take the spinlock only when we're
  657. * sure we've userfaults to wake.
  658. */
  659. do {
  660. seq = read_seqcount_begin(&ctx->refile_seq);
  661. need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
  662. waitqueue_active(&ctx->fault_wqh);
  663. cond_resched();
  664. } while (read_seqcount_retry(&ctx->refile_seq, seq));
  665. if (need_wakeup)
  666. __wake_userfault(ctx, range);
  667. }
  668. static __always_inline int validate_range(struct mm_struct *mm,
  669. __u64 start, __u64 len)
  670. {
  671. __u64 task_size = mm->task_size;
  672. if (start & ~PAGE_MASK)
  673. return -EINVAL;
  674. if (len & ~PAGE_MASK)
  675. return -EINVAL;
  676. if (!len)
  677. return -EINVAL;
  678. if (start < mmap_min_addr)
  679. return -EINVAL;
  680. if (start >= task_size)
  681. return -EINVAL;
  682. if (len > task_size - start)
  683. return -EINVAL;
  684. return 0;
  685. }
  686. static int userfaultfd_register(struct userfaultfd_ctx *ctx,
  687. unsigned long arg)
  688. {
  689. struct mm_struct *mm = ctx->mm;
  690. struct vm_area_struct *vma, *prev, *cur;
  691. int ret;
  692. struct uffdio_register uffdio_register;
  693. struct uffdio_register __user *user_uffdio_register;
  694. unsigned long vm_flags, new_flags;
  695. bool found;
  696. unsigned long start, end, vma_end;
  697. user_uffdio_register = (struct uffdio_register __user *) arg;
  698. ret = -EFAULT;
  699. if (copy_from_user(&uffdio_register, user_uffdio_register,
  700. sizeof(uffdio_register)-sizeof(__u64)))
  701. goto out;
  702. ret = -EINVAL;
  703. if (!uffdio_register.mode)
  704. goto out;
  705. if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
  706. UFFDIO_REGISTER_MODE_WP))
  707. goto out;
  708. vm_flags = 0;
  709. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
  710. vm_flags |= VM_UFFD_MISSING;
  711. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
  712. vm_flags |= VM_UFFD_WP;
  713. /*
  714. * FIXME: remove the below error constraint by
  715. * implementing the wprotect tracking mode.
  716. */
  717. ret = -EINVAL;
  718. goto out;
  719. }
  720. ret = validate_range(mm, uffdio_register.range.start,
  721. uffdio_register.range.len);
  722. if (ret)
  723. goto out;
  724. start = uffdio_register.range.start;
  725. end = start + uffdio_register.range.len;
  726. ret = -ENOMEM;
  727. if (!mmget_not_zero(mm))
  728. goto out;
  729. down_write(&mm->mmap_sem);
  730. vma = find_vma_prev(mm, start, &prev);
  731. if (!vma)
  732. goto out_unlock;
  733. /* check that there's at least one vma in the range */
  734. ret = -EINVAL;
  735. if (vma->vm_start >= end)
  736. goto out_unlock;
  737. /*
  738. * Search for not compatible vmas.
  739. *
  740. * FIXME: this shall be relaxed later so that it doesn't fail
  741. * on tmpfs backed vmas (in addition to the current allowance
  742. * on anonymous vmas).
  743. */
  744. found = false;
  745. for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
  746. cond_resched();
  747. BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
  748. !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
  749. /* check not compatible vmas */
  750. ret = -EINVAL;
  751. if (cur->vm_ops)
  752. goto out_unlock;
  753. /*
  754. * Check that this vma isn't already owned by a
  755. * different userfaultfd. We can't allow more than one
  756. * userfaultfd to own a single vma simultaneously or we
  757. * wouldn't know which one to deliver the userfaults to.
  758. */
  759. ret = -EBUSY;
  760. if (cur->vm_userfaultfd_ctx.ctx &&
  761. cur->vm_userfaultfd_ctx.ctx != ctx)
  762. goto out_unlock;
  763. found = true;
  764. }
  765. BUG_ON(!found);
  766. if (vma->vm_start < start)
  767. prev = vma;
  768. ret = 0;
  769. do {
  770. cond_resched();
  771. BUG_ON(vma->vm_ops);
  772. BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
  773. vma->vm_userfaultfd_ctx.ctx != ctx);
  774. /*
  775. * Nothing to do: this vma is already registered into this
  776. * userfaultfd and with the right tracking mode too.
  777. */
  778. if (vma->vm_userfaultfd_ctx.ctx == ctx &&
  779. (vma->vm_flags & vm_flags) == vm_flags)
  780. goto skip;
  781. if (vma->vm_start > start)
  782. start = vma->vm_start;
  783. vma_end = min(end, vma->vm_end);
  784. new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
  785. prev = vma_merge(mm, prev, start, vma_end, new_flags,
  786. vma->anon_vma, vma->vm_file, vma->vm_pgoff,
  787. vma_policy(vma),
  788. ((struct vm_userfaultfd_ctx){ ctx }));
  789. if (prev) {
  790. vma = prev;
  791. goto next;
  792. }
  793. if (vma->vm_start < start) {
  794. ret = split_vma(mm, vma, start, 1);
  795. if (ret)
  796. break;
  797. }
  798. if (vma->vm_end > end) {
  799. ret = split_vma(mm, vma, end, 0);
  800. if (ret)
  801. break;
  802. }
  803. next:
  804. /*
  805. * In the vma_merge() successful mprotect-like case 8:
  806. * the next vma was merged into the current one and
  807. * the current one has not been updated yet.
  808. */
  809. vma->vm_flags = new_flags;
  810. vma->vm_userfaultfd_ctx.ctx = ctx;
  811. skip:
  812. prev = vma;
  813. start = vma->vm_end;
  814. vma = vma->vm_next;
  815. } while (vma && vma->vm_start < end);
  816. out_unlock:
  817. up_write(&mm->mmap_sem);
  818. mmput(mm);
  819. if (!ret) {
  820. /*
  821. * Now that we scanned all vmas we can already tell
  822. * userland which ioctls methods are guaranteed to
  823. * succeed on this range.
  824. */
  825. if (put_user(UFFD_API_RANGE_IOCTLS,
  826. &user_uffdio_register->ioctls))
  827. ret = -EFAULT;
  828. }
  829. out:
  830. return ret;
  831. }
  832. static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
  833. unsigned long arg)
  834. {
  835. struct mm_struct *mm = ctx->mm;
  836. struct vm_area_struct *vma, *prev, *cur;
  837. int ret;
  838. struct uffdio_range uffdio_unregister;
  839. unsigned long new_flags;
  840. bool found;
  841. unsigned long start, end, vma_end;
  842. const void __user *buf = (void __user *)arg;
  843. ret = -EFAULT;
  844. if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
  845. goto out;
  846. ret = validate_range(mm, uffdio_unregister.start,
  847. uffdio_unregister.len);
  848. if (ret)
  849. goto out;
  850. start = uffdio_unregister.start;
  851. end = start + uffdio_unregister.len;
  852. ret = -ENOMEM;
  853. if (!mmget_not_zero(mm))
  854. goto out;
  855. down_write(&mm->mmap_sem);
  856. vma = find_vma_prev(mm, start, &prev);
  857. if (!vma)
  858. goto out_unlock;
  859. /* check that there's at least one vma in the range */
  860. ret = -EINVAL;
  861. if (vma->vm_start >= end)
  862. goto out_unlock;
  863. /*
  864. * Search for not compatible vmas.
  865. *
  866. * FIXME: this shall be relaxed later so that it doesn't fail
  867. * on tmpfs backed vmas (in addition to the current allowance
  868. * on anonymous vmas).
  869. */
  870. found = false;
  871. ret = -EINVAL;
  872. for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
  873. cond_resched();
  874. BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
  875. !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
  876. /*
  877. * Check not compatible vmas, not strictly required
  878. * here as not compatible vmas cannot have an
  879. * userfaultfd_ctx registered on them, but this
  880. * provides for more strict behavior to notice
  881. * unregistration errors.
  882. */
  883. if (cur->vm_ops)
  884. goto out_unlock;
  885. found = true;
  886. }
  887. BUG_ON(!found);
  888. if (vma->vm_start < start)
  889. prev = vma;
  890. ret = 0;
  891. do {
  892. cond_resched();
  893. BUG_ON(vma->vm_ops);
  894. /*
  895. * Nothing to do: this vma is already registered into this
  896. * userfaultfd and with the right tracking mode too.
  897. */
  898. if (!vma->vm_userfaultfd_ctx.ctx)
  899. goto skip;
  900. if (vma->vm_start > start)
  901. start = vma->vm_start;
  902. vma_end = min(end, vma->vm_end);
  903. new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
  904. prev = vma_merge(mm, prev, start, vma_end, new_flags,
  905. vma->anon_vma, vma->vm_file, vma->vm_pgoff,
  906. vma_policy(vma),
  907. NULL_VM_UFFD_CTX);
  908. if (prev) {
  909. vma = prev;
  910. goto next;
  911. }
  912. if (vma->vm_start < start) {
  913. ret = split_vma(mm, vma, start, 1);
  914. if (ret)
  915. break;
  916. }
  917. if (vma->vm_end > end) {
  918. ret = split_vma(mm, vma, end, 0);
  919. if (ret)
  920. break;
  921. }
  922. next:
  923. /*
  924. * In the vma_merge() successful mprotect-like case 8:
  925. * the next vma was merged into the current one and
  926. * the current one has not been updated yet.
  927. */
  928. vma->vm_flags = new_flags;
  929. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  930. skip:
  931. prev = vma;
  932. start = vma->vm_end;
  933. vma = vma->vm_next;
  934. } while (vma && vma->vm_start < end);
  935. out_unlock:
  936. up_write(&mm->mmap_sem);
  937. mmput(mm);
  938. out:
  939. return ret;
  940. }
  941. /*
  942. * userfaultfd_wake may be used in combination with the
  943. * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
  944. */
  945. static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
  946. unsigned long arg)
  947. {
  948. int ret;
  949. struct uffdio_range uffdio_wake;
  950. struct userfaultfd_wake_range range;
  951. const void __user *buf = (void __user *)arg;
  952. ret = -EFAULT;
  953. if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
  954. goto out;
  955. ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
  956. if (ret)
  957. goto out;
  958. range.start = uffdio_wake.start;
  959. range.len = uffdio_wake.len;
  960. /*
  961. * len == 0 means wake all and we don't want to wake all here,
  962. * so check it again to be sure.
  963. */
  964. VM_BUG_ON(!range.len);
  965. wake_userfault(ctx, &range);
  966. ret = 0;
  967. out:
  968. return ret;
  969. }
  970. static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
  971. unsigned long arg)
  972. {
  973. __s64 ret;
  974. struct uffdio_copy uffdio_copy;
  975. struct uffdio_copy __user *user_uffdio_copy;
  976. struct userfaultfd_wake_range range;
  977. user_uffdio_copy = (struct uffdio_copy __user *) arg;
  978. ret = -EFAULT;
  979. if (copy_from_user(&uffdio_copy, user_uffdio_copy,
  980. /* don't copy "copy" last field */
  981. sizeof(uffdio_copy)-sizeof(__s64)))
  982. goto out;
  983. ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
  984. if (ret)
  985. goto out;
  986. /*
  987. * double check for wraparound just in case. copy_from_user()
  988. * will later check uffdio_copy.src + uffdio_copy.len to fit
  989. * in the userland range.
  990. */
  991. ret = -EINVAL;
  992. if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
  993. goto out;
  994. if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
  995. goto out;
  996. if (mmget_not_zero(ctx->mm)) {
  997. ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
  998. uffdio_copy.len);
  999. mmput(ctx->mm);
  1000. }
  1001. if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
  1002. return -EFAULT;
  1003. if (ret < 0)
  1004. goto out;
  1005. BUG_ON(!ret);
  1006. /* len == 0 would wake all */
  1007. range.len = ret;
  1008. if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
  1009. range.start = uffdio_copy.dst;
  1010. wake_userfault(ctx, &range);
  1011. }
  1012. ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
  1013. out:
  1014. return ret;
  1015. }
  1016. static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
  1017. unsigned long arg)
  1018. {
  1019. __s64 ret;
  1020. struct uffdio_zeropage uffdio_zeropage;
  1021. struct uffdio_zeropage __user *user_uffdio_zeropage;
  1022. struct userfaultfd_wake_range range;
  1023. user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
  1024. ret = -EFAULT;
  1025. if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
  1026. /* don't copy "zeropage" last field */
  1027. sizeof(uffdio_zeropage)-sizeof(__s64)))
  1028. goto out;
  1029. ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
  1030. uffdio_zeropage.range.len);
  1031. if (ret)
  1032. goto out;
  1033. ret = -EINVAL;
  1034. if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
  1035. goto out;
  1036. if (mmget_not_zero(ctx->mm)) {
  1037. ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
  1038. uffdio_zeropage.range.len);
  1039. mmput(ctx->mm);
  1040. }
  1041. if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
  1042. return -EFAULT;
  1043. if (ret < 0)
  1044. goto out;
  1045. /* len == 0 would wake all */
  1046. BUG_ON(!ret);
  1047. range.len = ret;
  1048. if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
  1049. range.start = uffdio_zeropage.range.start;
  1050. wake_userfault(ctx, &range);
  1051. }
  1052. ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
  1053. out:
  1054. return ret;
  1055. }
  1056. /*
  1057. * userland asks for a certain API version and we return which bits
  1058. * and ioctl commands are implemented in this kernel for such API
  1059. * version or -EINVAL if unknown.
  1060. */
  1061. static int userfaultfd_api(struct userfaultfd_ctx *ctx,
  1062. unsigned long arg)
  1063. {
  1064. struct uffdio_api uffdio_api;
  1065. void __user *buf = (void __user *)arg;
  1066. int ret;
  1067. ret = -EINVAL;
  1068. if (ctx->state != UFFD_STATE_WAIT_API)
  1069. goto out;
  1070. ret = -EFAULT;
  1071. if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
  1072. goto out;
  1073. if (uffdio_api.api != UFFD_API || uffdio_api.features) {
  1074. memset(&uffdio_api, 0, sizeof(uffdio_api));
  1075. if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
  1076. goto out;
  1077. ret = -EINVAL;
  1078. goto out;
  1079. }
  1080. uffdio_api.features = UFFD_API_FEATURES;
  1081. uffdio_api.ioctls = UFFD_API_IOCTLS;
  1082. ret = -EFAULT;
  1083. if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
  1084. goto out;
  1085. ctx->state = UFFD_STATE_RUNNING;
  1086. ret = 0;
  1087. out:
  1088. return ret;
  1089. }
  1090. static long userfaultfd_ioctl(struct file *file, unsigned cmd,
  1091. unsigned long arg)
  1092. {
  1093. int ret = -EINVAL;
  1094. struct userfaultfd_ctx *ctx = file->private_data;
  1095. if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
  1096. return -EINVAL;
  1097. switch(cmd) {
  1098. case UFFDIO_API:
  1099. ret = userfaultfd_api(ctx, arg);
  1100. break;
  1101. case UFFDIO_REGISTER:
  1102. ret = userfaultfd_register(ctx, arg);
  1103. break;
  1104. case UFFDIO_UNREGISTER:
  1105. ret = userfaultfd_unregister(ctx, arg);
  1106. break;
  1107. case UFFDIO_WAKE:
  1108. ret = userfaultfd_wake(ctx, arg);
  1109. break;
  1110. case UFFDIO_COPY:
  1111. ret = userfaultfd_copy(ctx, arg);
  1112. break;
  1113. case UFFDIO_ZEROPAGE:
  1114. ret = userfaultfd_zeropage(ctx, arg);
  1115. break;
  1116. }
  1117. return ret;
  1118. }
  1119. #ifdef CONFIG_PROC_FS
  1120. static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
  1121. {
  1122. struct userfaultfd_ctx *ctx = f->private_data;
  1123. wait_queue_t *wq;
  1124. struct userfaultfd_wait_queue *uwq;
  1125. unsigned long pending = 0, total = 0;
  1126. spin_lock(&ctx->fault_pending_wqh.lock);
  1127. list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
  1128. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  1129. pending++;
  1130. total++;
  1131. }
  1132. list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
  1133. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  1134. total++;
  1135. }
  1136. spin_unlock(&ctx->fault_pending_wqh.lock);
  1137. /*
  1138. * If more protocols will be added, there will be all shown
  1139. * separated by a space. Like this:
  1140. * protocols: aa:... bb:...
  1141. */
  1142. seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
  1143. pending, total, UFFD_API, UFFD_API_FEATURES,
  1144. UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
  1145. }
  1146. #endif
  1147. static const struct file_operations userfaultfd_fops = {
  1148. #ifdef CONFIG_PROC_FS
  1149. .show_fdinfo = userfaultfd_show_fdinfo,
  1150. #endif
  1151. .release = userfaultfd_release,
  1152. .poll = userfaultfd_poll,
  1153. .read = userfaultfd_read,
  1154. .unlocked_ioctl = userfaultfd_ioctl,
  1155. .compat_ioctl = userfaultfd_ioctl,
  1156. .llseek = noop_llseek,
  1157. };
  1158. static void init_once_userfaultfd_ctx(void *mem)
  1159. {
  1160. struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
  1161. init_waitqueue_head(&ctx->fault_pending_wqh);
  1162. init_waitqueue_head(&ctx->fault_wqh);
  1163. init_waitqueue_head(&ctx->fd_wqh);
  1164. seqcount_init(&ctx->refile_seq);
  1165. }
  1166. /**
  1167. * userfaultfd_file_create - Creates an userfaultfd file pointer.
  1168. * @flags: Flags for the userfaultfd file.
  1169. *
  1170. * This function creates an userfaultfd file pointer, w/out installing
  1171. * it into the fd table. This is useful when the userfaultfd file is
  1172. * used during the initialization of data structures that require
  1173. * extra setup after the userfaultfd creation. So the userfaultfd
  1174. * creation is split into the file pointer creation phase, and the
  1175. * file descriptor installation phase. In this way races with
  1176. * userspace closing the newly installed file descriptor can be
  1177. * avoided. Returns an userfaultfd file pointer, or a proper error
  1178. * pointer.
  1179. */
  1180. static struct file *userfaultfd_file_create(int flags)
  1181. {
  1182. struct file *file;
  1183. struct userfaultfd_ctx *ctx;
  1184. BUG_ON(!current->mm);
  1185. /* Check the UFFD_* constants for consistency. */
  1186. BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
  1187. BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
  1188. file = ERR_PTR(-EINVAL);
  1189. if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
  1190. goto out;
  1191. file = ERR_PTR(-ENOMEM);
  1192. ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
  1193. if (!ctx)
  1194. goto out;
  1195. atomic_set(&ctx->refcount, 1);
  1196. ctx->flags = flags;
  1197. ctx->state = UFFD_STATE_WAIT_API;
  1198. ctx->released = false;
  1199. ctx->mm = current->mm;
  1200. /* prevent the mm struct to be freed */
  1201. atomic_inc(&ctx->mm->mm_count);
  1202. file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
  1203. O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
  1204. if (IS_ERR(file)) {
  1205. mmdrop(ctx->mm);
  1206. kmem_cache_free(userfaultfd_ctx_cachep, ctx);
  1207. }
  1208. out:
  1209. return file;
  1210. }
  1211. SYSCALL_DEFINE1(userfaultfd, int, flags)
  1212. {
  1213. int fd, error;
  1214. struct file *file;
  1215. error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
  1216. if (error < 0)
  1217. return error;
  1218. fd = error;
  1219. file = userfaultfd_file_create(flags);
  1220. if (IS_ERR(file)) {
  1221. error = PTR_ERR(file);
  1222. goto err_put_unused_fd;
  1223. }
  1224. fd_install(fd, file);
  1225. return fd;
  1226. err_put_unused_fd:
  1227. put_unused_fd(fd);
  1228. return error;
  1229. }
  1230. static int __init userfaultfd_init(void)
  1231. {
  1232. userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
  1233. sizeof(struct userfaultfd_ctx),
  1234. 0,
  1235. SLAB_HWCACHE_ALIGN|SLAB_PANIC,
  1236. init_once_userfaultfd_ctx);
  1237. return 0;
  1238. }
  1239. __initcall(userfaultfd_init);