userfaultfd.c 57 KB

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