userfaultfd.c 36 KB

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