userfaultfd.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * fs/userfaultfd.c
  4. *
  5. * Copyright (C) 2007 Davide Libenzi <[email protected]>
  6. * Copyright (C) 2008-2009 Red Hat, Inc.
  7. * Copyright (C) 2015 Red Hat, Inc.
  8. *
  9. * Some part derived from fs/eventfd.c (anon inode setup) and
  10. * mm/ksm.c (mm hashing).
  11. */
  12. #include <linux/list.h>
  13. #include <linux/hashtable.h>
  14. #include <linux/sched/signal.h>
  15. #include <linux/sched/mm.h>
  16. #include <linux/mm.h>
  17. #include <linux/mm_inline.h>
  18. #include <linux/mmu_notifier.h>
  19. #include <linux/poll.h>
  20. #include <linux/slab.h>
  21. #include <linux/seq_file.h>
  22. #include <linux/file.h>
  23. #include <linux/bug.h>
  24. #include <linux/anon_inodes.h>
  25. #include <linux/syscalls.h>
  26. #include <linux/userfaultfd_k.h>
  27. #include <linux/mempolicy.h>
  28. #include <linux/ioctl.h>
  29. #include <linux/security.h>
  30. #include <linux/hugetlb.h>
  31. #include <linux/swapops.h>
  32. #include <linux/miscdevice.h>
  33. int sysctl_unprivileged_userfaultfd __read_mostly;
  34. static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
  35. /*
  36. * Start with fault_pending_wqh and fault_wqh so they're more likely
  37. * to be in the same cacheline.
  38. *
  39. * Locking order:
  40. * fd_wqh.lock
  41. * fault_pending_wqh.lock
  42. * fault_wqh.lock
  43. * event_wqh.lock
  44. *
  45. * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
  46. * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
  47. * also taken in IRQ context.
  48. */
  49. struct userfaultfd_ctx {
  50. /* waitqueue head for the pending (i.e. not read) userfaults */
  51. wait_queue_head_t fault_pending_wqh;
  52. /* waitqueue head for the userfaults */
  53. wait_queue_head_t fault_wqh;
  54. /* waitqueue head for the pseudo fd to wakeup poll/read */
  55. wait_queue_head_t fd_wqh;
  56. /* waitqueue head for events */
  57. wait_queue_head_t event_wqh;
  58. /* a refile sequence protected by fault_pending_wqh lock */
  59. seqcount_spinlock_t refile_seq;
  60. /* pseudo fd refcounting */
  61. refcount_t refcount;
  62. /* userfaultfd syscall flags */
  63. unsigned int flags;
  64. /* features requested from the userspace */
  65. unsigned int features;
  66. /* released */
  67. bool released;
  68. /* memory mappings are changing because of non-cooperative event */
  69. atomic_t mmap_changing;
  70. /* mm with one ore more vmas attached to this userfaultfd_ctx */
  71. struct mm_struct *mm;
  72. };
  73. struct userfaultfd_fork_ctx {
  74. struct userfaultfd_ctx *orig;
  75. struct userfaultfd_ctx *new;
  76. struct list_head list;
  77. };
  78. struct userfaultfd_unmap_ctx {
  79. struct userfaultfd_ctx *ctx;
  80. unsigned long start;
  81. unsigned long end;
  82. struct list_head list;
  83. };
  84. struct userfaultfd_wait_queue {
  85. struct uffd_msg msg;
  86. wait_queue_entry_t wq;
  87. struct userfaultfd_ctx *ctx;
  88. bool waken;
  89. };
  90. struct userfaultfd_wake_range {
  91. unsigned long start;
  92. unsigned long len;
  93. };
  94. /* internal indication that UFFD_API ioctl was successfully executed */
  95. #define UFFD_FEATURE_INITIALIZED (1u << 31)
  96. static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
  97. {
  98. return ctx->features & UFFD_FEATURE_INITIALIZED;
  99. }
  100. static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
  101. vm_flags_t flags)
  102. {
  103. const bool uffd_wp_changed = (vma->vm_flags ^ flags) & VM_UFFD_WP;
  104. vm_flags_reset(vma, flags);
  105. /*
  106. * For shared mappings, we want to enable writenotify while
  107. * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
  108. * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
  109. */
  110. if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
  111. vma_set_page_prot(vma);
  112. }
  113. static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
  114. int wake_flags, void *key)
  115. {
  116. struct userfaultfd_wake_range *range = key;
  117. int ret;
  118. struct userfaultfd_wait_queue *uwq;
  119. unsigned long start, len;
  120. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  121. ret = 0;
  122. /* len == 0 means wake all */
  123. start = range->start;
  124. len = range->len;
  125. if (len && (start > uwq->msg.arg.pagefault.address ||
  126. start + len <= uwq->msg.arg.pagefault.address))
  127. goto out;
  128. WRITE_ONCE(uwq->waken, true);
  129. /*
  130. * The Program-Order guarantees provided by the scheduler
  131. * ensure uwq->waken is visible before the task is woken.
  132. */
  133. ret = wake_up_state(wq->private, mode);
  134. if (ret) {
  135. /*
  136. * Wake only once, autoremove behavior.
  137. *
  138. * After the effect of list_del_init is visible to the other
  139. * CPUs, the waitqueue may disappear from under us, see the
  140. * !list_empty_careful() in handle_userfault().
  141. *
  142. * try_to_wake_up() has an implicit smp_mb(), and the
  143. * wq->private is read before calling the extern function
  144. * "wake_up_state" (which in turns calls try_to_wake_up).
  145. */
  146. list_del_init(&wq->entry);
  147. }
  148. out:
  149. return ret;
  150. }
  151. /**
  152. * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
  153. * context.
  154. * @ctx: [in] Pointer to the userfaultfd context.
  155. */
  156. static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
  157. {
  158. refcount_inc(&ctx->refcount);
  159. }
  160. /**
  161. * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
  162. * context.
  163. * @ctx: [in] Pointer to userfaultfd context.
  164. *
  165. * The userfaultfd context reference must have been previously acquired either
  166. * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
  167. */
  168. static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
  169. {
  170. if (refcount_dec_and_test(&ctx->refcount)) {
  171. VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
  172. VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
  173. VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
  174. VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
  175. VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
  176. VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
  177. VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
  178. VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
  179. mmdrop(ctx->mm);
  180. kmem_cache_free(userfaultfd_ctx_cachep, ctx);
  181. }
  182. }
  183. static inline void msg_init(struct uffd_msg *msg)
  184. {
  185. BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
  186. /*
  187. * Must use memset to zero out the paddings or kernel data is
  188. * leaked to userland.
  189. */
  190. memset(msg, 0, sizeof(struct uffd_msg));
  191. }
  192. static inline struct uffd_msg userfault_msg(unsigned long address,
  193. unsigned long real_address,
  194. unsigned int flags,
  195. unsigned long reason,
  196. unsigned int features)
  197. {
  198. struct uffd_msg msg;
  199. msg_init(&msg);
  200. msg.event = UFFD_EVENT_PAGEFAULT;
  201. msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
  202. real_address : address;
  203. /*
  204. * These flags indicate why the userfault occurred:
  205. * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
  206. * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
  207. * - Neither of these flags being set indicates a MISSING fault.
  208. *
  209. * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
  210. * fault. Otherwise, it was a read fault.
  211. */
  212. if (flags & FAULT_FLAG_WRITE)
  213. msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
  214. if (reason & VM_UFFD_WP)
  215. msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
  216. if (reason & VM_UFFD_MINOR)
  217. msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
  218. if (features & UFFD_FEATURE_THREAD_ID)
  219. msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
  220. return msg;
  221. }
  222. #ifdef CONFIG_HUGETLB_PAGE
  223. /*
  224. * Same functionality as userfaultfd_must_wait below with modifications for
  225. * hugepmd ranges.
  226. */
  227. static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
  228. struct vm_fault *vmf,
  229. unsigned long reason)
  230. {
  231. struct vm_area_struct *vma = vmf->vma;
  232. struct mm_struct *mm = ctx->mm;
  233. pte_t *ptep, pte;
  234. bool ret = true;
  235. assert_fault_locked(vmf);
  236. ptep = huge_pte_offset(mm, vmf->address, vma_mmu_pagesize(vma));
  237. if (!ptep)
  238. goto out;
  239. ret = false;
  240. pte = huge_ptep_get(ptep);
  241. /*
  242. * Lockless access: we're in a wait_event so it's ok if it
  243. * changes under us. PTE markers should be handled the same as none
  244. * ptes here.
  245. */
  246. if (huge_pte_none_mostly(pte))
  247. ret = true;
  248. if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
  249. ret = true;
  250. out:
  251. return ret;
  252. }
  253. #else
  254. static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
  255. struct vm_fault *vmf,
  256. unsigned long reason)
  257. {
  258. return false; /* should never get here */
  259. }
  260. #endif /* CONFIG_HUGETLB_PAGE */
  261. /*
  262. * Verify the pagetables are still not ok after having reigstered into
  263. * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
  264. * userfault that has already been resolved, if userfaultfd_read and
  265. * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
  266. * threads.
  267. */
  268. static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
  269. struct vm_fault *vmf,
  270. unsigned long reason)
  271. {
  272. struct mm_struct *mm = ctx->mm;
  273. unsigned long address = vmf->address;
  274. pgd_t *pgd;
  275. p4d_t *p4d;
  276. pud_t *pud;
  277. pmd_t *pmd, _pmd;
  278. pte_t *pte;
  279. bool ret = true;
  280. assert_fault_locked(vmf);
  281. pgd = pgd_offset(mm, address);
  282. if (!pgd_present(*pgd))
  283. goto out;
  284. p4d = p4d_offset(pgd, address);
  285. if (!p4d_present(*p4d))
  286. goto out;
  287. pud = pud_offset(p4d, address);
  288. if (!pud_present(*pud))
  289. goto out;
  290. pmd = pmd_offset(pud, address);
  291. /*
  292. * READ_ONCE must function as a barrier with narrower scope
  293. * and it must be equivalent to:
  294. * _pmd = *pmd; barrier();
  295. *
  296. * This is to deal with the instability (as in
  297. * pmd_trans_unstable) of the pmd.
  298. */
  299. _pmd = READ_ONCE(*pmd);
  300. if (pmd_none(_pmd))
  301. goto out;
  302. ret = false;
  303. if (!pmd_present(_pmd))
  304. goto out;
  305. if (pmd_trans_huge(_pmd)) {
  306. if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
  307. ret = true;
  308. goto out;
  309. }
  310. /*
  311. * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
  312. * and use the standard pte_offset_map() instead of parsing _pmd.
  313. */
  314. pte = pte_offset_map(pmd, address);
  315. /*
  316. * Lockless access: we're in a wait_event so it's ok if it
  317. * changes under us. PTE markers should be handled the same as none
  318. * ptes here.
  319. */
  320. if (pte_none_mostly(*pte))
  321. ret = true;
  322. if (!pte_write(*pte) && (reason & VM_UFFD_WP))
  323. ret = true;
  324. pte_unmap(pte);
  325. out:
  326. return ret;
  327. }
  328. static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
  329. {
  330. if (flags & FAULT_FLAG_INTERRUPTIBLE)
  331. return TASK_INTERRUPTIBLE;
  332. if (flags & FAULT_FLAG_KILLABLE)
  333. return TASK_KILLABLE;
  334. return TASK_UNINTERRUPTIBLE;
  335. }
  336. /*
  337. * The locking rules involved in returning VM_FAULT_RETRY depending on
  338. * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
  339. * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
  340. * recommendation in __lock_page_or_retry is not an understatement.
  341. *
  342. * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
  343. * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
  344. * not set.
  345. *
  346. * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
  347. * set, VM_FAULT_RETRY can still be returned if and only if there are
  348. * fatal_signal_pending()s, and the mmap_lock must be released before
  349. * returning it.
  350. */
  351. vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
  352. {
  353. struct mm_struct *mm = vmf->vma->vm_mm;
  354. struct userfaultfd_ctx *ctx;
  355. struct userfaultfd_wait_queue uwq;
  356. vm_fault_t ret = VM_FAULT_SIGBUS;
  357. bool must_wait;
  358. unsigned int blocking_state;
  359. /*
  360. * We don't do userfault handling for the final child pid update.
  361. *
  362. * We also don't do userfault handling during
  363. * coredumping. hugetlbfs has the special
  364. * follow_hugetlb_page() to skip missing pages in the
  365. * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
  366. * the no_page_table() helper in follow_page_mask(), but the
  367. * shmem_vm_ops->fault method is invoked even during
  368. * coredumping without mmap_lock and it ends up here.
  369. */
  370. if (current->flags & (PF_EXITING|PF_DUMPCORE))
  371. goto out;
  372. /*
  373. * Coredumping runs without mmap_lock so we can only check that
  374. * the mmap_lock is held, if PF_DUMPCORE was not set.
  375. */
  376. assert_fault_locked(vmf);
  377. ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
  378. if (!ctx)
  379. goto out;
  380. BUG_ON(ctx->mm != mm);
  381. /* Any unrecognized flag is a bug. */
  382. VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
  383. /* 0 or > 1 flags set is a bug; we expect exactly 1. */
  384. VM_BUG_ON(!reason || (reason & (reason - 1)));
  385. if (ctx->features & UFFD_FEATURE_SIGBUS)
  386. goto out;
  387. if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
  388. goto out;
  389. /*
  390. * If it's already released don't get it. This avoids to loop
  391. * in __get_user_pages if userfaultfd_release waits on the
  392. * caller of handle_userfault to release the mmap_lock.
  393. */
  394. if (unlikely(READ_ONCE(ctx->released))) {
  395. /*
  396. * Don't return VM_FAULT_SIGBUS in this case, so a non
  397. * cooperative manager can close the uffd after the
  398. * last UFFDIO_COPY, without risking to trigger an
  399. * involuntary SIGBUS if the process was starting the
  400. * userfaultfd while the userfaultfd was still armed
  401. * (but after the last UFFDIO_COPY). If the uffd
  402. * wasn't already closed when the userfault reached
  403. * this point, that would normally be solved by
  404. * userfaultfd_must_wait returning 'false'.
  405. *
  406. * If we were to return VM_FAULT_SIGBUS here, the non
  407. * cooperative manager would be instead forced to
  408. * always call UFFDIO_UNREGISTER before it can safely
  409. * close the uffd.
  410. */
  411. ret = VM_FAULT_NOPAGE;
  412. goto out;
  413. }
  414. /*
  415. * Check that we can return VM_FAULT_RETRY.
  416. *
  417. * NOTE: it should become possible to return VM_FAULT_RETRY
  418. * even if FAULT_FLAG_TRIED is set without leading to gup()
  419. * -EBUSY failures, if the userfaultfd is to be extended for
  420. * VM_UFFD_WP tracking and we intend to arm the userfault
  421. * without first stopping userland access to the memory. For
  422. * VM_UFFD_MISSING userfaults this is enough for now.
  423. */
  424. if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
  425. /*
  426. * Validate the invariant that nowait must allow retry
  427. * to be sure not to return SIGBUS erroneously on
  428. * nowait invocations.
  429. */
  430. BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
  431. #ifdef CONFIG_DEBUG_VM
  432. if (printk_ratelimit()) {
  433. printk(KERN_WARNING
  434. "FAULT_FLAG_ALLOW_RETRY missing %x\n",
  435. vmf->flags);
  436. dump_stack();
  437. }
  438. #endif
  439. goto out;
  440. }
  441. /*
  442. * Handle nowait, not much to do other than tell it to retry
  443. * and wait.
  444. */
  445. ret = VM_FAULT_RETRY;
  446. if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
  447. goto out;
  448. /* take the reference before dropping the mmap_lock */
  449. userfaultfd_ctx_get(ctx);
  450. init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
  451. uwq.wq.private = current;
  452. uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
  453. reason, ctx->features);
  454. uwq.ctx = ctx;
  455. uwq.waken = false;
  456. blocking_state = userfaultfd_get_blocking_state(vmf->flags);
  457. spin_lock_irq(&ctx->fault_pending_wqh.lock);
  458. /*
  459. * After the __add_wait_queue the uwq is visible to userland
  460. * through poll/read().
  461. */
  462. __add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
  463. /*
  464. * The smp_mb() after __set_current_state prevents the reads
  465. * following the spin_unlock to happen before the list_add in
  466. * __add_wait_queue.
  467. */
  468. set_current_state(blocking_state);
  469. spin_unlock_irq(&ctx->fault_pending_wqh.lock);
  470. if (!is_vm_hugetlb_page(vmf->vma))
  471. must_wait = userfaultfd_must_wait(ctx, vmf, reason);
  472. else
  473. must_wait = userfaultfd_huge_must_wait(ctx, vmf, reason);
  474. release_fault_lock(vmf);
  475. if (likely(must_wait && !READ_ONCE(ctx->released))) {
  476. wake_up_poll(&ctx->fd_wqh, EPOLLIN);
  477. schedule();
  478. }
  479. __set_current_state(TASK_RUNNING);
  480. /*
  481. * Here we race with the list_del; list_add in
  482. * userfaultfd_ctx_read(), however because we don't ever run
  483. * list_del_init() to refile across the two lists, the prev
  484. * and next pointers will never point to self. list_add also
  485. * would never let any of the two pointers to point to
  486. * self. So list_empty_careful won't risk to see both pointers
  487. * pointing to self at any time during the list refile. The
  488. * only case where list_del_init() is called is the full
  489. * removal in the wake function and there we don't re-list_add
  490. * and it's fine not to block on the spinlock. The uwq on this
  491. * kernel stack can be released after the list_del_init.
  492. */
  493. if (!list_empty_careful(&uwq.wq.entry)) {
  494. spin_lock_irq(&ctx->fault_pending_wqh.lock);
  495. /*
  496. * No need of list_del_init(), the uwq on the stack
  497. * will be freed shortly anyway.
  498. */
  499. list_del(&uwq.wq.entry);
  500. spin_unlock_irq(&ctx->fault_pending_wqh.lock);
  501. }
  502. /*
  503. * ctx may go away after this if the userfault pseudo fd is
  504. * already released.
  505. */
  506. userfaultfd_ctx_put(ctx);
  507. out:
  508. return ret;
  509. }
  510. static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
  511. struct userfaultfd_wait_queue *ewq)
  512. {
  513. struct userfaultfd_ctx *release_new_ctx;
  514. if (WARN_ON_ONCE(current->flags & PF_EXITING))
  515. goto out;
  516. ewq->ctx = ctx;
  517. init_waitqueue_entry(&ewq->wq, current);
  518. release_new_ctx = NULL;
  519. spin_lock_irq(&ctx->event_wqh.lock);
  520. /*
  521. * After the __add_wait_queue the uwq is visible to userland
  522. * through poll/read().
  523. */
  524. __add_wait_queue(&ctx->event_wqh, &ewq->wq);
  525. for (;;) {
  526. set_current_state(TASK_KILLABLE);
  527. if (ewq->msg.event == 0)
  528. break;
  529. if (READ_ONCE(ctx->released) ||
  530. fatal_signal_pending(current)) {
  531. /*
  532. * &ewq->wq may be queued in fork_event, but
  533. * __remove_wait_queue ignores the head
  534. * parameter. It would be a problem if it
  535. * didn't.
  536. */
  537. __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
  538. if (ewq->msg.event == UFFD_EVENT_FORK) {
  539. struct userfaultfd_ctx *new;
  540. new = (struct userfaultfd_ctx *)
  541. (unsigned long)
  542. ewq->msg.arg.reserved.reserved1;
  543. release_new_ctx = new;
  544. }
  545. break;
  546. }
  547. spin_unlock_irq(&ctx->event_wqh.lock);
  548. wake_up_poll(&ctx->fd_wqh, EPOLLIN);
  549. schedule();
  550. spin_lock_irq(&ctx->event_wqh.lock);
  551. }
  552. __set_current_state(TASK_RUNNING);
  553. spin_unlock_irq(&ctx->event_wqh.lock);
  554. if (release_new_ctx) {
  555. struct vm_area_struct *vma;
  556. struct mm_struct *mm = release_new_ctx->mm;
  557. VMA_ITERATOR(vmi, mm, 0);
  558. /* the various vma->vm_userfaultfd_ctx still points to it */
  559. mmap_write_lock(mm);
  560. for_each_vma(vmi, vma) {
  561. if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
  562. vma_start_write(vma);
  563. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  564. userfaultfd_set_vm_flags(vma,
  565. vma->vm_flags & ~__VM_UFFD_FLAGS);
  566. }
  567. }
  568. mmap_write_unlock(mm);
  569. userfaultfd_ctx_put(release_new_ctx);
  570. }
  571. /*
  572. * ctx may go away after this if the userfault pseudo fd is
  573. * already released.
  574. */
  575. out:
  576. atomic_dec(&ctx->mmap_changing);
  577. VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
  578. userfaultfd_ctx_put(ctx);
  579. }
  580. static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
  581. struct userfaultfd_wait_queue *ewq)
  582. {
  583. ewq->msg.event = 0;
  584. wake_up_locked(&ctx->event_wqh);
  585. __remove_wait_queue(&ctx->event_wqh, &ewq->wq);
  586. }
  587. int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
  588. {
  589. struct userfaultfd_ctx *ctx = NULL, *octx;
  590. struct userfaultfd_fork_ctx *fctx;
  591. octx = vma->vm_userfaultfd_ctx.ctx;
  592. if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
  593. vma_start_write(vma);
  594. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  595. userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
  596. return 0;
  597. }
  598. list_for_each_entry(fctx, fcs, list)
  599. if (fctx->orig == octx) {
  600. ctx = fctx->new;
  601. break;
  602. }
  603. if (!ctx) {
  604. fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
  605. if (!fctx)
  606. return -ENOMEM;
  607. ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
  608. if (!ctx) {
  609. kfree(fctx);
  610. return -ENOMEM;
  611. }
  612. refcount_set(&ctx->refcount, 1);
  613. ctx->flags = octx->flags;
  614. ctx->features = octx->features;
  615. ctx->released = false;
  616. atomic_set(&ctx->mmap_changing, 0);
  617. ctx->mm = vma->vm_mm;
  618. mmgrab(ctx->mm);
  619. userfaultfd_ctx_get(octx);
  620. atomic_inc(&octx->mmap_changing);
  621. fctx->orig = octx;
  622. fctx->new = ctx;
  623. list_add_tail(&fctx->list, fcs);
  624. }
  625. vma->vm_userfaultfd_ctx.ctx = ctx;
  626. return 0;
  627. }
  628. static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
  629. {
  630. struct userfaultfd_ctx *ctx = fctx->orig;
  631. struct userfaultfd_wait_queue ewq;
  632. msg_init(&ewq.msg);
  633. ewq.msg.event = UFFD_EVENT_FORK;
  634. ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
  635. userfaultfd_event_wait_completion(ctx, &ewq);
  636. }
  637. void dup_userfaultfd_complete(struct list_head *fcs)
  638. {
  639. struct userfaultfd_fork_ctx *fctx, *n;
  640. list_for_each_entry_safe(fctx, n, fcs, list) {
  641. dup_fctx(fctx);
  642. list_del(&fctx->list);
  643. kfree(fctx);
  644. }
  645. }
  646. void mremap_userfaultfd_prep(struct vm_area_struct *vma,
  647. struct vm_userfaultfd_ctx *vm_ctx)
  648. {
  649. struct userfaultfd_ctx *ctx;
  650. ctx = vma->vm_userfaultfd_ctx.ctx;
  651. if (!ctx)
  652. return;
  653. if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
  654. vm_ctx->ctx = ctx;
  655. userfaultfd_ctx_get(ctx);
  656. atomic_inc(&ctx->mmap_changing);
  657. } else {
  658. /* Drop uffd context if remap feature not enabled */
  659. vma_start_write(vma);
  660. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  661. userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
  662. }
  663. }
  664. void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
  665. unsigned long from, unsigned long to,
  666. unsigned long len)
  667. {
  668. struct userfaultfd_ctx *ctx = vm_ctx->ctx;
  669. struct userfaultfd_wait_queue ewq;
  670. if (!ctx)
  671. return;
  672. if (to & ~PAGE_MASK) {
  673. userfaultfd_ctx_put(ctx);
  674. return;
  675. }
  676. msg_init(&ewq.msg);
  677. ewq.msg.event = UFFD_EVENT_REMAP;
  678. ewq.msg.arg.remap.from = from;
  679. ewq.msg.arg.remap.to = to;
  680. ewq.msg.arg.remap.len = len;
  681. userfaultfd_event_wait_completion(ctx, &ewq);
  682. }
  683. bool userfaultfd_remove(struct vm_area_struct *vma,
  684. unsigned long start, unsigned long end)
  685. {
  686. struct mm_struct *mm = vma->vm_mm;
  687. struct userfaultfd_ctx *ctx;
  688. struct userfaultfd_wait_queue ewq;
  689. ctx = vma->vm_userfaultfd_ctx.ctx;
  690. if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
  691. return true;
  692. userfaultfd_ctx_get(ctx);
  693. atomic_inc(&ctx->mmap_changing);
  694. mmap_read_unlock(mm);
  695. msg_init(&ewq.msg);
  696. ewq.msg.event = UFFD_EVENT_REMOVE;
  697. ewq.msg.arg.remove.start = start;
  698. ewq.msg.arg.remove.end = end;
  699. userfaultfd_event_wait_completion(ctx, &ewq);
  700. return false;
  701. }
  702. static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
  703. unsigned long start, unsigned long end)
  704. {
  705. struct userfaultfd_unmap_ctx *unmap_ctx;
  706. list_for_each_entry(unmap_ctx, unmaps, list)
  707. if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
  708. unmap_ctx->end == end)
  709. return true;
  710. return false;
  711. }
  712. int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start,
  713. unsigned long end, struct list_head *unmaps)
  714. {
  715. struct userfaultfd_unmap_ctx *unmap_ctx;
  716. struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
  717. if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
  718. has_unmap_ctx(ctx, unmaps, start, end))
  719. return 0;
  720. unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
  721. if (!unmap_ctx)
  722. return -ENOMEM;
  723. userfaultfd_ctx_get(ctx);
  724. atomic_inc(&ctx->mmap_changing);
  725. unmap_ctx->ctx = ctx;
  726. unmap_ctx->start = start;
  727. unmap_ctx->end = end;
  728. list_add_tail(&unmap_ctx->list, unmaps);
  729. return 0;
  730. }
  731. void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
  732. {
  733. struct userfaultfd_unmap_ctx *ctx, *n;
  734. struct userfaultfd_wait_queue ewq;
  735. list_for_each_entry_safe(ctx, n, uf, list) {
  736. msg_init(&ewq.msg);
  737. ewq.msg.event = UFFD_EVENT_UNMAP;
  738. ewq.msg.arg.remove.start = ctx->start;
  739. ewq.msg.arg.remove.end = ctx->end;
  740. userfaultfd_event_wait_completion(ctx->ctx, &ewq);
  741. list_del(&ctx->list);
  742. kfree(ctx);
  743. }
  744. }
  745. static int userfaultfd_release(struct inode *inode, struct file *file)
  746. {
  747. struct userfaultfd_ctx *ctx = file->private_data;
  748. struct mm_struct *mm = ctx->mm;
  749. struct vm_area_struct *vma, *prev;
  750. /* len == 0 means wake all */
  751. struct userfaultfd_wake_range range = { .len = 0, };
  752. unsigned long new_flags;
  753. MA_STATE(mas, &mm->mm_mt, 0, 0);
  754. WRITE_ONCE(ctx->released, true);
  755. if (!mmget_not_zero(mm))
  756. goto wakeup;
  757. /*
  758. * Flush page faults out of all CPUs. NOTE: all page faults
  759. * must be retried without returning VM_FAULT_SIGBUS if
  760. * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
  761. * changes while handle_userfault released the mmap_lock. So
  762. * it's critical that released is set to true (above), before
  763. * taking the mmap_lock for writing.
  764. */
  765. mmap_write_lock(mm);
  766. prev = NULL;
  767. mas_for_each(&mas, vma, ULONG_MAX) {
  768. cond_resched();
  769. BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
  770. !!(vma->vm_flags & __VM_UFFD_FLAGS));
  771. if (vma->vm_userfaultfd_ctx.ctx != ctx) {
  772. prev = vma;
  773. continue;
  774. }
  775. new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
  776. prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
  777. new_flags, vma->anon_vma,
  778. vma->vm_file, vma->vm_pgoff,
  779. vma_policy(vma),
  780. NULL_VM_UFFD_CTX, anon_vma_name(vma));
  781. if (prev) {
  782. mas_pause(&mas);
  783. vma = prev;
  784. } else {
  785. prev = vma;
  786. }
  787. vma_start_write(vma);
  788. userfaultfd_set_vm_flags(vma, new_flags);
  789. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  790. }
  791. mmap_write_unlock(mm);
  792. mmput(mm);
  793. wakeup:
  794. /*
  795. * After no new page faults can wait on this fault_*wqh, flush
  796. * the last page faults that may have been already waiting on
  797. * the fault_*wqh.
  798. */
  799. spin_lock_irq(&ctx->fault_pending_wqh.lock);
  800. __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
  801. __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
  802. spin_unlock_irq(&ctx->fault_pending_wqh.lock);
  803. /* Flush pending events that may still wait on event_wqh */
  804. wake_up_all(&ctx->event_wqh);
  805. wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
  806. userfaultfd_ctx_put(ctx);
  807. return 0;
  808. }
  809. /* fault_pending_wqh.lock must be hold by the caller */
  810. static inline struct userfaultfd_wait_queue *find_userfault_in(
  811. wait_queue_head_t *wqh)
  812. {
  813. wait_queue_entry_t *wq;
  814. struct userfaultfd_wait_queue *uwq;
  815. lockdep_assert_held(&wqh->lock);
  816. uwq = NULL;
  817. if (!waitqueue_active(wqh))
  818. goto out;
  819. /* walk in reverse to provide FIFO behavior to read userfaults */
  820. wq = list_last_entry(&wqh->head, typeof(*wq), entry);
  821. uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
  822. out:
  823. return uwq;
  824. }
  825. static inline struct userfaultfd_wait_queue *find_userfault(
  826. struct userfaultfd_ctx *ctx)
  827. {
  828. return find_userfault_in(&ctx->fault_pending_wqh);
  829. }
  830. static inline struct userfaultfd_wait_queue *find_userfault_evt(
  831. struct userfaultfd_ctx *ctx)
  832. {
  833. return find_userfault_in(&ctx->event_wqh);
  834. }
  835. static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
  836. {
  837. struct userfaultfd_ctx *ctx = file->private_data;
  838. __poll_t ret;
  839. poll_wait(file, &ctx->fd_wqh, wait);
  840. if (!userfaultfd_is_initialized(ctx))
  841. return EPOLLERR;
  842. /*
  843. * poll() never guarantees that read won't block.
  844. * userfaults can be waken before they're read().
  845. */
  846. if (unlikely(!(file->f_flags & O_NONBLOCK)))
  847. return EPOLLERR;
  848. /*
  849. * lockless access to see if there are pending faults
  850. * __pollwait last action is the add_wait_queue but
  851. * the spin_unlock would allow the waitqueue_active to
  852. * pass above the actual list_add inside
  853. * add_wait_queue critical section. So use a full
  854. * memory barrier to serialize the list_add write of
  855. * add_wait_queue() with the waitqueue_active read
  856. * below.
  857. */
  858. ret = 0;
  859. smp_mb();
  860. if (waitqueue_active(&ctx->fault_pending_wqh))
  861. ret = EPOLLIN;
  862. else if (waitqueue_active(&ctx->event_wqh))
  863. ret = EPOLLIN;
  864. return ret;
  865. }
  866. static const struct file_operations userfaultfd_fops;
  867. static int resolve_userfault_fork(struct userfaultfd_ctx *new,
  868. struct inode *inode,
  869. struct uffd_msg *msg)
  870. {
  871. int fd;
  872. fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
  873. O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
  874. if (fd < 0)
  875. return fd;
  876. msg->arg.reserved.reserved1 = 0;
  877. msg->arg.fork.ufd = fd;
  878. return 0;
  879. }
  880. static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
  881. struct uffd_msg *msg, struct inode *inode)
  882. {
  883. ssize_t ret;
  884. DECLARE_WAITQUEUE(wait, current);
  885. struct userfaultfd_wait_queue *uwq;
  886. /*
  887. * Handling fork event requires sleeping operations, so
  888. * we drop the event_wqh lock, then do these ops, then
  889. * lock it back and wake up the waiter. While the lock is
  890. * dropped the ewq may go away so we keep track of it
  891. * carefully.
  892. */
  893. LIST_HEAD(fork_event);
  894. struct userfaultfd_ctx *fork_nctx = NULL;
  895. /* always take the fd_wqh lock before the fault_pending_wqh lock */
  896. spin_lock_irq(&ctx->fd_wqh.lock);
  897. __add_wait_queue(&ctx->fd_wqh, &wait);
  898. for (;;) {
  899. set_current_state(TASK_INTERRUPTIBLE);
  900. spin_lock(&ctx->fault_pending_wqh.lock);
  901. uwq = find_userfault(ctx);
  902. if (uwq) {
  903. /*
  904. * Use a seqcount to repeat the lockless check
  905. * in wake_userfault() to avoid missing
  906. * wakeups because during the refile both
  907. * waitqueue could become empty if this is the
  908. * only userfault.
  909. */
  910. write_seqcount_begin(&ctx->refile_seq);
  911. /*
  912. * The fault_pending_wqh.lock prevents the uwq
  913. * to disappear from under us.
  914. *
  915. * Refile this userfault from
  916. * fault_pending_wqh to fault_wqh, it's not
  917. * pending anymore after we read it.
  918. *
  919. * Use list_del() by hand (as
  920. * userfaultfd_wake_function also uses
  921. * list_del_init() by hand) to be sure nobody
  922. * changes __remove_wait_queue() to use
  923. * list_del_init() in turn breaking the
  924. * !list_empty_careful() check in
  925. * handle_userfault(). The uwq->wq.head list
  926. * must never be empty at any time during the
  927. * refile, or the waitqueue could disappear
  928. * from under us. The "wait_queue_head_t"
  929. * parameter of __remove_wait_queue() is unused
  930. * anyway.
  931. */
  932. list_del(&uwq->wq.entry);
  933. add_wait_queue(&ctx->fault_wqh, &uwq->wq);
  934. write_seqcount_end(&ctx->refile_seq);
  935. /* careful to always initialize msg if ret == 0 */
  936. *msg = uwq->msg;
  937. spin_unlock(&ctx->fault_pending_wqh.lock);
  938. ret = 0;
  939. break;
  940. }
  941. spin_unlock(&ctx->fault_pending_wqh.lock);
  942. spin_lock(&ctx->event_wqh.lock);
  943. uwq = find_userfault_evt(ctx);
  944. if (uwq) {
  945. *msg = uwq->msg;
  946. if (uwq->msg.event == UFFD_EVENT_FORK) {
  947. fork_nctx = (struct userfaultfd_ctx *)
  948. (unsigned long)
  949. uwq->msg.arg.reserved.reserved1;
  950. list_move(&uwq->wq.entry, &fork_event);
  951. /*
  952. * fork_nctx can be freed as soon as
  953. * we drop the lock, unless we take a
  954. * reference on it.
  955. */
  956. userfaultfd_ctx_get(fork_nctx);
  957. spin_unlock(&ctx->event_wqh.lock);
  958. ret = 0;
  959. break;
  960. }
  961. userfaultfd_event_complete(ctx, uwq);
  962. spin_unlock(&ctx->event_wqh.lock);
  963. ret = 0;
  964. break;
  965. }
  966. spin_unlock(&ctx->event_wqh.lock);
  967. if (signal_pending(current)) {
  968. ret = -ERESTARTSYS;
  969. break;
  970. }
  971. if (no_wait) {
  972. ret = -EAGAIN;
  973. break;
  974. }
  975. spin_unlock_irq(&ctx->fd_wqh.lock);
  976. schedule();
  977. spin_lock_irq(&ctx->fd_wqh.lock);
  978. }
  979. __remove_wait_queue(&ctx->fd_wqh, &wait);
  980. __set_current_state(TASK_RUNNING);
  981. spin_unlock_irq(&ctx->fd_wqh.lock);
  982. if (!ret && msg->event == UFFD_EVENT_FORK) {
  983. ret = resolve_userfault_fork(fork_nctx, inode, msg);
  984. spin_lock_irq(&ctx->event_wqh.lock);
  985. if (!list_empty(&fork_event)) {
  986. /*
  987. * The fork thread didn't abort, so we can
  988. * drop the temporary refcount.
  989. */
  990. userfaultfd_ctx_put(fork_nctx);
  991. uwq = list_first_entry(&fork_event,
  992. typeof(*uwq),
  993. wq.entry);
  994. /*
  995. * If fork_event list wasn't empty and in turn
  996. * the event wasn't already released by fork
  997. * (the event is allocated on fork kernel
  998. * stack), put the event back to its place in
  999. * the event_wq. fork_event head will be freed
  1000. * as soon as we return so the event cannot
  1001. * stay queued there no matter the current
  1002. * "ret" value.
  1003. */
  1004. list_del(&uwq->wq.entry);
  1005. __add_wait_queue(&ctx->event_wqh, &uwq->wq);
  1006. /*
  1007. * Leave the event in the waitqueue and report
  1008. * error to userland if we failed to resolve
  1009. * the userfault fork.
  1010. */
  1011. if (likely(!ret))
  1012. userfaultfd_event_complete(ctx, uwq);
  1013. } else {
  1014. /*
  1015. * Here the fork thread aborted and the
  1016. * refcount from the fork thread on fork_nctx
  1017. * has already been released. We still hold
  1018. * the reference we took before releasing the
  1019. * lock above. If resolve_userfault_fork
  1020. * failed we've to drop it because the
  1021. * fork_nctx has to be freed in such case. If
  1022. * it succeeded we'll hold it because the new
  1023. * uffd references it.
  1024. */
  1025. if (ret)
  1026. userfaultfd_ctx_put(fork_nctx);
  1027. }
  1028. spin_unlock_irq(&ctx->event_wqh.lock);
  1029. }
  1030. return ret;
  1031. }
  1032. static ssize_t userfaultfd_read(struct file *file, char __user *buf,
  1033. size_t count, loff_t *ppos)
  1034. {
  1035. struct userfaultfd_ctx *ctx = file->private_data;
  1036. ssize_t _ret, ret = 0;
  1037. struct uffd_msg msg;
  1038. int no_wait = file->f_flags & O_NONBLOCK;
  1039. struct inode *inode = file_inode(file);
  1040. if (!userfaultfd_is_initialized(ctx))
  1041. return -EINVAL;
  1042. for (;;) {
  1043. if (count < sizeof(msg))
  1044. return ret ? ret : -EINVAL;
  1045. _ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
  1046. if (_ret < 0)
  1047. return ret ? ret : _ret;
  1048. if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
  1049. return ret ? ret : -EFAULT;
  1050. ret += sizeof(msg);
  1051. buf += sizeof(msg);
  1052. count -= sizeof(msg);
  1053. /*
  1054. * Allow to read more than one fault at time but only
  1055. * block if waiting for the very first one.
  1056. */
  1057. no_wait = O_NONBLOCK;
  1058. }
  1059. }
  1060. static void __wake_userfault(struct userfaultfd_ctx *ctx,
  1061. struct userfaultfd_wake_range *range)
  1062. {
  1063. spin_lock_irq(&ctx->fault_pending_wqh.lock);
  1064. /* wake all in the range and autoremove */
  1065. if (waitqueue_active(&ctx->fault_pending_wqh))
  1066. __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
  1067. range);
  1068. if (waitqueue_active(&ctx->fault_wqh))
  1069. __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
  1070. spin_unlock_irq(&ctx->fault_pending_wqh.lock);
  1071. }
  1072. static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
  1073. struct userfaultfd_wake_range *range)
  1074. {
  1075. unsigned seq;
  1076. bool need_wakeup;
  1077. /*
  1078. * To be sure waitqueue_active() is not reordered by the CPU
  1079. * before the pagetable update, use an explicit SMP memory
  1080. * barrier here. PT lock release or mmap_read_unlock(mm) still
  1081. * have release semantics that can allow the
  1082. * waitqueue_active() to be reordered before the pte update.
  1083. */
  1084. smp_mb();
  1085. /*
  1086. * Use waitqueue_active because it's very frequent to
  1087. * change the address space atomically even if there are no
  1088. * userfaults yet. So we take the spinlock only when we're
  1089. * sure we've userfaults to wake.
  1090. */
  1091. do {
  1092. seq = read_seqcount_begin(&ctx->refile_seq);
  1093. need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
  1094. waitqueue_active(&ctx->fault_wqh);
  1095. cond_resched();
  1096. } while (read_seqcount_retry(&ctx->refile_seq, seq));
  1097. if (need_wakeup)
  1098. __wake_userfault(ctx, range);
  1099. }
  1100. static __always_inline int validate_range(struct mm_struct *mm,
  1101. __u64 start, __u64 len)
  1102. {
  1103. __u64 task_size = mm->task_size;
  1104. if (start & ~PAGE_MASK)
  1105. return -EINVAL;
  1106. if (len & ~PAGE_MASK)
  1107. return -EINVAL;
  1108. if (!len)
  1109. return -EINVAL;
  1110. if (start < mmap_min_addr)
  1111. return -EINVAL;
  1112. if (start >= task_size)
  1113. return -EINVAL;
  1114. if (len > task_size - start)
  1115. return -EINVAL;
  1116. return 0;
  1117. }
  1118. static int userfaultfd_register(struct userfaultfd_ctx *ctx,
  1119. unsigned long arg)
  1120. {
  1121. struct mm_struct *mm = ctx->mm;
  1122. struct vm_area_struct *vma, *prev, *cur;
  1123. int ret;
  1124. struct uffdio_register uffdio_register;
  1125. struct uffdio_register __user *user_uffdio_register;
  1126. unsigned long vm_flags, new_flags;
  1127. bool found;
  1128. bool basic_ioctls;
  1129. unsigned long start, end, vma_end;
  1130. MA_STATE(mas, &mm->mm_mt, 0, 0);
  1131. user_uffdio_register = (struct uffdio_register __user *) arg;
  1132. ret = -EFAULT;
  1133. if (copy_from_user(&uffdio_register, user_uffdio_register,
  1134. sizeof(uffdio_register)-sizeof(__u64)))
  1135. goto out;
  1136. ret = -EINVAL;
  1137. if (!uffdio_register.mode)
  1138. goto out;
  1139. if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
  1140. goto out;
  1141. vm_flags = 0;
  1142. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
  1143. vm_flags |= VM_UFFD_MISSING;
  1144. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
  1145. #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
  1146. goto out;
  1147. #endif
  1148. vm_flags |= VM_UFFD_WP;
  1149. }
  1150. if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
  1151. #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
  1152. goto out;
  1153. #endif
  1154. vm_flags |= VM_UFFD_MINOR;
  1155. }
  1156. ret = validate_range(mm, uffdio_register.range.start,
  1157. uffdio_register.range.len);
  1158. if (ret)
  1159. goto out;
  1160. start = uffdio_register.range.start;
  1161. end = start + uffdio_register.range.len;
  1162. ret = -ENOMEM;
  1163. if (!mmget_not_zero(mm))
  1164. goto out;
  1165. mmap_write_lock(mm);
  1166. mas_set(&mas, start);
  1167. vma = mas_find(&mas, ULONG_MAX);
  1168. if (!vma)
  1169. goto out_unlock;
  1170. /* check that there's at least one vma in the range */
  1171. ret = -EINVAL;
  1172. if (vma->vm_start >= end)
  1173. goto out_unlock;
  1174. /*
  1175. * If the first vma contains huge pages, make sure start address
  1176. * is aligned to huge page size.
  1177. */
  1178. if (is_vm_hugetlb_page(vma)) {
  1179. unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
  1180. if (start & (vma_hpagesize - 1))
  1181. goto out_unlock;
  1182. }
  1183. /*
  1184. * Search for not compatible vmas.
  1185. */
  1186. found = false;
  1187. basic_ioctls = false;
  1188. for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
  1189. cond_resched();
  1190. BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
  1191. !!(cur->vm_flags & __VM_UFFD_FLAGS));
  1192. /* check not compatible vmas */
  1193. ret = -EINVAL;
  1194. if (!vma_can_userfault(cur, vm_flags))
  1195. goto out_unlock;
  1196. /*
  1197. * UFFDIO_COPY will fill file holes even without
  1198. * PROT_WRITE. This check enforces that if this is a
  1199. * MAP_SHARED, the process has write permission to the backing
  1200. * file. If VM_MAYWRITE is set it also enforces that on a
  1201. * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
  1202. * F_WRITE_SEAL can be taken until the vma is destroyed.
  1203. */
  1204. ret = -EPERM;
  1205. if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
  1206. goto out_unlock;
  1207. /*
  1208. * If this vma contains ending address, and huge pages
  1209. * check alignment.
  1210. */
  1211. if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
  1212. end > cur->vm_start) {
  1213. unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
  1214. ret = -EINVAL;
  1215. if (end & (vma_hpagesize - 1))
  1216. goto out_unlock;
  1217. }
  1218. if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
  1219. goto out_unlock;
  1220. /*
  1221. * Check that this vma isn't already owned by a
  1222. * different userfaultfd. We can't allow more than one
  1223. * userfaultfd to own a single vma simultaneously or we
  1224. * wouldn't know which one to deliver the userfaults to.
  1225. */
  1226. ret = -EBUSY;
  1227. if (cur->vm_userfaultfd_ctx.ctx &&
  1228. cur->vm_userfaultfd_ctx.ctx != ctx)
  1229. goto out_unlock;
  1230. /*
  1231. * Note vmas containing huge pages
  1232. */
  1233. if (is_vm_hugetlb_page(cur))
  1234. basic_ioctls = true;
  1235. found = true;
  1236. }
  1237. BUG_ON(!found);
  1238. mas_set(&mas, start);
  1239. prev = mas_prev(&mas, 0);
  1240. if (prev != vma)
  1241. mas_next(&mas, ULONG_MAX);
  1242. ret = 0;
  1243. do {
  1244. cond_resched();
  1245. BUG_ON(!vma_can_userfault(vma, vm_flags));
  1246. BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
  1247. vma->vm_userfaultfd_ctx.ctx != ctx);
  1248. WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
  1249. /*
  1250. * Nothing to do: this vma is already registered into this
  1251. * userfaultfd and with the right tracking mode too.
  1252. */
  1253. if (vma->vm_userfaultfd_ctx.ctx == ctx &&
  1254. (vma->vm_flags & vm_flags) == vm_flags)
  1255. goto skip;
  1256. if (vma->vm_start > start)
  1257. start = vma->vm_start;
  1258. vma_end = min(end, vma->vm_end);
  1259. new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
  1260. prev = vma_merge(mm, prev, start, vma_end, new_flags,
  1261. vma->anon_vma, vma->vm_file, vma->vm_pgoff,
  1262. vma_policy(vma),
  1263. ((struct vm_userfaultfd_ctx){ ctx }),
  1264. anon_vma_name(vma));
  1265. if (prev) {
  1266. /* vma_merge() invalidated the mas */
  1267. mas_pause(&mas);
  1268. vma = prev;
  1269. goto next;
  1270. }
  1271. if (vma->vm_start < start) {
  1272. ret = split_vma(mm, vma, start, 1);
  1273. if (ret)
  1274. break;
  1275. /* split_vma() invalidated the mas */
  1276. mas_pause(&mas);
  1277. }
  1278. if (vma->vm_end > end) {
  1279. ret = split_vma(mm, vma, end, 0);
  1280. if (ret)
  1281. break;
  1282. /* split_vma() invalidated the mas */
  1283. mas_pause(&mas);
  1284. }
  1285. next:
  1286. /*
  1287. * In the vma_merge() successful mprotect-like case 8:
  1288. * the next vma was merged into the current one and
  1289. * the current one has not been updated yet.
  1290. */
  1291. vma_start_write(vma);
  1292. userfaultfd_set_vm_flags(vma, new_flags);
  1293. vma->vm_userfaultfd_ctx.ctx = ctx;
  1294. if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
  1295. hugetlb_unshare_all_pmds(vma);
  1296. skip:
  1297. prev = vma;
  1298. start = vma->vm_end;
  1299. vma = mas_next(&mas, end - 1);
  1300. } while (vma);
  1301. out_unlock:
  1302. mmap_write_unlock(mm);
  1303. mmput(mm);
  1304. if (!ret) {
  1305. __u64 ioctls_out;
  1306. ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
  1307. UFFD_API_RANGE_IOCTLS;
  1308. /*
  1309. * Declare the WP ioctl only if the WP mode is
  1310. * specified and all checks passed with the range
  1311. */
  1312. if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
  1313. ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
  1314. /* CONTINUE ioctl is only supported for MINOR ranges. */
  1315. if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
  1316. ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
  1317. /*
  1318. * Now that we scanned all vmas we can already tell
  1319. * userland which ioctls methods are guaranteed to
  1320. * succeed on this range.
  1321. */
  1322. if (put_user(ioctls_out, &user_uffdio_register->ioctls))
  1323. ret = -EFAULT;
  1324. }
  1325. out:
  1326. return ret;
  1327. }
  1328. static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
  1329. unsigned long arg)
  1330. {
  1331. struct mm_struct *mm = ctx->mm;
  1332. struct vm_area_struct *vma, *prev, *cur;
  1333. int ret;
  1334. struct uffdio_range uffdio_unregister;
  1335. unsigned long new_flags;
  1336. bool found;
  1337. unsigned long start, end, vma_end;
  1338. const void __user *buf = (void __user *)arg;
  1339. MA_STATE(mas, &mm->mm_mt, 0, 0);
  1340. ret = -EFAULT;
  1341. if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
  1342. goto out;
  1343. ret = validate_range(mm, uffdio_unregister.start,
  1344. uffdio_unregister.len);
  1345. if (ret)
  1346. goto out;
  1347. start = uffdio_unregister.start;
  1348. end = start + uffdio_unregister.len;
  1349. ret = -ENOMEM;
  1350. if (!mmget_not_zero(mm))
  1351. goto out;
  1352. mmap_write_lock(mm);
  1353. mas_set(&mas, start);
  1354. vma = mas_find(&mas, ULONG_MAX);
  1355. if (!vma)
  1356. goto out_unlock;
  1357. /* check that there's at least one vma in the range */
  1358. ret = -EINVAL;
  1359. if (vma->vm_start >= end)
  1360. goto out_unlock;
  1361. /*
  1362. * If the first vma contains huge pages, make sure start address
  1363. * is aligned to huge page size.
  1364. */
  1365. if (is_vm_hugetlb_page(vma)) {
  1366. unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
  1367. if (start & (vma_hpagesize - 1))
  1368. goto out_unlock;
  1369. }
  1370. /*
  1371. * Search for not compatible vmas.
  1372. */
  1373. found = false;
  1374. ret = -EINVAL;
  1375. for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
  1376. cond_resched();
  1377. BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
  1378. !!(cur->vm_flags & __VM_UFFD_FLAGS));
  1379. /*
  1380. * Check not compatible vmas, not strictly required
  1381. * here as not compatible vmas cannot have an
  1382. * userfaultfd_ctx registered on them, but this
  1383. * provides for more strict behavior to notice
  1384. * unregistration errors.
  1385. */
  1386. if (!vma_can_userfault(cur, cur->vm_flags))
  1387. goto out_unlock;
  1388. found = true;
  1389. }
  1390. BUG_ON(!found);
  1391. mas_set(&mas, start);
  1392. prev = mas_prev(&mas, 0);
  1393. if (prev != vma)
  1394. mas_next(&mas, ULONG_MAX);
  1395. ret = 0;
  1396. do {
  1397. cond_resched();
  1398. BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
  1399. /*
  1400. * Nothing to do: this vma is already registered into this
  1401. * userfaultfd and with the right tracking mode too.
  1402. */
  1403. if (!vma->vm_userfaultfd_ctx.ctx)
  1404. goto skip;
  1405. WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
  1406. if (vma->vm_start > start)
  1407. start = vma->vm_start;
  1408. vma_end = min(end, vma->vm_end);
  1409. if (userfaultfd_missing(vma)) {
  1410. /*
  1411. * Wake any concurrent pending userfault while
  1412. * we unregister, so they will not hang
  1413. * permanently and it avoids userland to call
  1414. * UFFDIO_WAKE explicitly.
  1415. */
  1416. struct userfaultfd_wake_range range;
  1417. range.start = start;
  1418. range.len = vma_end - start;
  1419. wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
  1420. }
  1421. /* Reset ptes for the whole vma range if wr-protected */
  1422. if (userfaultfd_wp(vma))
  1423. uffd_wp_range(mm, vma, start, vma_end - start, false);
  1424. new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
  1425. prev = vma_merge(mm, prev, start, vma_end, new_flags,
  1426. vma->anon_vma, vma->vm_file, vma->vm_pgoff,
  1427. vma_policy(vma),
  1428. NULL_VM_UFFD_CTX, anon_vma_name(vma));
  1429. if (prev) {
  1430. vma = prev;
  1431. mas_pause(&mas);
  1432. goto next;
  1433. }
  1434. if (vma->vm_start < start) {
  1435. ret = split_vma(mm, vma, start, 1);
  1436. if (ret)
  1437. break;
  1438. mas_pause(&mas);
  1439. }
  1440. if (vma->vm_end > end) {
  1441. ret = split_vma(mm, vma, end, 0);
  1442. if (ret)
  1443. break;
  1444. mas_pause(&mas);
  1445. }
  1446. next:
  1447. /*
  1448. * In the vma_merge() successful mprotect-like case 8:
  1449. * the next vma was merged into the current one and
  1450. * the current one has not been updated yet.
  1451. */
  1452. vma_start_write(vma);
  1453. userfaultfd_set_vm_flags(vma, new_flags);
  1454. vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
  1455. skip:
  1456. prev = vma;
  1457. start = vma->vm_end;
  1458. vma = mas_next(&mas, end - 1);
  1459. } while (vma);
  1460. out_unlock:
  1461. mmap_write_unlock(mm);
  1462. mmput(mm);
  1463. out:
  1464. return ret;
  1465. }
  1466. /*
  1467. * userfaultfd_wake may be used in combination with the
  1468. * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
  1469. */
  1470. static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
  1471. unsigned long arg)
  1472. {
  1473. int ret;
  1474. struct uffdio_range uffdio_wake;
  1475. struct userfaultfd_wake_range range;
  1476. const void __user *buf = (void __user *)arg;
  1477. ret = -EFAULT;
  1478. if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
  1479. goto out;
  1480. ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
  1481. if (ret)
  1482. goto out;
  1483. range.start = uffdio_wake.start;
  1484. range.len = uffdio_wake.len;
  1485. /*
  1486. * len == 0 means wake all and we don't want to wake all here,
  1487. * so check it again to be sure.
  1488. */
  1489. VM_BUG_ON(!range.len);
  1490. wake_userfault(ctx, &range);
  1491. ret = 0;
  1492. out:
  1493. return ret;
  1494. }
  1495. static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
  1496. unsigned long arg)
  1497. {
  1498. __s64 ret;
  1499. struct uffdio_copy uffdio_copy;
  1500. struct uffdio_copy __user *user_uffdio_copy;
  1501. struct userfaultfd_wake_range range;
  1502. user_uffdio_copy = (struct uffdio_copy __user *) arg;
  1503. ret = -EAGAIN;
  1504. if (atomic_read(&ctx->mmap_changing))
  1505. goto out;
  1506. ret = -EFAULT;
  1507. if (copy_from_user(&uffdio_copy, user_uffdio_copy,
  1508. /* don't copy "copy" last field */
  1509. sizeof(uffdio_copy)-sizeof(__s64)))
  1510. goto out;
  1511. ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
  1512. if (ret)
  1513. goto out;
  1514. /*
  1515. * double check for wraparound just in case. copy_from_user()
  1516. * will later check uffdio_copy.src + uffdio_copy.len to fit
  1517. * in the userland range.
  1518. */
  1519. ret = -EINVAL;
  1520. if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
  1521. goto out;
  1522. if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
  1523. goto out;
  1524. if (mmget_not_zero(ctx->mm)) {
  1525. ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
  1526. uffdio_copy.len, &ctx->mmap_changing,
  1527. uffdio_copy.mode);
  1528. mmput(ctx->mm);
  1529. } else {
  1530. return -ESRCH;
  1531. }
  1532. if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
  1533. return -EFAULT;
  1534. if (ret < 0)
  1535. goto out;
  1536. BUG_ON(!ret);
  1537. /* len == 0 would wake all */
  1538. range.len = ret;
  1539. if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
  1540. range.start = uffdio_copy.dst;
  1541. wake_userfault(ctx, &range);
  1542. }
  1543. ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
  1544. out:
  1545. return ret;
  1546. }
  1547. static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
  1548. unsigned long arg)
  1549. {
  1550. __s64 ret;
  1551. struct uffdio_zeropage uffdio_zeropage;
  1552. struct uffdio_zeropage __user *user_uffdio_zeropage;
  1553. struct userfaultfd_wake_range range;
  1554. user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
  1555. ret = -EAGAIN;
  1556. if (atomic_read(&ctx->mmap_changing))
  1557. goto out;
  1558. ret = -EFAULT;
  1559. if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
  1560. /* don't copy "zeropage" last field */
  1561. sizeof(uffdio_zeropage)-sizeof(__s64)))
  1562. goto out;
  1563. ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
  1564. uffdio_zeropage.range.len);
  1565. if (ret)
  1566. goto out;
  1567. ret = -EINVAL;
  1568. if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
  1569. goto out;
  1570. if (mmget_not_zero(ctx->mm)) {
  1571. ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
  1572. uffdio_zeropage.range.len,
  1573. &ctx->mmap_changing);
  1574. mmput(ctx->mm);
  1575. } else {
  1576. return -ESRCH;
  1577. }
  1578. if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
  1579. return -EFAULT;
  1580. if (ret < 0)
  1581. goto out;
  1582. /* len == 0 would wake all */
  1583. BUG_ON(!ret);
  1584. range.len = ret;
  1585. if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
  1586. range.start = uffdio_zeropage.range.start;
  1587. wake_userfault(ctx, &range);
  1588. }
  1589. ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
  1590. out:
  1591. return ret;
  1592. }
  1593. static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
  1594. unsigned long arg)
  1595. {
  1596. int ret;
  1597. struct uffdio_writeprotect uffdio_wp;
  1598. struct uffdio_writeprotect __user *user_uffdio_wp;
  1599. struct userfaultfd_wake_range range;
  1600. bool mode_wp, mode_dontwake;
  1601. if (atomic_read(&ctx->mmap_changing))
  1602. return -EAGAIN;
  1603. user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
  1604. if (copy_from_user(&uffdio_wp, user_uffdio_wp,
  1605. sizeof(struct uffdio_writeprotect)))
  1606. return -EFAULT;
  1607. ret = validate_range(ctx->mm, uffdio_wp.range.start,
  1608. uffdio_wp.range.len);
  1609. if (ret)
  1610. return ret;
  1611. if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
  1612. UFFDIO_WRITEPROTECT_MODE_WP))
  1613. return -EINVAL;
  1614. mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
  1615. mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
  1616. if (mode_wp && mode_dontwake)
  1617. return -EINVAL;
  1618. if (mmget_not_zero(ctx->mm)) {
  1619. ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
  1620. uffdio_wp.range.len, mode_wp,
  1621. &ctx->mmap_changing);
  1622. mmput(ctx->mm);
  1623. } else {
  1624. return -ESRCH;
  1625. }
  1626. if (ret)
  1627. return ret;
  1628. if (!mode_wp && !mode_dontwake) {
  1629. range.start = uffdio_wp.range.start;
  1630. range.len = uffdio_wp.range.len;
  1631. wake_userfault(ctx, &range);
  1632. }
  1633. return ret;
  1634. }
  1635. static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
  1636. {
  1637. __s64 ret;
  1638. struct uffdio_continue uffdio_continue;
  1639. struct uffdio_continue __user *user_uffdio_continue;
  1640. struct userfaultfd_wake_range range;
  1641. user_uffdio_continue = (struct uffdio_continue __user *)arg;
  1642. ret = -EAGAIN;
  1643. if (atomic_read(&ctx->mmap_changing))
  1644. goto out;
  1645. ret = -EFAULT;
  1646. if (copy_from_user(&uffdio_continue, user_uffdio_continue,
  1647. /* don't copy the output fields */
  1648. sizeof(uffdio_continue) - (sizeof(__s64))))
  1649. goto out;
  1650. ret = validate_range(ctx->mm, uffdio_continue.range.start,
  1651. uffdio_continue.range.len);
  1652. if (ret)
  1653. goto out;
  1654. ret = -EINVAL;
  1655. /* double check for wraparound just in case. */
  1656. if (uffdio_continue.range.start + uffdio_continue.range.len <=
  1657. uffdio_continue.range.start) {
  1658. goto out;
  1659. }
  1660. if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
  1661. goto out;
  1662. if (mmget_not_zero(ctx->mm)) {
  1663. ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
  1664. uffdio_continue.range.len,
  1665. &ctx->mmap_changing);
  1666. mmput(ctx->mm);
  1667. } else {
  1668. return -ESRCH;
  1669. }
  1670. if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
  1671. return -EFAULT;
  1672. if (ret < 0)
  1673. goto out;
  1674. /* len == 0 would wake all */
  1675. BUG_ON(!ret);
  1676. range.len = ret;
  1677. if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
  1678. range.start = uffdio_continue.range.start;
  1679. wake_userfault(ctx, &range);
  1680. }
  1681. ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
  1682. out:
  1683. return ret;
  1684. }
  1685. static inline unsigned int uffd_ctx_features(__u64 user_features)
  1686. {
  1687. /*
  1688. * For the current set of features the bits just coincide. Set
  1689. * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
  1690. */
  1691. return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
  1692. }
  1693. /*
  1694. * userland asks for a certain API version and we return which bits
  1695. * and ioctl commands are implemented in this kernel for such API
  1696. * version or -EINVAL if unknown.
  1697. */
  1698. static int userfaultfd_api(struct userfaultfd_ctx *ctx,
  1699. unsigned long arg)
  1700. {
  1701. struct uffdio_api uffdio_api;
  1702. void __user *buf = (void __user *)arg;
  1703. unsigned int ctx_features;
  1704. int ret;
  1705. __u64 features;
  1706. ret = -EFAULT;
  1707. if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
  1708. goto out;
  1709. features = uffdio_api.features;
  1710. ret = -EINVAL;
  1711. if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES))
  1712. goto err_out;
  1713. ret = -EPERM;
  1714. if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
  1715. goto err_out;
  1716. /* report all available features and ioctls to userland */
  1717. uffdio_api.features = UFFD_API_FEATURES;
  1718. #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
  1719. uffdio_api.features &=
  1720. ~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
  1721. #endif
  1722. #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
  1723. uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
  1724. #endif
  1725. #ifndef CONFIG_PTE_MARKER_UFFD_WP
  1726. uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
  1727. #endif
  1728. uffdio_api.ioctls = UFFD_API_IOCTLS;
  1729. ret = -EFAULT;
  1730. if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
  1731. goto out;
  1732. /* only enable the requested features for this uffd context */
  1733. ctx_features = uffd_ctx_features(features);
  1734. ret = -EINVAL;
  1735. if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
  1736. goto err_out;
  1737. ret = 0;
  1738. out:
  1739. return ret;
  1740. err_out:
  1741. memset(&uffdio_api, 0, sizeof(uffdio_api));
  1742. if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
  1743. ret = -EFAULT;
  1744. goto out;
  1745. }
  1746. static long userfaultfd_ioctl(struct file *file, unsigned cmd,
  1747. unsigned long arg)
  1748. {
  1749. int ret = -EINVAL;
  1750. struct userfaultfd_ctx *ctx = file->private_data;
  1751. if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
  1752. return -EINVAL;
  1753. switch(cmd) {
  1754. case UFFDIO_API:
  1755. ret = userfaultfd_api(ctx, arg);
  1756. break;
  1757. case UFFDIO_REGISTER:
  1758. ret = userfaultfd_register(ctx, arg);
  1759. break;
  1760. case UFFDIO_UNREGISTER:
  1761. ret = userfaultfd_unregister(ctx, arg);
  1762. break;
  1763. case UFFDIO_WAKE:
  1764. ret = userfaultfd_wake(ctx, arg);
  1765. break;
  1766. case UFFDIO_COPY:
  1767. ret = userfaultfd_copy(ctx, arg);
  1768. break;
  1769. case UFFDIO_ZEROPAGE:
  1770. ret = userfaultfd_zeropage(ctx, arg);
  1771. break;
  1772. case UFFDIO_WRITEPROTECT:
  1773. ret = userfaultfd_writeprotect(ctx, arg);
  1774. break;
  1775. case UFFDIO_CONTINUE:
  1776. ret = userfaultfd_continue(ctx, arg);
  1777. break;
  1778. }
  1779. return ret;
  1780. }
  1781. #ifdef CONFIG_PROC_FS
  1782. static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
  1783. {
  1784. struct userfaultfd_ctx *ctx = f->private_data;
  1785. wait_queue_entry_t *wq;
  1786. unsigned long pending = 0, total = 0;
  1787. spin_lock_irq(&ctx->fault_pending_wqh.lock);
  1788. list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
  1789. pending++;
  1790. total++;
  1791. }
  1792. list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
  1793. total++;
  1794. }
  1795. spin_unlock_irq(&ctx->fault_pending_wqh.lock);
  1796. /*
  1797. * If more protocols will be added, there will be all shown
  1798. * separated by a space. Like this:
  1799. * protocols: aa:... bb:...
  1800. */
  1801. seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
  1802. pending, total, UFFD_API, ctx->features,
  1803. UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
  1804. }
  1805. #endif
  1806. static const struct file_operations userfaultfd_fops = {
  1807. #ifdef CONFIG_PROC_FS
  1808. .show_fdinfo = userfaultfd_show_fdinfo,
  1809. #endif
  1810. .release = userfaultfd_release,
  1811. .poll = userfaultfd_poll,
  1812. .read = userfaultfd_read,
  1813. .unlocked_ioctl = userfaultfd_ioctl,
  1814. .compat_ioctl = compat_ptr_ioctl,
  1815. .llseek = noop_llseek,
  1816. };
  1817. static void init_once_userfaultfd_ctx(void *mem)
  1818. {
  1819. struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
  1820. init_waitqueue_head(&ctx->fault_pending_wqh);
  1821. init_waitqueue_head(&ctx->fault_wqh);
  1822. init_waitqueue_head(&ctx->event_wqh);
  1823. init_waitqueue_head(&ctx->fd_wqh);
  1824. seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
  1825. }
  1826. static int new_userfaultfd(int flags)
  1827. {
  1828. struct userfaultfd_ctx *ctx;
  1829. int fd;
  1830. BUG_ON(!current->mm);
  1831. /* Check the UFFD_* constants for consistency. */
  1832. BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
  1833. BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
  1834. BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
  1835. if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
  1836. return -EINVAL;
  1837. ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
  1838. if (!ctx)
  1839. return -ENOMEM;
  1840. refcount_set(&ctx->refcount, 1);
  1841. ctx->flags = flags;
  1842. ctx->features = 0;
  1843. ctx->released = false;
  1844. atomic_set(&ctx->mmap_changing, 0);
  1845. ctx->mm = current->mm;
  1846. /* prevent the mm struct to be freed */
  1847. mmgrab(ctx->mm);
  1848. fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
  1849. O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
  1850. if (fd < 0) {
  1851. mmdrop(ctx->mm);
  1852. kmem_cache_free(userfaultfd_ctx_cachep, ctx);
  1853. }
  1854. return fd;
  1855. }
  1856. static inline bool userfaultfd_syscall_allowed(int flags)
  1857. {
  1858. /* Userspace-only page faults are always allowed */
  1859. if (flags & UFFD_USER_MODE_ONLY)
  1860. return true;
  1861. /*
  1862. * The user is requesting a userfaultfd which can handle kernel faults.
  1863. * Privileged users are always allowed to do this.
  1864. */
  1865. if (capable(CAP_SYS_PTRACE))
  1866. return true;
  1867. /* Otherwise, access to kernel fault handling is sysctl controlled. */
  1868. return sysctl_unprivileged_userfaultfd;
  1869. }
  1870. SYSCALL_DEFINE1(userfaultfd, int, flags)
  1871. {
  1872. if (!userfaultfd_syscall_allowed(flags))
  1873. return -EPERM;
  1874. return new_userfaultfd(flags);
  1875. }
  1876. static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
  1877. {
  1878. if (cmd != USERFAULTFD_IOC_NEW)
  1879. return -EINVAL;
  1880. return new_userfaultfd(flags);
  1881. }
  1882. static const struct file_operations userfaultfd_dev_fops = {
  1883. .unlocked_ioctl = userfaultfd_dev_ioctl,
  1884. .compat_ioctl = userfaultfd_dev_ioctl,
  1885. .owner = THIS_MODULE,
  1886. .llseek = noop_llseek,
  1887. };
  1888. static struct miscdevice userfaultfd_misc = {
  1889. .minor = MISC_DYNAMIC_MINOR,
  1890. .name = "userfaultfd",
  1891. .fops = &userfaultfd_dev_fops
  1892. };
  1893. static int __init userfaultfd_init(void)
  1894. {
  1895. int ret;
  1896. ret = misc_register(&userfaultfd_misc);
  1897. if (ret)
  1898. return ret;
  1899. userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
  1900. sizeof(struct userfaultfd_ctx),
  1901. 0,
  1902. SLAB_HWCACHE_ALIGN|SLAB_PANIC,
  1903. init_once_userfaultfd_ctx);
  1904. return 0;
  1905. }
  1906. __initcall(userfaultfd_init);