fork.c 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/kernel/fork.c
  4. *
  5. * Copyright (C) 1991, 1992 Linus Torvalds
  6. */
  7. /*
  8. * 'fork.c' contains the help-routines for the 'fork' system call
  9. * (see also entry.S and others).
  10. * Fork is rather simple, once you get the hang of it, but the memory
  11. * management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
  12. */
  13. #include <linux/anon_inodes.h>
  14. #include <linux/slab.h>
  15. #include <linux/sched/autogroup.h>
  16. #include <linux/sched/mm.h>
  17. #include <linux/sched/coredump.h>
  18. #include <linux/sched/user.h>
  19. #include <linux/sched/numa_balancing.h>
  20. #include <linux/sched/stat.h>
  21. #include <linux/sched/task.h>
  22. #include <linux/sched/task_stack.h>
  23. #include <linux/sched/cputime.h>
  24. #include <linux/sched/ext.h>
  25. #include <linux/seq_file.h>
  26. #include <linux/rtmutex.h>
  27. #include <linux/init.h>
  28. #include <linux/unistd.h>
  29. #include <linux/module.h>
  30. #include <linux/vmalloc.h>
  31. #include <linux/completion.h>
  32. #include <linux/personality.h>
  33. #include <linux/mempolicy.h>
  34. #include <linux/sem.h>
  35. #include <linux/file.h>
  36. #include <linux/fdtable.h>
  37. #include <linux/iocontext.h>
  38. #include <linux/key.h>
  39. #include <linux/kmsan.h>
  40. #include <linux/binfmts.h>
  41. #include <linux/mman.h>
  42. #include <linux/mmu_notifier.h>
  43. #include <linux/fs.h>
  44. #include <linux/mm.h>
  45. #include <linux/mm_inline.h>
  46. #include <linux/memblock.h>
  47. #include <linux/nsproxy.h>
  48. #include <linux/capability.h>
  49. #include <linux/cpu.h>
  50. #include <linux/cgroup.h>
  51. #include <linux/security.h>
  52. #include <linux/hugetlb.h>
  53. #include <linux/seccomp.h>
  54. #include <linux/swap.h>
  55. #include <linux/syscalls.h>
  56. #include <linux/syscall_user_dispatch.h>
  57. #include <linux/jiffies.h>
  58. #include <linux/futex.h>
  59. #include <linux/compat.h>
  60. #include <linux/kthread.h>
  61. #include <linux/task_io_accounting_ops.h>
  62. #include <linux/rcupdate.h>
  63. #include <linux/ptrace.h>
  64. #include <linux/mount.h>
  65. #include <linux/audit.h>
  66. #include <linux/memcontrol.h>
  67. #include <linux/ftrace.h>
  68. #include <linux/proc_fs.h>
  69. #include <linux/profile.h>
  70. #include <linux/rmap.h>
  71. #include <linux/ksm.h>
  72. #include <linux/acct.h>
  73. #include <linux/userfaultfd_k.h>
  74. #include <linux/tsacct_kern.h>
  75. #include <linux/cn_proc.h>
  76. #include <linux/freezer.h>
  77. #include <linux/delayacct.h>
  78. #include <linux/taskstats_kern.h>
  79. #include <linux/tty.h>
  80. #include <linux/fs_struct.h>
  81. #include <linux/magic.h>
  82. #include <linux/perf_event.h>
  83. #include <linux/posix-timers.h>
  84. #include <linux/user-return-notifier.h>
  85. #include <linux/oom.h>
  86. #include <linux/khugepaged.h>
  87. #include <linux/signalfd.h>
  88. #include <linux/uprobes.h>
  89. #include <linux/aio.h>
  90. #include <linux/compiler.h>
  91. #include <linux/sysctl.h>
  92. #include <linux/kcov.h>
  93. #include <linux/livepatch.h>
  94. #include <linux/thread_info.h>
  95. #include <linux/stackleak.h>
  96. #include <linux/kasan.h>
  97. #include <linux/scs.h>
  98. #include <linux/io_uring.h>
  99. #include <linux/bpf.h>
  100. #include <linux/stackprotector.h>
  101. #include <linux/user_events.h>
  102. #include <linux/iommu.h>
  103. #include <linux/rseq.h>
  104. #include <uapi/linux/pidfd.h>
  105. #include <linux/pidfs.h>
  106. #include <linux/tick.h>
  107. #include <asm/pgalloc.h>
  108. #include <linux/uaccess.h>
  109. #include <asm/mmu_context.h>
  110. #include <asm/cacheflush.h>
  111. #include <asm/tlbflush.h>
  112. #include <trace/events/sched.h>
  113. #define CREATE_TRACE_POINTS
  114. #include <trace/events/task.h>
  115. #include <kunit/visibility.h>
  116. /*
  117. * Minimum number of threads to boot the kernel
  118. */
  119. #define MIN_THREADS 20
  120. /*
  121. * Maximum number of threads
  122. */
  123. #define MAX_THREADS FUTEX_TID_MASK
  124. /*
  125. * Protected counters by write_lock_irq(&tasklist_lock)
  126. */
  127. unsigned long total_forks; /* Handle normal Linux uptimes. */
  128. int nr_threads; /* The idle threads do not count.. */
  129. static int max_threads; /* tunable limit on nr_threads */
  130. #define NAMED_ARRAY_INDEX(x) [x] = __stringify(x)
  131. static const char * const resident_page_types[] = {
  132. NAMED_ARRAY_INDEX(MM_FILEPAGES),
  133. NAMED_ARRAY_INDEX(MM_ANONPAGES),
  134. NAMED_ARRAY_INDEX(MM_SWAPENTS),
  135. NAMED_ARRAY_INDEX(MM_SHMEMPAGES),
  136. };
  137. DEFINE_PER_CPU(unsigned long, process_counts) = 0;
  138. __cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
  139. #ifdef CONFIG_PROVE_RCU
  140. int lockdep_tasklist_lock_is_held(void)
  141. {
  142. return lockdep_is_held(&tasklist_lock);
  143. }
  144. EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
  145. #endif /* #ifdef CONFIG_PROVE_RCU */
  146. int nr_processes(void)
  147. {
  148. int cpu;
  149. int total = 0;
  150. for_each_possible_cpu(cpu)
  151. total += per_cpu(process_counts, cpu);
  152. return total;
  153. }
  154. void __weak arch_release_task_struct(struct task_struct *tsk)
  155. {
  156. }
  157. static struct kmem_cache *task_struct_cachep;
  158. static inline struct task_struct *alloc_task_struct_node(int node)
  159. {
  160. return kmem_cache_alloc_node(task_struct_cachep, GFP_KERNEL, node);
  161. }
  162. static inline void free_task_struct(struct task_struct *tsk)
  163. {
  164. kmem_cache_free(task_struct_cachep, tsk);
  165. }
  166. /*
  167. * Allocate pages if THREAD_SIZE is >= PAGE_SIZE, otherwise use a
  168. * kmemcache based allocator.
  169. */
  170. # if THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)
  171. # ifdef CONFIG_VMAP_STACK
  172. /*
  173. * vmalloc() is a bit slow, and calling vfree() enough times will force a TLB
  174. * flush. Try to minimize the number of calls by caching stacks.
  175. */
  176. #define NR_CACHED_STACKS 2
  177. static DEFINE_PER_CPU(struct vm_struct *, cached_stacks[NR_CACHED_STACKS]);
  178. struct vm_stack {
  179. struct rcu_head rcu;
  180. struct vm_struct *stack_vm_area;
  181. };
  182. static bool try_release_thread_stack_to_cache(struct vm_struct *vm)
  183. {
  184. unsigned int i;
  185. for (i = 0; i < NR_CACHED_STACKS; i++) {
  186. struct vm_struct *tmp = NULL;
  187. if (this_cpu_try_cmpxchg(cached_stacks[i], &tmp, vm))
  188. return true;
  189. }
  190. return false;
  191. }
  192. static void thread_stack_free_rcu(struct rcu_head *rh)
  193. {
  194. struct vm_stack *vm_stack = container_of(rh, struct vm_stack, rcu);
  195. if (try_release_thread_stack_to_cache(vm_stack->stack_vm_area))
  196. return;
  197. vfree(vm_stack);
  198. }
  199. static void thread_stack_delayed_free(struct task_struct *tsk)
  200. {
  201. struct vm_stack *vm_stack = tsk->stack;
  202. vm_stack->stack_vm_area = tsk->stack_vm_area;
  203. call_rcu(&vm_stack->rcu, thread_stack_free_rcu);
  204. }
  205. static int free_vm_stack_cache(unsigned int cpu)
  206. {
  207. struct vm_struct **cached_vm_stacks = per_cpu_ptr(cached_stacks, cpu);
  208. int i;
  209. for (i = 0; i < NR_CACHED_STACKS; i++) {
  210. struct vm_struct *vm_stack = cached_vm_stacks[i];
  211. if (!vm_stack)
  212. continue;
  213. vfree(vm_stack->addr);
  214. cached_vm_stacks[i] = NULL;
  215. }
  216. return 0;
  217. }
  218. static int memcg_charge_kernel_stack(struct vm_struct *vm)
  219. {
  220. int i;
  221. int ret;
  222. int nr_charged = 0;
  223. BUG_ON(vm->nr_pages != THREAD_SIZE / PAGE_SIZE);
  224. for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++) {
  225. ret = memcg_kmem_charge_page(vm->pages[i], GFP_KERNEL, 0);
  226. if (ret)
  227. goto err;
  228. nr_charged++;
  229. }
  230. return 0;
  231. err:
  232. for (i = 0; i < nr_charged; i++)
  233. memcg_kmem_uncharge_page(vm->pages[i], 0);
  234. return ret;
  235. }
  236. static int alloc_thread_stack_node(struct task_struct *tsk, int node)
  237. {
  238. struct vm_struct *vm;
  239. void *stack;
  240. int i;
  241. for (i = 0; i < NR_CACHED_STACKS; i++) {
  242. struct vm_struct *s;
  243. s = this_cpu_xchg(cached_stacks[i], NULL);
  244. if (!s)
  245. continue;
  246. /* Reset stack metadata. */
  247. kasan_unpoison_range(s->addr, THREAD_SIZE);
  248. stack = kasan_reset_tag(s->addr);
  249. /* Clear stale pointers from reused stack. */
  250. memset(stack, 0, THREAD_SIZE);
  251. if (memcg_charge_kernel_stack(s)) {
  252. vfree(s->addr);
  253. return -ENOMEM;
  254. }
  255. tsk->stack_vm_area = s;
  256. tsk->stack = stack;
  257. return 0;
  258. }
  259. /*
  260. * Allocated stacks are cached and later reused by new threads,
  261. * so memcg accounting is performed manually on assigning/releasing
  262. * stacks to tasks. Drop __GFP_ACCOUNT.
  263. */
  264. stack = __vmalloc_node_range(THREAD_SIZE, THREAD_ALIGN,
  265. VMALLOC_START, VMALLOC_END,
  266. THREADINFO_GFP & ~__GFP_ACCOUNT,
  267. PAGE_KERNEL,
  268. 0, node, __builtin_return_address(0));
  269. if (!stack)
  270. return -ENOMEM;
  271. vm = find_vm_area(stack);
  272. if (memcg_charge_kernel_stack(vm)) {
  273. vfree(stack);
  274. return -ENOMEM;
  275. }
  276. /*
  277. * We can't call find_vm_area() in interrupt context, and
  278. * free_thread_stack() can be called in interrupt context,
  279. * so cache the vm_struct.
  280. */
  281. tsk->stack_vm_area = vm;
  282. stack = kasan_reset_tag(stack);
  283. tsk->stack = stack;
  284. return 0;
  285. }
  286. static void free_thread_stack(struct task_struct *tsk)
  287. {
  288. if (!try_release_thread_stack_to_cache(tsk->stack_vm_area))
  289. thread_stack_delayed_free(tsk);
  290. tsk->stack = NULL;
  291. tsk->stack_vm_area = NULL;
  292. }
  293. # else /* !CONFIG_VMAP_STACK */
  294. static void thread_stack_free_rcu(struct rcu_head *rh)
  295. {
  296. __free_pages(virt_to_page(rh), THREAD_SIZE_ORDER);
  297. }
  298. static void thread_stack_delayed_free(struct task_struct *tsk)
  299. {
  300. struct rcu_head *rh = tsk->stack;
  301. call_rcu(rh, thread_stack_free_rcu);
  302. }
  303. static int alloc_thread_stack_node(struct task_struct *tsk, int node)
  304. {
  305. struct page *page = alloc_pages_node(node, THREADINFO_GFP,
  306. THREAD_SIZE_ORDER);
  307. if (likely(page)) {
  308. tsk->stack = kasan_reset_tag(page_address(page));
  309. return 0;
  310. }
  311. return -ENOMEM;
  312. }
  313. static void free_thread_stack(struct task_struct *tsk)
  314. {
  315. thread_stack_delayed_free(tsk);
  316. tsk->stack = NULL;
  317. }
  318. # endif /* CONFIG_VMAP_STACK */
  319. # else /* !(THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK)) */
  320. static struct kmem_cache *thread_stack_cache;
  321. static void thread_stack_free_rcu(struct rcu_head *rh)
  322. {
  323. kmem_cache_free(thread_stack_cache, rh);
  324. }
  325. static void thread_stack_delayed_free(struct task_struct *tsk)
  326. {
  327. struct rcu_head *rh = tsk->stack;
  328. call_rcu(rh, thread_stack_free_rcu);
  329. }
  330. static int alloc_thread_stack_node(struct task_struct *tsk, int node)
  331. {
  332. unsigned long *stack;
  333. stack = kmem_cache_alloc_node(thread_stack_cache, THREADINFO_GFP, node);
  334. stack = kasan_reset_tag(stack);
  335. tsk->stack = stack;
  336. return stack ? 0 : -ENOMEM;
  337. }
  338. static void free_thread_stack(struct task_struct *tsk)
  339. {
  340. thread_stack_delayed_free(tsk);
  341. tsk->stack = NULL;
  342. }
  343. void thread_stack_cache_init(void)
  344. {
  345. thread_stack_cache = kmem_cache_create_usercopy("thread_stack",
  346. THREAD_SIZE, THREAD_SIZE, 0, 0,
  347. THREAD_SIZE, NULL);
  348. BUG_ON(thread_stack_cache == NULL);
  349. }
  350. # endif /* THREAD_SIZE >= PAGE_SIZE || defined(CONFIG_VMAP_STACK) */
  351. /* SLAB cache for signal_struct structures (tsk->signal) */
  352. static struct kmem_cache *signal_cachep;
  353. /* SLAB cache for sighand_struct structures (tsk->sighand) */
  354. struct kmem_cache *sighand_cachep;
  355. /* SLAB cache for files_struct structures (tsk->files) */
  356. struct kmem_cache *files_cachep;
  357. /* SLAB cache for fs_struct structures (tsk->fs) */
  358. struct kmem_cache *fs_cachep;
  359. /* SLAB cache for vm_area_struct structures */
  360. static struct kmem_cache *vm_area_cachep;
  361. /* SLAB cache for mm_struct structures (tsk->mm) */
  362. static struct kmem_cache *mm_cachep;
  363. #ifdef CONFIG_PER_VMA_LOCK
  364. /* SLAB cache for vm_area_struct.lock */
  365. static struct kmem_cache *vma_lock_cachep;
  366. static bool vma_lock_alloc(struct vm_area_struct *vma)
  367. {
  368. vma->vm_lock = kmem_cache_alloc(vma_lock_cachep, GFP_KERNEL);
  369. if (!vma->vm_lock)
  370. return false;
  371. init_rwsem(&vma->vm_lock->lock);
  372. vma->vm_lock_seq = -1;
  373. return true;
  374. }
  375. static inline void vma_lock_free(struct vm_area_struct *vma)
  376. {
  377. kmem_cache_free(vma_lock_cachep, vma->vm_lock);
  378. }
  379. #else /* CONFIG_PER_VMA_LOCK */
  380. static inline bool vma_lock_alloc(struct vm_area_struct *vma) { return true; }
  381. static inline void vma_lock_free(struct vm_area_struct *vma) {}
  382. #endif /* CONFIG_PER_VMA_LOCK */
  383. struct vm_area_struct *vm_area_alloc(struct mm_struct *mm)
  384. {
  385. struct vm_area_struct *vma;
  386. vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
  387. if (!vma)
  388. return NULL;
  389. vma_init(vma, mm);
  390. if (!vma_lock_alloc(vma)) {
  391. kmem_cache_free(vm_area_cachep, vma);
  392. return NULL;
  393. }
  394. return vma;
  395. }
  396. struct vm_area_struct *vm_area_dup(struct vm_area_struct *orig)
  397. {
  398. struct vm_area_struct *new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
  399. if (!new)
  400. return NULL;
  401. ASSERT_EXCLUSIVE_WRITER(orig->vm_flags);
  402. ASSERT_EXCLUSIVE_WRITER(orig->vm_file);
  403. /*
  404. * orig->shared.rb may be modified concurrently, but the clone
  405. * will be reinitialized.
  406. */
  407. data_race(memcpy(new, orig, sizeof(*new)));
  408. if (!vma_lock_alloc(new)) {
  409. kmem_cache_free(vm_area_cachep, new);
  410. return NULL;
  411. }
  412. INIT_LIST_HEAD(&new->anon_vma_chain);
  413. vma_numab_state_init(new);
  414. dup_anon_vma_name(orig, new);
  415. return new;
  416. }
  417. void __vm_area_free(struct vm_area_struct *vma)
  418. {
  419. vma_numab_state_free(vma);
  420. free_anon_vma_name(vma);
  421. vma_lock_free(vma);
  422. kmem_cache_free(vm_area_cachep, vma);
  423. }
  424. #ifdef CONFIG_PER_VMA_LOCK
  425. static void vm_area_free_rcu_cb(struct rcu_head *head)
  426. {
  427. struct vm_area_struct *vma = container_of(head, struct vm_area_struct,
  428. vm_rcu);
  429. /* The vma should not be locked while being destroyed. */
  430. VM_BUG_ON_VMA(rwsem_is_locked(&vma->vm_lock->lock), vma);
  431. __vm_area_free(vma);
  432. }
  433. #endif
  434. void vm_area_free(struct vm_area_struct *vma)
  435. {
  436. #ifdef CONFIG_PER_VMA_LOCK
  437. call_rcu(&vma->vm_rcu, vm_area_free_rcu_cb);
  438. #else
  439. __vm_area_free(vma);
  440. #endif
  441. }
  442. static void account_kernel_stack(struct task_struct *tsk, int account)
  443. {
  444. if (IS_ENABLED(CONFIG_VMAP_STACK)) {
  445. struct vm_struct *vm = task_stack_vm_area(tsk);
  446. int i;
  447. for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
  448. mod_lruvec_page_state(vm->pages[i], NR_KERNEL_STACK_KB,
  449. account * (PAGE_SIZE / 1024));
  450. } else {
  451. void *stack = task_stack_page(tsk);
  452. /* All stack pages are in the same node. */
  453. mod_lruvec_kmem_state(stack, NR_KERNEL_STACK_KB,
  454. account * (THREAD_SIZE / 1024));
  455. }
  456. }
  457. void exit_task_stack_account(struct task_struct *tsk)
  458. {
  459. account_kernel_stack(tsk, -1);
  460. if (IS_ENABLED(CONFIG_VMAP_STACK)) {
  461. struct vm_struct *vm;
  462. int i;
  463. vm = task_stack_vm_area(tsk);
  464. for (i = 0; i < THREAD_SIZE / PAGE_SIZE; i++)
  465. memcg_kmem_uncharge_page(vm->pages[i], 0);
  466. }
  467. }
  468. static void release_task_stack(struct task_struct *tsk)
  469. {
  470. if (WARN_ON(READ_ONCE(tsk->__state) != TASK_DEAD))
  471. return; /* Better to leak the stack than to free prematurely */
  472. free_thread_stack(tsk);
  473. }
  474. #ifdef CONFIG_THREAD_INFO_IN_TASK
  475. void put_task_stack(struct task_struct *tsk)
  476. {
  477. if (refcount_dec_and_test(&tsk->stack_refcount))
  478. release_task_stack(tsk);
  479. }
  480. #endif
  481. void free_task(struct task_struct *tsk)
  482. {
  483. #ifdef CONFIG_SECCOMP
  484. WARN_ON_ONCE(tsk->seccomp.filter);
  485. #endif
  486. release_user_cpus_ptr(tsk);
  487. scs_release(tsk);
  488. #ifndef CONFIG_THREAD_INFO_IN_TASK
  489. /*
  490. * The task is finally done with both the stack and thread_info,
  491. * so free both.
  492. */
  493. release_task_stack(tsk);
  494. #else
  495. /*
  496. * If the task had a separate stack allocation, it should be gone
  497. * by now.
  498. */
  499. WARN_ON_ONCE(refcount_read(&tsk->stack_refcount) != 0);
  500. #endif
  501. rt_mutex_debug_task_free(tsk);
  502. ftrace_graph_exit_task(tsk);
  503. arch_release_task_struct(tsk);
  504. if (tsk->flags & PF_KTHREAD)
  505. free_kthread_struct(tsk);
  506. bpf_task_storage_free(tsk);
  507. free_task_struct(tsk);
  508. }
  509. EXPORT_SYMBOL(free_task);
  510. static void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)
  511. {
  512. struct file *exe_file;
  513. exe_file = get_mm_exe_file(oldmm);
  514. RCU_INIT_POINTER(mm->exe_file, exe_file);
  515. /*
  516. * We depend on the oldmm having properly denied write access to the
  517. * exe_file already.
  518. */
  519. if (exe_file && deny_write_access(exe_file))
  520. pr_warn_once("deny_write_access() failed in %s\n", __func__);
  521. }
  522. #ifdef CONFIG_MMU
  523. static __latent_entropy int dup_mmap(struct mm_struct *mm,
  524. struct mm_struct *oldmm)
  525. {
  526. struct vm_area_struct *mpnt, *tmp;
  527. int retval;
  528. unsigned long charge = 0;
  529. LIST_HEAD(uf);
  530. VMA_ITERATOR(vmi, mm, 0);
  531. if (mmap_write_lock_killable(oldmm))
  532. return -EINTR;
  533. flush_cache_dup_mm(oldmm);
  534. uprobe_dup_mmap(oldmm, mm);
  535. /*
  536. * Not linked in yet - no deadlock potential:
  537. */
  538. mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
  539. /* No ordering required: file already has been exposed. */
  540. dup_mm_exe_file(mm, oldmm);
  541. mm->total_vm = oldmm->total_vm;
  542. mm->data_vm = oldmm->data_vm;
  543. mm->exec_vm = oldmm->exec_vm;
  544. mm->stack_vm = oldmm->stack_vm;
  545. /* Use __mt_dup() to efficiently build an identical maple tree. */
  546. retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
  547. if (unlikely(retval))
  548. goto out;
  549. mt_clear_in_rcu(vmi.mas.tree);
  550. for_each_vma(vmi, mpnt) {
  551. struct file *file;
  552. vma_start_write(mpnt);
  553. if (mpnt->vm_flags & VM_DONTCOPY) {
  554. retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
  555. mpnt->vm_end, GFP_KERNEL);
  556. if (retval)
  557. goto loop_out;
  558. vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
  559. continue;
  560. }
  561. charge = 0;
  562. /*
  563. * Don't duplicate many vmas if we've been oom-killed (for
  564. * example)
  565. */
  566. if (fatal_signal_pending(current)) {
  567. retval = -EINTR;
  568. goto loop_out;
  569. }
  570. if (mpnt->vm_flags & VM_ACCOUNT) {
  571. unsigned long len = vma_pages(mpnt);
  572. if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
  573. goto fail_nomem;
  574. charge = len;
  575. }
  576. tmp = vm_area_dup(mpnt);
  577. if (!tmp)
  578. goto fail_nomem;
  579. retval = vma_dup_policy(mpnt, tmp);
  580. if (retval)
  581. goto fail_nomem_policy;
  582. tmp->vm_mm = mm;
  583. retval = dup_userfaultfd(tmp, &uf);
  584. if (retval)
  585. goto fail_nomem_anon_vma_fork;
  586. if (tmp->vm_flags & VM_WIPEONFORK) {
  587. /*
  588. * VM_WIPEONFORK gets a clean slate in the child.
  589. * Don't prepare anon_vma until fault since we don't
  590. * copy page for current vma.
  591. */
  592. tmp->anon_vma = NULL;
  593. } else if (anon_vma_fork(tmp, mpnt))
  594. goto fail_nomem_anon_vma_fork;
  595. vm_flags_clear(tmp, VM_LOCKED_MASK);
  596. /*
  597. * Copy/update hugetlb private vma information.
  598. */
  599. if (is_vm_hugetlb_page(tmp))
  600. hugetlb_dup_vma_private(tmp);
  601. /*
  602. * Link the vma into the MT. After using __mt_dup(), memory
  603. * allocation is not necessary here, so it cannot fail.
  604. */
  605. vma_iter_bulk_store(&vmi, tmp);
  606. mm->map_count++;
  607. if (tmp->vm_ops && tmp->vm_ops->open)
  608. tmp->vm_ops->open(tmp);
  609. file = tmp->vm_file;
  610. if (file) {
  611. struct address_space *mapping = file->f_mapping;
  612. get_file(file);
  613. i_mmap_lock_write(mapping);
  614. if (vma_is_shared_maywrite(tmp))
  615. mapping_allow_writable(mapping);
  616. flush_dcache_mmap_lock(mapping);
  617. /* insert tmp into the share list, just after mpnt */
  618. vma_interval_tree_insert_after(tmp, mpnt,
  619. &mapping->i_mmap);
  620. flush_dcache_mmap_unlock(mapping);
  621. i_mmap_unlock_write(mapping);
  622. }
  623. if (!(tmp->vm_flags & VM_WIPEONFORK))
  624. retval = copy_page_range(tmp, mpnt);
  625. if (retval) {
  626. mpnt = vma_next(&vmi);
  627. goto loop_out;
  628. }
  629. }
  630. /* a new mm has just been created */
  631. retval = arch_dup_mmap(oldmm, mm);
  632. loop_out:
  633. vma_iter_free(&vmi);
  634. if (!retval) {
  635. mt_set_in_rcu(vmi.mas.tree);
  636. ksm_fork(mm, oldmm);
  637. khugepaged_fork(mm, oldmm);
  638. } else if (mpnt) {
  639. /*
  640. * The entire maple tree has already been duplicated. If the
  641. * mmap duplication fails, mark the failure point with
  642. * XA_ZERO_ENTRY. In exit_mmap(), if this marker is encountered,
  643. * stop releasing VMAs that have not been duplicated after this
  644. * point.
  645. */
  646. mas_set_range(&vmi.mas, mpnt->vm_start, mpnt->vm_end - 1);
  647. mas_store(&vmi.mas, XA_ZERO_ENTRY);
  648. }
  649. out:
  650. mmap_write_unlock(mm);
  651. flush_tlb_mm(oldmm);
  652. mmap_write_unlock(oldmm);
  653. if (!retval)
  654. dup_userfaultfd_complete(&uf);
  655. else
  656. dup_userfaultfd_fail(&uf);
  657. return retval;
  658. fail_nomem_anon_vma_fork:
  659. mpol_put(vma_policy(tmp));
  660. fail_nomem_policy:
  661. vm_area_free(tmp);
  662. fail_nomem:
  663. retval = -ENOMEM;
  664. vm_unacct_memory(charge);
  665. goto loop_out;
  666. }
  667. static inline int mm_alloc_pgd(struct mm_struct *mm)
  668. {
  669. mm->pgd = pgd_alloc(mm);
  670. if (unlikely(!mm->pgd))
  671. return -ENOMEM;
  672. return 0;
  673. }
  674. static inline void mm_free_pgd(struct mm_struct *mm)
  675. {
  676. pgd_free(mm, mm->pgd);
  677. }
  678. #else
  679. static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
  680. {
  681. mmap_write_lock(oldmm);
  682. dup_mm_exe_file(mm, oldmm);
  683. mmap_write_unlock(oldmm);
  684. return 0;
  685. }
  686. #define mm_alloc_pgd(mm) (0)
  687. #define mm_free_pgd(mm)
  688. #endif /* CONFIG_MMU */
  689. static void check_mm(struct mm_struct *mm)
  690. {
  691. int i;
  692. BUILD_BUG_ON_MSG(ARRAY_SIZE(resident_page_types) != NR_MM_COUNTERS,
  693. "Please make sure 'struct resident_page_types[]' is updated as well");
  694. for (i = 0; i < NR_MM_COUNTERS; i++) {
  695. long x = percpu_counter_sum(&mm->rss_stat[i]);
  696. if (unlikely(x))
  697. pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld\n",
  698. mm, resident_page_types[i], x);
  699. }
  700. if (mm_pgtables_bytes(mm))
  701. pr_alert("BUG: non-zero pgtables_bytes on freeing mm: %ld\n",
  702. mm_pgtables_bytes(mm));
  703. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
  704. VM_BUG_ON_MM(mm->pmd_huge_pte, mm);
  705. #endif
  706. }
  707. #define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
  708. #define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
  709. static void do_check_lazy_tlb(void *arg)
  710. {
  711. struct mm_struct *mm = arg;
  712. WARN_ON_ONCE(current->active_mm == mm);
  713. }
  714. static void do_shoot_lazy_tlb(void *arg)
  715. {
  716. struct mm_struct *mm = arg;
  717. if (current->active_mm == mm) {
  718. WARN_ON_ONCE(current->mm);
  719. current->active_mm = &init_mm;
  720. switch_mm(mm, &init_mm, current);
  721. }
  722. }
  723. static void cleanup_lazy_tlbs(struct mm_struct *mm)
  724. {
  725. if (!IS_ENABLED(CONFIG_MMU_LAZY_TLB_SHOOTDOWN)) {
  726. /*
  727. * In this case, lazy tlb mms are refounted and would not reach
  728. * __mmdrop until all CPUs have switched away and mmdrop()ed.
  729. */
  730. return;
  731. }
  732. /*
  733. * Lazy mm shootdown does not refcount "lazy tlb mm" usage, rather it
  734. * requires lazy mm users to switch to another mm when the refcount
  735. * drops to zero, before the mm is freed. This requires IPIs here to
  736. * switch kernel threads to init_mm.
  737. *
  738. * archs that use IPIs to flush TLBs can piggy-back that lazy tlb mm
  739. * switch with the final userspace teardown TLB flush which leaves the
  740. * mm lazy on this CPU but no others, reducing the need for additional
  741. * IPIs here. There are cases where a final IPI is still required here,
  742. * such as the final mmdrop being performed on a different CPU than the
  743. * one exiting, or kernel threads using the mm when userspace exits.
  744. *
  745. * IPI overheads have not found to be expensive, but they could be
  746. * reduced in a number of possible ways, for example (roughly
  747. * increasing order of complexity):
  748. * - The last lazy reference created by exit_mm() could instead switch
  749. * to init_mm, however it's probable this will run on the same CPU
  750. * immediately afterwards, so this may not reduce IPIs much.
  751. * - A batch of mms requiring IPIs could be gathered and freed at once.
  752. * - CPUs store active_mm where it can be remotely checked without a
  753. * lock, to filter out false-positives in the cpumask.
  754. * - After mm_users or mm_count reaches zero, switching away from the
  755. * mm could clear mm_cpumask to reduce some IPIs, perhaps together
  756. * with some batching or delaying of the final IPIs.
  757. * - A delayed freeing and RCU-like quiescing sequence based on mm
  758. * switching to avoid IPIs completely.
  759. */
  760. on_each_cpu_mask(mm_cpumask(mm), do_shoot_lazy_tlb, (void *)mm, 1);
  761. if (IS_ENABLED(CONFIG_DEBUG_VM_SHOOT_LAZIES))
  762. on_each_cpu(do_check_lazy_tlb, (void *)mm, 1);
  763. }
  764. /*
  765. * Called when the last reference to the mm
  766. * is dropped: either by a lazy thread or by
  767. * mmput. Free the page directory and the mm.
  768. */
  769. void __mmdrop(struct mm_struct *mm)
  770. {
  771. BUG_ON(mm == &init_mm);
  772. WARN_ON_ONCE(mm == current->mm);
  773. /* Ensure no CPUs are using this as their lazy tlb mm */
  774. cleanup_lazy_tlbs(mm);
  775. WARN_ON_ONCE(mm == current->active_mm);
  776. mm_free_pgd(mm);
  777. destroy_context(mm);
  778. mmu_notifier_subscriptions_destroy(mm);
  779. check_mm(mm);
  780. put_user_ns(mm->user_ns);
  781. mm_pasid_drop(mm);
  782. mm_destroy_cid(mm);
  783. percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
  784. free_mm(mm);
  785. }
  786. EXPORT_SYMBOL_GPL(__mmdrop);
  787. static void mmdrop_async_fn(struct work_struct *work)
  788. {
  789. struct mm_struct *mm;
  790. mm = container_of(work, struct mm_struct, async_put_work);
  791. __mmdrop(mm);
  792. }
  793. static void mmdrop_async(struct mm_struct *mm)
  794. {
  795. if (unlikely(atomic_dec_and_test(&mm->mm_count))) {
  796. INIT_WORK(&mm->async_put_work, mmdrop_async_fn);
  797. schedule_work(&mm->async_put_work);
  798. }
  799. }
  800. static inline void free_signal_struct(struct signal_struct *sig)
  801. {
  802. taskstats_tgid_free(sig);
  803. sched_autogroup_exit(sig);
  804. /*
  805. * __mmdrop is not safe to call from softirq context on x86 due to
  806. * pgd_dtor so postpone it to the async context
  807. */
  808. if (sig->oom_mm)
  809. mmdrop_async(sig->oom_mm);
  810. kmem_cache_free(signal_cachep, sig);
  811. }
  812. static inline void put_signal_struct(struct signal_struct *sig)
  813. {
  814. if (refcount_dec_and_test(&sig->sigcnt))
  815. free_signal_struct(sig);
  816. }
  817. void __put_task_struct(struct task_struct *tsk)
  818. {
  819. WARN_ON(!tsk->exit_state);
  820. WARN_ON(refcount_read(&tsk->usage));
  821. WARN_ON(tsk == current);
  822. sched_ext_free(tsk);
  823. io_uring_free(tsk);
  824. cgroup_free(tsk);
  825. task_numa_free(tsk, true);
  826. security_task_free(tsk);
  827. exit_creds(tsk);
  828. delayacct_tsk_free(tsk);
  829. put_signal_struct(tsk->signal);
  830. sched_core_free(tsk);
  831. free_task(tsk);
  832. }
  833. EXPORT_SYMBOL_GPL(__put_task_struct);
  834. void __put_task_struct_rcu_cb(struct rcu_head *rhp)
  835. {
  836. struct task_struct *task = container_of(rhp, struct task_struct, rcu);
  837. __put_task_struct(task);
  838. }
  839. EXPORT_SYMBOL_GPL(__put_task_struct_rcu_cb);
  840. void __init __weak arch_task_cache_init(void) { }
  841. /*
  842. * set_max_threads
  843. */
  844. static void __init set_max_threads(unsigned int max_threads_suggested)
  845. {
  846. u64 threads;
  847. unsigned long nr_pages = memblock_estimated_nr_free_pages();
  848. /*
  849. * The number of threads shall be limited such that the thread
  850. * structures may only consume a small part of the available memory.
  851. */
  852. if (fls64(nr_pages) + fls64(PAGE_SIZE) > 64)
  853. threads = MAX_THREADS;
  854. else
  855. threads = div64_u64((u64) nr_pages * (u64) PAGE_SIZE,
  856. (u64) THREAD_SIZE * 8UL);
  857. if (threads > max_threads_suggested)
  858. threads = max_threads_suggested;
  859. max_threads = clamp_t(u64, threads, MIN_THREADS, MAX_THREADS);
  860. }
  861. #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
  862. /* Initialized by the architecture: */
  863. int arch_task_struct_size __read_mostly;
  864. #endif
  865. static void __init task_struct_whitelist(unsigned long *offset, unsigned long *size)
  866. {
  867. /* Fetch thread_struct whitelist for the architecture. */
  868. arch_thread_struct_whitelist(offset, size);
  869. /*
  870. * Handle zero-sized whitelist or empty thread_struct, otherwise
  871. * adjust offset to position of thread_struct in task_struct.
  872. */
  873. if (unlikely(*size == 0))
  874. *offset = 0;
  875. else
  876. *offset += offsetof(struct task_struct, thread);
  877. }
  878. void __init fork_init(void)
  879. {
  880. int i;
  881. #ifndef ARCH_MIN_TASKALIGN
  882. #define ARCH_MIN_TASKALIGN 0
  883. #endif
  884. int align = max_t(int, L1_CACHE_BYTES, ARCH_MIN_TASKALIGN);
  885. unsigned long useroffset, usersize;
  886. /* create a slab on which task_structs can be allocated */
  887. task_struct_whitelist(&useroffset, &usersize);
  888. task_struct_cachep = kmem_cache_create_usercopy("task_struct",
  889. arch_task_struct_size, align,
  890. SLAB_PANIC|SLAB_ACCOUNT,
  891. useroffset, usersize, NULL);
  892. /* do the arch specific task caches init */
  893. arch_task_cache_init();
  894. set_max_threads(MAX_THREADS);
  895. init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
  896. init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
  897. init_task.signal->rlim[RLIMIT_SIGPENDING] =
  898. init_task.signal->rlim[RLIMIT_NPROC];
  899. for (i = 0; i < UCOUNT_COUNTS; i++)
  900. init_user_ns.ucount_max[i] = max_threads/2;
  901. set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_NPROC, RLIM_INFINITY);
  902. set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MSGQUEUE, RLIM_INFINITY);
  903. set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_SIGPENDING, RLIM_INFINITY);
  904. set_userns_rlimit_max(&init_user_ns, UCOUNT_RLIMIT_MEMLOCK, RLIM_INFINITY);
  905. #ifdef CONFIG_VMAP_STACK
  906. cpuhp_setup_state(CPUHP_BP_PREPARE_DYN, "fork:vm_stack_cache",
  907. NULL, free_vm_stack_cache);
  908. #endif
  909. scs_init();
  910. lockdep_init_task(&init_task);
  911. uprobes_init();
  912. }
  913. int __weak arch_dup_task_struct(struct task_struct *dst,
  914. struct task_struct *src)
  915. {
  916. *dst = *src;
  917. return 0;
  918. }
  919. void set_task_stack_end_magic(struct task_struct *tsk)
  920. {
  921. unsigned long *stackend;
  922. stackend = end_of_stack(tsk);
  923. *stackend = STACK_END_MAGIC; /* for overflow detection */
  924. }
  925. static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
  926. {
  927. struct task_struct *tsk;
  928. int err;
  929. if (node == NUMA_NO_NODE)
  930. node = tsk_fork_get_node(orig);
  931. tsk = alloc_task_struct_node(node);
  932. if (!tsk)
  933. return NULL;
  934. err = arch_dup_task_struct(tsk, orig);
  935. if (err)
  936. goto free_tsk;
  937. err = alloc_thread_stack_node(tsk, node);
  938. if (err)
  939. goto free_tsk;
  940. #ifdef CONFIG_THREAD_INFO_IN_TASK
  941. refcount_set(&tsk->stack_refcount, 1);
  942. #endif
  943. account_kernel_stack(tsk, 1);
  944. err = scs_prepare(tsk, node);
  945. if (err)
  946. goto free_stack;
  947. #ifdef CONFIG_SECCOMP
  948. /*
  949. * We must handle setting up seccomp filters once we're under
  950. * the sighand lock in case orig has changed between now and
  951. * then. Until then, filter must be NULL to avoid messing up
  952. * the usage counts on the error path calling free_task.
  953. */
  954. tsk->seccomp.filter = NULL;
  955. #endif
  956. setup_thread_stack(tsk, orig);
  957. clear_user_return_notifier(tsk);
  958. clear_tsk_need_resched(tsk);
  959. set_task_stack_end_magic(tsk);
  960. clear_syscall_work_syscall_user_dispatch(tsk);
  961. #ifdef CONFIG_STACKPROTECTOR
  962. tsk->stack_canary = get_random_canary();
  963. #endif
  964. if (orig->cpus_ptr == &orig->cpus_mask)
  965. tsk->cpus_ptr = &tsk->cpus_mask;
  966. dup_user_cpus_ptr(tsk, orig, node);
  967. /*
  968. * One for the user space visible state that goes away when reaped.
  969. * One for the scheduler.
  970. */
  971. refcount_set(&tsk->rcu_users, 2);
  972. /* One for the rcu users */
  973. refcount_set(&tsk->usage, 1);
  974. #ifdef CONFIG_BLK_DEV_IO_TRACE
  975. tsk->btrace_seq = 0;
  976. #endif
  977. tsk->splice_pipe = NULL;
  978. tsk->task_frag.page = NULL;
  979. tsk->wake_q.next = NULL;
  980. tsk->worker_private = NULL;
  981. kcov_task_init(tsk);
  982. kmsan_task_create(tsk);
  983. kmap_local_fork(tsk);
  984. #ifdef CONFIG_FAULT_INJECTION
  985. tsk->fail_nth = 0;
  986. #endif
  987. #ifdef CONFIG_BLK_CGROUP
  988. tsk->throttle_disk = NULL;
  989. tsk->use_memdelay = 0;
  990. #endif
  991. #ifdef CONFIG_ARCH_HAS_CPU_PASID
  992. tsk->pasid_activated = 0;
  993. #endif
  994. #ifdef CONFIG_MEMCG
  995. tsk->active_memcg = NULL;
  996. #endif
  997. #ifdef CONFIG_CPU_SUP_INTEL
  998. tsk->reported_split_lock = 0;
  999. #endif
  1000. #ifdef CONFIG_SCHED_MM_CID
  1001. tsk->mm_cid = -1;
  1002. tsk->last_mm_cid = -1;
  1003. tsk->mm_cid_active = 0;
  1004. tsk->migrate_from_cpu = -1;
  1005. #endif
  1006. return tsk;
  1007. free_stack:
  1008. exit_task_stack_account(tsk);
  1009. free_thread_stack(tsk);
  1010. free_tsk:
  1011. free_task_struct(tsk);
  1012. return NULL;
  1013. }
  1014. __cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
  1015. static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
  1016. static int __init coredump_filter_setup(char *s)
  1017. {
  1018. default_dump_filter =
  1019. (simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
  1020. MMF_DUMP_FILTER_MASK;
  1021. return 1;
  1022. }
  1023. __setup("coredump_filter=", coredump_filter_setup);
  1024. #include <linux/init_task.h>
  1025. static void mm_init_aio(struct mm_struct *mm)
  1026. {
  1027. #ifdef CONFIG_AIO
  1028. spin_lock_init(&mm->ioctx_lock);
  1029. mm->ioctx_table = NULL;
  1030. #endif
  1031. }
  1032. static __always_inline void mm_clear_owner(struct mm_struct *mm,
  1033. struct task_struct *p)
  1034. {
  1035. #ifdef CONFIG_MEMCG
  1036. if (mm->owner == p)
  1037. WRITE_ONCE(mm->owner, NULL);
  1038. #endif
  1039. }
  1040. static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
  1041. {
  1042. #ifdef CONFIG_MEMCG
  1043. mm->owner = p;
  1044. #endif
  1045. }
  1046. static void mm_init_uprobes_state(struct mm_struct *mm)
  1047. {
  1048. #ifdef CONFIG_UPROBES
  1049. mm->uprobes_state.xol_area = NULL;
  1050. #endif
  1051. }
  1052. static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p,
  1053. struct user_namespace *user_ns)
  1054. {
  1055. mt_init_flags(&mm->mm_mt, MM_MT_FLAGS);
  1056. mt_set_external_lock(&mm->mm_mt, &mm->mmap_lock);
  1057. atomic_set(&mm->mm_users, 1);
  1058. atomic_set(&mm->mm_count, 1);
  1059. seqcount_init(&mm->write_protect_seq);
  1060. mmap_init_lock(mm);
  1061. INIT_LIST_HEAD(&mm->mmlist);
  1062. #ifdef CONFIG_PER_VMA_LOCK
  1063. mm->mm_lock_seq = 0;
  1064. #endif
  1065. mm_pgtables_bytes_init(mm);
  1066. mm->map_count = 0;
  1067. mm->locked_vm = 0;
  1068. atomic64_set(&mm->pinned_vm, 0);
  1069. memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
  1070. spin_lock_init(&mm->page_table_lock);
  1071. spin_lock_init(&mm->arg_lock);
  1072. mm_init_cpumask(mm);
  1073. mm_init_aio(mm);
  1074. mm_init_owner(mm, p);
  1075. mm_pasid_init(mm);
  1076. RCU_INIT_POINTER(mm->exe_file, NULL);
  1077. mmu_notifier_subscriptions_init(mm);
  1078. init_tlb_flush_pending(mm);
  1079. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
  1080. mm->pmd_huge_pte = NULL;
  1081. #endif
  1082. mm_init_uprobes_state(mm);
  1083. hugetlb_count_init(mm);
  1084. if (current->mm) {
  1085. mm->flags = mmf_init_flags(current->mm->flags);
  1086. mm->def_flags = current->mm->def_flags & VM_INIT_DEF_MASK;
  1087. } else {
  1088. mm->flags = default_dump_filter;
  1089. mm->def_flags = 0;
  1090. }
  1091. if (mm_alloc_pgd(mm))
  1092. goto fail_nopgd;
  1093. if (init_new_context(p, mm))
  1094. goto fail_nocontext;
  1095. if (mm_alloc_cid(mm))
  1096. goto fail_cid;
  1097. if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
  1098. NR_MM_COUNTERS))
  1099. goto fail_pcpu;
  1100. mm->user_ns = get_user_ns(user_ns);
  1101. lru_gen_init_mm(mm);
  1102. return mm;
  1103. fail_pcpu:
  1104. mm_destroy_cid(mm);
  1105. fail_cid:
  1106. destroy_context(mm);
  1107. fail_nocontext:
  1108. mm_free_pgd(mm);
  1109. fail_nopgd:
  1110. free_mm(mm);
  1111. return NULL;
  1112. }
  1113. /*
  1114. * Allocate and initialize an mm_struct.
  1115. */
  1116. struct mm_struct *mm_alloc(void)
  1117. {
  1118. struct mm_struct *mm;
  1119. mm = allocate_mm();
  1120. if (!mm)
  1121. return NULL;
  1122. memset(mm, 0, sizeof(*mm));
  1123. return mm_init(mm, current, current_user_ns());
  1124. }
  1125. EXPORT_SYMBOL_IF_KUNIT(mm_alloc);
  1126. static inline void __mmput(struct mm_struct *mm)
  1127. {
  1128. VM_BUG_ON(atomic_read(&mm->mm_users));
  1129. uprobe_clear_state(mm);
  1130. exit_aio(mm);
  1131. ksm_exit(mm);
  1132. khugepaged_exit(mm); /* must run before exit_mmap */
  1133. exit_mmap(mm);
  1134. mm_put_huge_zero_folio(mm);
  1135. set_mm_exe_file(mm, NULL);
  1136. if (!list_empty(&mm->mmlist)) {
  1137. spin_lock(&mmlist_lock);
  1138. list_del(&mm->mmlist);
  1139. spin_unlock(&mmlist_lock);
  1140. }
  1141. if (mm->binfmt)
  1142. module_put(mm->binfmt->module);
  1143. lru_gen_del_mm(mm);
  1144. mmdrop(mm);
  1145. }
  1146. /*
  1147. * Decrement the use count and release all resources for an mm.
  1148. */
  1149. void mmput(struct mm_struct *mm)
  1150. {
  1151. might_sleep();
  1152. if (atomic_dec_and_test(&mm->mm_users))
  1153. __mmput(mm);
  1154. }
  1155. EXPORT_SYMBOL_GPL(mmput);
  1156. #ifdef CONFIG_MMU
  1157. static void mmput_async_fn(struct work_struct *work)
  1158. {
  1159. struct mm_struct *mm = container_of(work, struct mm_struct,
  1160. async_put_work);
  1161. __mmput(mm);
  1162. }
  1163. void mmput_async(struct mm_struct *mm)
  1164. {
  1165. if (atomic_dec_and_test(&mm->mm_users)) {
  1166. INIT_WORK(&mm->async_put_work, mmput_async_fn);
  1167. schedule_work(&mm->async_put_work);
  1168. }
  1169. }
  1170. EXPORT_SYMBOL_GPL(mmput_async);
  1171. #endif
  1172. /**
  1173. * set_mm_exe_file - change a reference to the mm's executable file
  1174. * @mm: The mm to change.
  1175. * @new_exe_file: The new file to use.
  1176. *
  1177. * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
  1178. *
  1179. * Main users are mmput() and sys_execve(). Callers prevent concurrent
  1180. * invocations: in mmput() nobody alive left, in execve it happens before
  1181. * the new mm is made visible to anyone.
  1182. *
  1183. * Can only fail if new_exe_file != NULL.
  1184. */
  1185. int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
  1186. {
  1187. struct file *old_exe_file;
  1188. /*
  1189. * It is safe to dereference the exe_file without RCU as
  1190. * this function is only called if nobody else can access
  1191. * this mm -- see comment above for justification.
  1192. */
  1193. old_exe_file = rcu_dereference_raw(mm->exe_file);
  1194. if (new_exe_file) {
  1195. /*
  1196. * We expect the caller (i.e., sys_execve) to already denied
  1197. * write access, so this is unlikely to fail.
  1198. */
  1199. if (unlikely(deny_write_access(new_exe_file)))
  1200. return -EACCES;
  1201. get_file(new_exe_file);
  1202. }
  1203. rcu_assign_pointer(mm->exe_file, new_exe_file);
  1204. if (old_exe_file) {
  1205. allow_write_access(old_exe_file);
  1206. fput(old_exe_file);
  1207. }
  1208. return 0;
  1209. }
  1210. /**
  1211. * replace_mm_exe_file - replace a reference to the mm's executable file
  1212. * @mm: The mm to change.
  1213. * @new_exe_file: The new file to use.
  1214. *
  1215. * This changes mm's executable file (shown as symlink /proc/[pid]/exe).
  1216. *
  1217. * Main user is sys_prctl(PR_SET_MM_MAP/EXE_FILE).
  1218. */
  1219. int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file)
  1220. {
  1221. struct vm_area_struct *vma;
  1222. struct file *old_exe_file;
  1223. int ret = 0;
  1224. /* Forbid mm->exe_file change if old file still mapped. */
  1225. old_exe_file = get_mm_exe_file(mm);
  1226. if (old_exe_file) {
  1227. VMA_ITERATOR(vmi, mm, 0);
  1228. mmap_read_lock(mm);
  1229. for_each_vma(vmi, vma) {
  1230. if (!vma->vm_file)
  1231. continue;
  1232. if (path_equal(&vma->vm_file->f_path,
  1233. &old_exe_file->f_path)) {
  1234. ret = -EBUSY;
  1235. break;
  1236. }
  1237. }
  1238. mmap_read_unlock(mm);
  1239. fput(old_exe_file);
  1240. if (ret)
  1241. return ret;
  1242. }
  1243. ret = deny_write_access(new_exe_file);
  1244. if (ret)
  1245. return -EACCES;
  1246. get_file(new_exe_file);
  1247. /* set the new file */
  1248. mmap_write_lock(mm);
  1249. old_exe_file = rcu_dereference_raw(mm->exe_file);
  1250. rcu_assign_pointer(mm->exe_file, new_exe_file);
  1251. mmap_write_unlock(mm);
  1252. if (old_exe_file) {
  1253. allow_write_access(old_exe_file);
  1254. fput(old_exe_file);
  1255. }
  1256. return 0;
  1257. }
  1258. /**
  1259. * get_mm_exe_file - acquire a reference to the mm's executable file
  1260. * @mm: The mm of interest.
  1261. *
  1262. * Returns %NULL if mm has no associated executable file.
  1263. * User must release file via fput().
  1264. */
  1265. struct file *get_mm_exe_file(struct mm_struct *mm)
  1266. {
  1267. struct file *exe_file;
  1268. rcu_read_lock();
  1269. exe_file = get_file_rcu(&mm->exe_file);
  1270. rcu_read_unlock();
  1271. return exe_file;
  1272. }
  1273. /**
  1274. * get_task_exe_file - acquire a reference to the task's executable file
  1275. * @task: The task.
  1276. *
  1277. * Returns %NULL if task's mm (if any) has no associated executable file or
  1278. * this is a kernel thread with borrowed mm (see the comment above get_task_mm).
  1279. * User must release file via fput().
  1280. */
  1281. struct file *get_task_exe_file(struct task_struct *task)
  1282. {
  1283. struct file *exe_file = NULL;
  1284. struct mm_struct *mm;
  1285. task_lock(task);
  1286. mm = task->mm;
  1287. if (mm) {
  1288. if (!(task->flags & PF_KTHREAD))
  1289. exe_file = get_mm_exe_file(mm);
  1290. }
  1291. task_unlock(task);
  1292. return exe_file;
  1293. }
  1294. /**
  1295. * get_task_mm - acquire a reference to the task's mm
  1296. * @task: The task.
  1297. *
  1298. * Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
  1299. * this kernel workthread has transiently adopted a user mm with use_mm,
  1300. * to do its AIO) is not set and if so returns a reference to it, after
  1301. * bumping up the use count. User must release the mm via mmput()
  1302. * after use. Typically used by /proc and ptrace.
  1303. */
  1304. struct mm_struct *get_task_mm(struct task_struct *task)
  1305. {
  1306. struct mm_struct *mm;
  1307. if (task->flags & PF_KTHREAD)
  1308. return NULL;
  1309. task_lock(task);
  1310. mm = task->mm;
  1311. if (mm)
  1312. mmget(mm);
  1313. task_unlock(task);
  1314. return mm;
  1315. }
  1316. EXPORT_SYMBOL_GPL(get_task_mm);
  1317. struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
  1318. {
  1319. struct mm_struct *mm;
  1320. int err;
  1321. err = down_read_killable(&task->signal->exec_update_lock);
  1322. if (err)
  1323. return ERR_PTR(err);
  1324. mm = get_task_mm(task);
  1325. if (mm && mm != current->mm &&
  1326. !ptrace_may_access(task, mode)) {
  1327. mmput(mm);
  1328. mm = ERR_PTR(-EACCES);
  1329. }
  1330. up_read(&task->signal->exec_update_lock);
  1331. return mm;
  1332. }
  1333. static void complete_vfork_done(struct task_struct *tsk)
  1334. {
  1335. struct completion *vfork;
  1336. task_lock(tsk);
  1337. vfork = tsk->vfork_done;
  1338. if (likely(vfork)) {
  1339. tsk->vfork_done = NULL;
  1340. complete(vfork);
  1341. }
  1342. task_unlock(tsk);
  1343. }
  1344. static int wait_for_vfork_done(struct task_struct *child,
  1345. struct completion *vfork)
  1346. {
  1347. unsigned int state = TASK_KILLABLE|TASK_FREEZABLE;
  1348. int killed;
  1349. cgroup_enter_frozen();
  1350. killed = wait_for_completion_state(vfork, state);
  1351. cgroup_leave_frozen(false);
  1352. if (killed) {
  1353. task_lock(child);
  1354. child->vfork_done = NULL;
  1355. task_unlock(child);
  1356. }
  1357. put_task_struct(child);
  1358. return killed;
  1359. }
  1360. /* Please note the differences between mmput and mm_release.
  1361. * mmput is called whenever we stop holding onto a mm_struct,
  1362. * error success whatever.
  1363. *
  1364. * mm_release is called after a mm_struct has been removed
  1365. * from the current process.
  1366. *
  1367. * This difference is important for error handling, when we
  1368. * only half set up a mm_struct for a new process and need to restore
  1369. * the old one. Because we mmput the new mm_struct before
  1370. * restoring the old one. . .
  1371. * Eric Biederman 10 January 1998
  1372. */
  1373. static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
  1374. {
  1375. uprobe_free_utask(tsk);
  1376. /* Get rid of any cached register state */
  1377. deactivate_mm(tsk, mm);
  1378. /*
  1379. * Signal userspace if we're not exiting with a core dump
  1380. * because we want to leave the value intact for debugging
  1381. * purposes.
  1382. */
  1383. if (tsk->clear_child_tid) {
  1384. if (atomic_read(&mm->mm_users) > 1) {
  1385. /*
  1386. * We don't check the error code - if userspace has
  1387. * not set up a proper pointer then tough luck.
  1388. */
  1389. put_user(0, tsk->clear_child_tid);
  1390. do_futex(tsk->clear_child_tid, FUTEX_WAKE,
  1391. 1, NULL, NULL, 0, 0);
  1392. }
  1393. tsk->clear_child_tid = NULL;
  1394. }
  1395. /*
  1396. * All done, finally we can wake up parent and return this mm to him.
  1397. * Also kthread_stop() uses this completion for synchronization.
  1398. */
  1399. if (tsk->vfork_done)
  1400. complete_vfork_done(tsk);
  1401. }
  1402. void exit_mm_release(struct task_struct *tsk, struct mm_struct *mm)
  1403. {
  1404. futex_exit_release(tsk);
  1405. mm_release(tsk, mm);
  1406. }
  1407. void exec_mm_release(struct task_struct *tsk, struct mm_struct *mm)
  1408. {
  1409. futex_exec_release(tsk);
  1410. mm_release(tsk, mm);
  1411. }
  1412. /**
  1413. * dup_mm() - duplicates an existing mm structure
  1414. * @tsk: the task_struct with which the new mm will be associated.
  1415. * @oldmm: the mm to duplicate.
  1416. *
  1417. * Allocates a new mm structure and duplicates the provided @oldmm structure
  1418. * content into it.
  1419. *
  1420. * Return: the duplicated mm or NULL on failure.
  1421. */
  1422. static struct mm_struct *dup_mm(struct task_struct *tsk,
  1423. struct mm_struct *oldmm)
  1424. {
  1425. struct mm_struct *mm;
  1426. int err;
  1427. mm = allocate_mm();
  1428. if (!mm)
  1429. goto fail_nomem;
  1430. memcpy(mm, oldmm, sizeof(*mm));
  1431. if (!mm_init(mm, tsk, mm->user_ns))
  1432. goto fail_nomem;
  1433. uprobe_start_dup_mmap();
  1434. err = dup_mmap(mm, oldmm);
  1435. if (err)
  1436. goto free_pt;
  1437. uprobe_end_dup_mmap();
  1438. mm->hiwater_rss = get_mm_rss(mm);
  1439. mm->hiwater_vm = mm->total_vm;
  1440. if (mm->binfmt && !try_module_get(mm->binfmt->module))
  1441. goto free_pt;
  1442. return mm;
  1443. free_pt:
  1444. /* don't put binfmt in mmput, we haven't got module yet */
  1445. mm->binfmt = NULL;
  1446. mm_init_owner(mm, NULL);
  1447. mmput(mm);
  1448. if (err)
  1449. uprobe_end_dup_mmap();
  1450. fail_nomem:
  1451. return NULL;
  1452. }
  1453. static int copy_mm(unsigned long clone_flags, struct task_struct *tsk)
  1454. {
  1455. struct mm_struct *mm, *oldmm;
  1456. tsk->min_flt = tsk->maj_flt = 0;
  1457. tsk->nvcsw = tsk->nivcsw = 0;
  1458. #ifdef CONFIG_DETECT_HUNG_TASK
  1459. tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
  1460. tsk->last_switch_time = 0;
  1461. #endif
  1462. tsk->mm = NULL;
  1463. tsk->active_mm = NULL;
  1464. /*
  1465. * Are we cloning a kernel thread?
  1466. *
  1467. * We need to steal a active VM for that..
  1468. */
  1469. oldmm = current->mm;
  1470. if (!oldmm)
  1471. return 0;
  1472. if (clone_flags & CLONE_VM) {
  1473. mmget(oldmm);
  1474. mm = oldmm;
  1475. } else {
  1476. mm = dup_mm(tsk, current->mm);
  1477. if (!mm)
  1478. return -ENOMEM;
  1479. }
  1480. tsk->mm = mm;
  1481. tsk->active_mm = mm;
  1482. sched_mm_cid_fork(tsk);
  1483. return 0;
  1484. }
  1485. static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
  1486. {
  1487. struct fs_struct *fs = current->fs;
  1488. if (clone_flags & CLONE_FS) {
  1489. /* tsk->fs is already what we want */
  1490. spin_lock(&fs->lock);
  1491. /* "users" and "in_exec" locked for check_unsafe_exec() */
  1492. if (fs->in_exec) {
  1493. spin_unlock(&fs->lock);
  1494. return -EAGAIN;
  1495. }
  1496. fs->users++;
  1497. spin_unlock(&fs->lock);
  1498. return 0;
  1499. }
  1500. tsk->fs = copy_fs_struct(fs);
  1501. if (!tsk->fs)
  1502. return -ENOMEM;
  1503. return 0;
  1504. }
  1505. static int copy_files(unsigned long clone_flags, struct task_struct *tsk,
  1506. int no_files)
  1507. {
  1508. struct files_struct *oldf, *newf;
  1509. /*
  1510. * A background process may not have any files ...
  1511. */
  1512. oldf = current->files;
  1513. if (!oldf)
  1514. return 0;
  1515. if (no_files) {
  1516. tsk->files = NULL;
  1517. return 0;
  1518. }
  1519. if (clone_flags & CLONE_FILES) {
  1520. atomic_inc(&oldf->count);
  1521. return 0;
  1522. }
  1523. newf = dup_fd(oldf, NULL);
  1524. if (IS_ERR(newf))
  1525. return PTR_ERR(newf);
  1526. tsk->files = newf;
  1527. return 0;
  1528. }
  1529. static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
  1530. {
  1531. struct sighand_struct *sig;
  1532. if (clone_flags & CLONE_SIGHAND) {
  1533. refcount_inc(&current->sighand->count);
  1534. return 0;
  1535. }
  1536. sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
  1537. RCU_INIT_POINTER(tsk->sighand, sig);
  1538. if (!sig)
  1539. return -ENOMEM;
  1540. refcount_set(&sig->count, 1);
  1541. spin_lock_irq(&current->sighand->siglock);
  1542. memcpy(sig->action, current->sighand->action, sizeof(sig->action));
  1543. spin_unlock_irq(&current->sighand->siglock);
  1544. /* Reset all signal handler not set to SIG_IGN to SIG_DFL. */
  1545. if (clone_flags & CLONE_CLEAR_SIGHAND)
  1546. flush_signal_handlers(tsk, 0);
  1547. return 0;
  1548. }
  1549. void __cleanup_sighand(struct sighand_struct *sighand)
  1550. {
  1551. if (refcount_dec_and_test(&sighand->count)) {
  1552. signalfd_cleanup(sighand);
  1553. /*
  1554. * sighand_cachep is SLAB_TYPESAFE_BY_RCU so we can free it
  1555. * without an RCU grace period, see __lock_task_sighand().
  1556. */
  1557. kmem_cache_free(sighand_cachep, sighand);
  1558. }
  1559. }
  1560. /*
  1561. * Initialize POSIX timer handling for a thread group.
  1562. */
  1563. static void posix_cpu_timers_init_group(struct signal_struct *sig)
  1564. {
  1565. struct posix_cputimers *pct = &sig->posix_cputimers;
  1566. unsigned long cpu_limit;
  1567. cpu_limit = READ_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
  1568. posix_cputimers_group_init(pct, cpu_limit);
  1569. }
  1570. static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
  1571. {
  1572. struct signal_struct *sig;
  1573. if (clone_flags & CLONE_THREAD)
  1574. return 0;
  1575. sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
  1576. tsk->signal = sig;
  1577. if (!sig)
  1578. return -ENOMEM;
  1579. sig->nr_threads = 1;
  1580. sig->quick_threads = 1;
  1581. atomic_set(&sig->live, 1);
  1582. refcount_set(&sig->sigcnt, 1);
  1583. /* list_add(thread_node, thread_head) without INIT_LIST_HEAD() */
  1584. sig->thread_head = (struct list_head)LIST_HEAD_INIT(tsk->thread_node);
  1585. tsk->thread_node = (struct list_head)LIST_HEAD_INIT(sig->thread_head);
  1586. init_waitqueue_head(&sig->wait_chldexit);
  1587. sig->curr_target = tsk;
  1588. init_sigpending(&sig->shared_pending);
  1589. INIT_HLIST_HEAD(&sig->multiprocess);
  1590. seqlock_init(&sig->stats_lock);
  1591. prev_cputime_init(&sig->prev_cputime);
  1592. #ifdef CONFIG_POSIX_TIMERS
  1593. INIT_HLIST_HEAD(&sig->posix_timers);
  1594. hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  1595. sig->real_timer.function = it_real_fn;
  1596. #endif
  1597. task_lock(current->group_leader);
  1598. memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
  1599. task_unlock(current->group_leader);
  1600. posix_cpu_timers_init_group(sig);
  1601. tty_audit_fork(sig);
  1602. sched_autogroup_fork(sig);
  1603. sig->oom_score_adj = current->signal->oom_score_adj;
  1604. sig->oom_score_adj_min = current->signal->oom_score_adj_min;
  1605. mutex_init(&sig->cred_guard_mutex);
  1606. init_rwsem(&sig->exec_update_lock);
  1607. return 0;
  1608. }
  1609. static void copy_seccomp(struct task_struct *p)
  1610. {
  1611. #ifdef CONFIG_SECCOMP
  1612. /*
  1613. * Must be called with sighand->lock held, which is common to
  1614. * all threads in the group. Holding cred_guard_mutex is not
  1615. * needed because this new task is not yet running and cannot
  1616. * be racing exec.
  1617. */
  1618. assert_spin_locked(&current->sighand->siglock);
  1619. /* Ref-count the new filter user, and assign it. */
  1620. get_seccomp_filter(current);
  1621. p->seccomp = current->seccomp;
  1622. /*
  1623. * Explicitly enable no_new_privs here in case it got set
  1624. * between the task_struct being duplicated and holding the
  1625. * sighand lock. The seccomp state and nnp must be in sync.
  1626. */
  1627. if (task_no_new_privs(current))
  1628. task_set_no_new_privs(p);
  1629. /*
  1630. * If the parent gained a seccomp mode after copying thread
  1631. * flags and between before we held the sighand lock, we have
  1632. * to manually enable the seccomp thread flag here.
  1633. */
  1634. if (p->seccomp.mode != SECCOMP_MODE_DISABLED)
  1635. set_task_syscall_work(p, SECCOMP);
  1636. #endif
  1637. }
  1638. SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
  1639. {
  1640. current->clear_child_tid = tidptr;
  1641. return task_pid_vnr(current);
  1642. }
  1643. static void rt_mutex_init_task(struct task_struct *p)
  1644. {
  1645. raw_spin_lock_init(&p->pi_lock);
  1646. #ifdef CONFIG_RT_MUTEXES
  1647. p->pi_waiters = RB_ROOT_CACHED;
  1648. p->pi_top_task = NULL;
  1649. p->pi_blocked_on = NULL;
  1650. #endif
  1651. }
  1652. static inline void init_task_pid_links(struct task_struct *task)
  1653. {
  1654. enum pid_type type;
  1655. for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type)
  1656. INIT_HLIST_NODE(&task->pid_links[type]);
  1657. }
  1658. static inline void
  1659. init_task_pid(struct task_struct *task, enum pid_type type, struct pid *pid)
  1660. {
  1661. if (type == PIDTYPE_PID)
  1662. task->thread_pid = pid;
  1663. else
  1664. task->signal->pids[type] = pid;
  1665. }
  1666. static inline void rcu_copy_process(struct task_struct *p)
  1667. {
  1668. #ifdef CONFIG_PREEMPT_RCU
  1669. p->rcu_read_lock_nesting = 0;
  1670. p->rcu_read_unlock_special.s = 0;
  1671. p->rcu_blocked_node = NULL;
  1672. INIT_LIST_HEAD(&p->rcu_node_entry);
  1673. #endif /* #ifdef CONFIG_PREEMPT_RCU */
  1674. #ifdef CONFIG_TASKS_RCU
  1675. p->rcu_tasks_holdout = false;
  1676. INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
  1677. p->rcu_tasks_idle_cpu = -1;
  1678. INIT_LIST_HEAD(&p->rcu_tasks_exit_list);
  1679. #endif /* #ifdef CONFIG_TASKS_RCU */
  1680. #ifdef CONFIG_TASKS_TRACE_RCU
  1681. p->trc_reader_nesting = 0;
  1682. p->trc_reader_special.s = 0;
  1683. INIT_LIST_HEAD(&p->trc_holdout_list);
  1684. INIT_LIST_HEAD(&p->trc_blkd_node);
  1685. #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
  1686. }
  1687. /**
  1688. * __pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
  1689. * @pid: the struct pid for which to create a pidfd
  1690. * @flags: flags of the new @pidfd
  1691. * @ret: Where to return the file for the pidfd.
  1692. *
  1693. * Allocate a new file that stashes @pid and reserve a new pidfd number in the
  1694. * caller's file descriptor table. The pidfd is reserved but not installed yet.
  1695. *
  1696. * The helper doesn't perform checks on @pid which makes it useful for pidfds
  1697. * created via CLONE_PIDFD where @pid has no task attached when the pidfd and
  1698. * pidfd file are prepared.
  1699. *
  1700. * If this function returns successfully the caller is responsible to either
  1701. * call fd_install() passing the returned pidfd and pidfd file as arguments in
  1702. * order to install the pidfd into its file descriptor table or they must use
  1703. * put_unused_fd() and fput() on the returned pidfd and pidfd file
  1704. * respectively.
  1705. *
  1706. * This function is useful when a pidfd must already be reserved but there
  1707. * might still be points of failure afterwards and the caller wants to ensure
  1708. * that no pidfd is leaked into its file descriptor table.
  1709. *
  1710. * Return: On success, a reserved pidfd is returned from the function and a new
  1711. * pidfd file is returned in the last argument to the function. On
  1712. * error, a negative error code is returned from the function and the
  1713. * last argument remains unchanged.
  1714. */
  1715. static int __pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
  1716. {
  1717. int pidfd;
  1718. struct file *pidfd_file;
  1719. pidfd = get_unused_fd_flags(O_CLOEXEC);
  1720. if (pidfd < 0)
  1721. return pidfd;
  1722. pidfd_file = pidfs_alloc_file(pid, flags | O_RDWR);
  1723. if (IS_ERR(pidfd_file)) {
  1724. put_unused_fd(pidfd);
  1725. return PTR_ERR(pidfd_file);
  1726. }
  1727. /*
  1728. * anon_inode_getfile() ignores everything outside of the
  1729. * O_ACCMODE | O_NONBLOCK mask, set PIDFD_THREAD manually.
  1730. */
  1731. pidfd_file->f_flags |= (flags & PIDFD_THREAD);
  1732. *ret = pidfd_file;
  1733. return pidfd;
  1734. }
  1735. /**
  1736. * pidfd_prepare - allocate a new pidfd_file and reserve a pidfd
  1737. * @pid: the struct pid for which to create a pidfd
  1738. * @flags: flags of the new @pidfd
  1739. * @ret: Where to return the pidfd.
  1740. *
  1741. * Allocate a new file that stashes @pid and reserve a new pidfd number in the
  1742. * caller's file descriptor table. The pidfd is reserved but not installed yet.
  1743. *
  1744. * The helper verifies that @pid is still in use, without PIDFD_THREAD the
  1745. * task identified by @pid must be a thread-group leader.
  1746. *
  1747. * If this function returns successfully the caller is responsible to either
  1748. * call fd_install() passing the returned pidfd and pidfd file as arguments in
  1749. * order to install the pidfd into its file descriptor table or they must use
  1750. * put_unused_fd() and fput() on the returned pidfd and pidfd file
  1751. * respectively.
  1752. *
  1753. * This function is useful when a pidfd must already be reserved but there
  1754. * might still be points of failure afterwards and the caller wants to ensure
  1755. * that no pidfd is leaked into its file descriptor table.
  1756. *
  1757. * Return: On success, a reserved pidfd is returned from the function and a new
  1758. * pidfd file is returned in the last argument to the function. On
  1759. * error, a negative error code is returned from the function and the
  1760. * last argument remains unchanged.
  1761. */
  1762. int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret)
  1763. {
  1764. bool thread = flags & PIDFD_THREAD;
  1765. if (!pid || !pid_has_task(pid, thread ? PIDTYPE_PID : PIDTYPE_TGID))
  1766. return -EINVAL;
  1767. return __pidfd_prepare(pid, flags, ret);
  1768. }
  1769. static void __delayed_free_task(struct rcu_head *rhp)
  1770. {
  1771. struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
  1772. free_task(tsk);
  1773. }
  1774. static __always_inline void delayed_free_task(struct task_struct *tsk)
  1775. {
  1776. if (IS_ENABLED(CONFIG_MEMCG))
  1777. call_rcu(&tsk->rcu, __delayed_free_task);
  1778. else
  1779. free_task(tsk);
  1780. }
  1781. static void copy_oom_score_adj(u64 clone_flags, struct task_struct *tsk)
  1782. {
  1783. /* Skip if kernel thread */
  1784. if (!tsk->mm)
  1785. return;
  1786. /* Skip if spawning a thread or using vfork */
  1787. if ((clone_flags & (CLONE_VM | CLONE_THREAD | CLONE_VFORK)) != CLONE_VM)
  1788. return;
  1789. /* We need to synchronize with __set_oom_adj */
  1790. mutex_lock(&oom_adj_mutex);
  1791. set_bit(MMF_MULTIPROCESS, &tsk->mm->flags);
  1792. /* Update the values in case they were changed after copy_signal */
  1793. tsk->signal->oom_score_adj = current->signal->oom_score_adj;
  1794. tsk->signal->oom_score_adj_min = current->signal->oom_score_adj_min;
  1795. mutex_unlock(&oom_adj_mutex);
  1796. }
  1797. #ifdef CONFIG_RV
  1798. static void rv_task_fork(struct task_struct *p)
  1799. {
  1800. int i;
  1801. for (i = 0; i < RV_PER_TASK_MONITORS; i++)
  1802. p->rv[i].da_mon.monitoring = false;
  1803. }
  1804. #else
  1805. #define rv_task_fork(p) do {} while (0)
  1806. #endif
  1807. /*
  1808. * This creates a new process as a copy of the old one,
  1809. * but does not actually start it yet.
  1810. *
  1811. * It copies the registers, and all the appropriate
  1812. * parts of the process environment (as per the clone
  1813. * flags). The actual kick-off is left to the caller.
  1814. */
  1815. __latent_entropy struct task_struct *copy_process(
  1816. struct pid *pid,
  1817. int trace,
  1818. int node,
  1819. struct kernel_clone_args *args)
  1820. {
  1821. int pidfd = -1, retval;
  1822. struct task_struct *p;
  1823. struct multiprocess_signals delayed;
  1824. struct file *pidfile = NULL;
  1825. const u64 clone_flags = args->flags;
  1826. struct nsproxy *nsp = current->nsproxy;
  1827. /*
  1828. * Don't allow sharing the root directory with processes in a different
  1829. * namespace
  1830. */
  1831. if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
  1832. return ERR_PTR(-EINVAL);
  1833. if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS))
  1834. return ERR_PTR(-EINVAL);
  1835. /*
  1836. * Thread groups must share signals as well, and detached threads
  1837. * can only be started up within the thread group.
  1838. */
  1839. if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
  1840. return ERR_PTR(-EINVAL);
  1841. /*
  1842. * Shared signal handlers imply shared VM. By way of the above,
  1843. * thread groups also imply shared VM. Blocking this case allows
  1844. * for various simplifications in other code.
  1845. */
  1846. if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
  1847. return ERR_PTR(-EINVAL);
  1848. /*
  1849. * Siblings of global init remain as zombies on exit since they are
  1850. * not reaped by their parent (swapper). To solve this and to avoid
  1851. * multi-rooted process trees, prevent global and container-inits
  1852. * from creating siblings.
  1853. */
  1854. if ((clone_flags & CLONE_PARENT) &&
  1855. current->signal->flags & SIGNAL_UNKILLABLE)
  1856. return ERR_PTR(-EINVAL);
  1857. /*
  1858. * If the new process will be in a different pid or user namespace
  1859. * do not allow it to share a thread group with the forking task.
  1860. */
  1861. if (clone_flags & CLONE_THREAD) {
  1862. if ((clone_flags & (CLONE_NEWUSER | CLONE_NEWPID)) ||
  1863. (task_active_pid_ns(current) != nsp->pid_ns_for_children))
  1864. return ERR_PTR(-EINVAL);
  1865. }
  1866. if (clone_flags & CLONE_PIDFD) {
  1867. /*
  1868. * - CLONE_DETACHED is blocked so that we can potentially
  1869. * reuse it later for CLONE_PIDFD.
  1870. */
  1871. if (clone_flags & CLONE_DETACHED)
  1872. return ERR_PTR(-EINVAL);
  1873. }
  1874. /*
  1875. * Force any signals received before this point to be delivered
  1876. * before the fork happens. Collect up signals sent to multiple
  1877. * processes that happen during the fork and delay them so that
  1878. * they appear to happen after the fork.
  1879. */
  1880. sigemptyset(&delayed.signal);
  1881. INIT_HLIST_NODE(&delayed.node);
  1882. spin_lock_irq(&current->sighand->siglock);
  1883. if (!(clone_flags & CLONE_THREAD))
  1884. hlist_add_head(&delayed.node, &current->signal->multiprocess);
  1885. recalc_sigpending();
  1886. spin_unlock_irq(&current->sighand->siglock);
  1887. retval = -ERESTARTNOINTR;
  1888. if (task_sigpending(current))
  1889. goto fork_out;
  1890. retval = -ENOMEM;
  1891. p = dup_task_struct(current, node);
  1892. if (!p)
  1893. goto fork_out;
  1894. p->flags &= ~PF_KTHREAD;
  1895. if (args->kthread)
  1896. p->flags |= PF_KTHREAD;
  1897. if (args->user_worker) {
  1898. /*
  1899. * Mark us a user worker, and block any signal that isn't
  1900. * fatal or STOP
  1901. */
  1902. p->flags |= PF_USER_WORKER;
  1903. siginitsetinv(&p->blocked, sigmask(SIGKILL)|sigmask(SIGSTOP));
  1904. }
  1905. if (args->io_thread)
  1906. p->flags |= PF_IO_WORKER;
  1907. if (args->name)
  1908. strscpy_pad(p->comm, args->name, sizeof(p->comm));
  1909. p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? args->child_tid : NULL;
  1910. /*
  1911. * Clear TID on mm_release()?
  1912. */
  1913. p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? args->child_tid : NULL;
  1914. ftrace_graph_init_task(p);
  1915. rt_mutex_init_task(p);
  1916. lockdep_assert_irqs_enabled();
  1917. #ifdef CONFIG_PROVE_LOCKING
  1918. DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
  1919. #endif
  1920. retval = copy_creds(p, clone_flags);
  1921. if (retval < 0)
  1922. goto bad_fork_free;
  1923. retval = -EAGAIN;
  1924. if (is_rlimit_overlimit(task_ucounts(p), UCOUNT_RLIMIT_NPROC, rlimit(RLIMIT_NPROC))) {
  1925. if (p->real_cred->user != INIT_USER &&
  1926. !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN))
  1927. goto bad_fork_cleanup_count;
  1928. }
  1929. current->flags &= ~PF_NPROC_EXCEEDED;
  1930. /*
  1931. * If multiple threads are within copy_process(), then this check
  1932. * triggers too late. This doesn't hurt, the check is only there
  1933. * to stop root fork bombs.
  1934. */
  1935. retval = -EAGAIN;
  1936. if (data_race(nr_threads >= max_threads))
  1937. goto bad_fork_cleanup_count;
  1938. delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
  1939. p->flags &= ~(PF_SUPERPRIV | PF_WQ_WORKER | PF_IDLE | PF_NO_SETAFFINITY);
  1940. p->flags |= PF_FORKNOEXEC;
  1941. INIT_LIST_HEAD(&p->children);
  1942. INIT_LIST_HEAD(&p->sibling);
  1943. rcu_copy_process(p);
  1944. p->vfork_done = NULL;
  1945. spin_lock_init(&p->alloc_lock);
  1946. init_sigpending(&p->pending);
  1947. p->utime = p->stime = p->gtime = 0;
  1948. #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
  1949. p->utimescaled = p->stimescaled = 0;
  1950. #endif
  1951. prev_cputime_init(&p->prev_cputime);
  1952. #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
  1953. seqcount_init(&p->vtime.seqcount);
  1954. p->vtime.starttime = 0;
  1955. p->vtime.state = VTIME_INACTIVE;
  1956. #endif
  1957. #ifdef CONFIG_IO_URING
  1958. p->io_uring = NULL;
  1959. #endif
  1960. p->default_timer_slack_ns = current->timer_slack_ns;
  1961. #ifdef CONFIG_PSI
  1962. p->psi_flags = 0;
  1963. #endif
  1964. task_io_accounting_init(&p->ioac);
  1965. acct_clear_integrals(p);
  1966. posix_cputimers_init(&p->posix_cputimers);
  1967. tick_dep_init_task(p);
  1968. p->io_context = NULL;
  1969. audit_set_context(p, NULL);
  1970. cgroup_fork(p);
  1971. if (args->kthread) {
  1972. if (!set_kthread_struct(p))
  1973. goto bad_fork_cleanup_delayacct;
  1974. }
  1975. #ifdef CONFIG_NUMA
  1976. p->mempolicy = mpol_dup(p->mempolicy);
  1977. if (IS_ERR(p->mempolicy)) {
  1978. retval = PTR_ERR(p->mempolicy);
  1979. p->mempolicy = NULL;
  1980. goto bad_fork_cleanup_delayacct;
  1981. }
  1982. #endif
  1983. #ifdef CONFIG_CPUSETS
  1984. p->cpuset_mem_spread_rotor = NUMA_NO_NODE;
  1985. seqcount_spinlock_init(&p->mems_allowed_seq, &p->alloc_lock);
  1986. #endif
  1987. #ifdef CONFIG_TRACE_IRQFLAGS
  1988. memset(&p->irqtrace, 0, sizeof(p->irqtrace));
  1989. p->irqtrace.hardirq_disable_ip = _THIS_IP_;
  1990. p->irqtrace.softirq_enable_ip = _THIS_IP_;
  1991. p->softirqs_enabled = 1;
  1992. p->softirq_context = 0;
  1993. #endif
  1994. p->pagefault_disabled = 0;
  1995. #ifdef CONFIG_LOCKDEP
  1996. lockdep_init_task(p);
  1997. #endif
  1998. #ifdef CONFIG_DEBUG_MUTEXES
  1999. p->blocked_on = NULL; /* not blocked yet */
  2000. #endif
  2001. #ifdef CONFIG_BCACHE
  2002. p->sequential_io = 0;
  2003. p->sequential_io_avg = 0;
  2004. #endif
  2005. #ifdef CONFIG_BPF_SYSCALL
  2006. RCU_INIT_POINTER(p->bpf_storage, NULL);
  2007. p->bpf_ctx = NULL;
  2008. #endif
  2009. /* Perform scheduler related setup. Assign this task to a CPU. */
  2010. retval = sched_fork(clone_flags, p);
  2011. if (retval)
  2012. goto bad_fork_cleanup_policy;
  2013. retval = perf_event_init_task(p, clone_flags);
  2014. if (retval)
  2015. goto bad_fork_sched_cancel_fork;
  2016. retval = audit_alloc(p);
  2017. if (retval)
  2018. goto bad_fork_cleanup_perf;
  2019. /* copy all the process information */
  2020. shm_init_task(p);
  2021. retval = security_task_alloc(p, clone_flags);
  2022. if (retval)
  2023. goto bad_fork_cleanup_audit;
  2024. retval = copy_semundo(clone_flags, p);
  2025. if (retval)
  2026. goto bad_fork_cleanup_security;
  2027. retval = copy_files(clone_flags, p, args->no_files);
  2028. if (retval)
  2029. goto bad_fork_cleanup_semundo;
  2030. retval = copy_fs(clone_flags, p);
  2031. if (retval)
  2032. goto bad_fork_cleanup_files;
  2033. retval = copy_sighand(clone_flags, p);
  2034. if (retval)
  2035. goto bad_fork_cleanup_fs;
  2036. retval = copy_signal(clone_flags, p);
  2037. if (retval)
  2038. goto bad_fork_cleanup_sighand;
  2039. retval = copy_mm(clone_flags, p);
  2040. if (retval)
  2041. goto bad_fork_cleanup_signal;
  2042. retval = copy_namespaces(clone_flags, p);
  2043. if (retval)
  2044. goto bad_fork_cleanup_mm;
  2045. retval = copy_io(clone_flags, p);
  2046. if (retval)
  2047. goto bad_fork_cleanup_namespaces;
  2048. retval = copy_thread(p, args);
  2049. if (retval)
  2050. goto bad_fork_cleanup_io;
  2051. stackleak_task_init(p);
  2052. if (pid != &init_struct_pid) {
  2053. pid = alloc_pid(p->nsproxy->pid_ns_for_children, args->set_tid,
  2054. args->set_tid_size);
  2055. if (IS_ERR(pid)) {
  2056. retval = PTR_ERR(pid);
  2057. goto bad_fork_cleanup_thread;
  2058. }
  2059. }
  2060. /*
  2061. * This has to happen after we've potentially unshared the file
  2062. * descriptor table (so that the pidfd doesn't leak into the child
  2063. * if the fd table isn't shared).
  2064. */
  2065. if (clone_flags & CLONE_PIDFD) {
  2066. int flags = (clone_flags & CLONE_THREAD) ? PIDFD_THREAD : 0;
  2067. /* Note that no task has been attached to @pid yet. */
  2068. retval = __pidfd_prepare(pid, flags, &pidfile);
  2069. if (retval < 0)
  2070. goto bad_fork_free_pid;
  2071. pidfd = retval;
  2072. retval = put_user(pidfd, args->pidfd);
  2073. if (retval)
  2074. goto bad_fork_put_pidfd;
  2075. }
  2076. #ifdef CONFIG_BLOCK
  2077. p->plug = NULL;
  2078. #endif
  2079. futex_init_task(p);
  2080. /*
  2081. * sigaltstack should be cleared when sharing the same VM
  2082. */
  2083. if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
  2084. sas_ss_reset(p);
  2085. /*
  2086. * Syscall tracing and stepping should be turned off in the
  2087. * child regardless of CLONE_PTRACE.
  2088. */
  2089. user_disable_single_step(p);
  2090. clear_task_syscall_work(p, SYSCALL_TRACE);
  2091. #if defined(CONFIG_GENERIC_ENTRY) || defined(TIF_SYSCALL_EMU)
  2092. clear_task_syscall_work(p, SYSCALL_EMU);
  2093. #endif
  2094. clear_tsk_latency_tracing(p);
  2095. /* ok, now we should be set up.. */
  2096. p->pid = pid_nr(pid);
  2097. if (clone_flags & CLONE_THREAD) {
  2098. p->group_leader = current->group_leader;
  2099. p->tgid = current->tgid;
  2100. } else {
  2101. p->group_leader = p;
  2102. p->tgid = p->pid;
  2103. }
  2104. p->nr_dirtied = 0;
  2105. p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10);
  2106. p->dirty_paused_when = 0;
  2107. p->pdeath_signal = 0;
  2108. p->task_works = NULL;
  2109. clear_posix_cputimers_work(p);
  2110. #ifdef CONFIG_KRETPROBES
  2111. p->kretprobe_instances.first = NULL;
  2112. #endif
  2113. #ifdef CONFIG_RETHOOK
  2114. p->rethooks.first = NULL;
  2115. #endif
  2116. /*
  2117. * Ensure that the cgroup subsystem policies allow the new process to be
  2118. * forked. It should be noted that the new process's css_set can be changed
  2119. * between here and cgroup_post_fork() if an organisation operation is in
  2120. * progress.
  2121. */
  2122. retval = cgroup_can_fork(p, args);
  2123. if (retval)
  2124. goto bad_fork_put_pidfd;
  2125. /*
  2126. * Now that the cgroups are pinned, re-clone the parent cgroup and put
  2127. * the new task on the correct runqueue. All this *before* the task
  2128. * becomes visible.
  2129. *
  2130. * This isn't part of ->can_fork() because while the re-cloning is
  2131. * cgroup specific, it unconditionally needs to place the task on a
  2132. * runqueue.
  2133. */
  2134. retval = sched_cgroup_fork(p, args);
  2135. if (retval)
  2136. goto bad_fork_cancel_cgroup;
  2137. /*
  2138. * From this point on we must avoid any synchronous user-space
  2139. * communication until we take the tasklist-lock. In particular, we do
  2140. * not want user-space to be able to predict the process start-time by
  2141. * stalling fork(2) after we recorded the start_time but before it is
  2142. * visible to the system.
  2143. */
  2144. p->start_time = ktime_get_ns();
  2145. p->start_boottime = ktime_get_boottime_ns();
  2146. /*
  2147. * Make it visible to the rest of the system, but dont wake it up yet.
  2148. * Need tasklist lock for parent etc handling!
  2149. */
  2150. write_lock_irq(&tasklist_lock);
  2151. /* CLONE_PARENT re-uses the old parent */
  2152. if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
  2153. p->real_parent = current->real_parent;
  2154. p->parent_exec_id = current->parent_exec_id;
  2155. if (clone_flags & CLONE_THREAD)
  2156. p->exit_signal = -1;
  2157. else
  2158. p->exit_signal = current->group_leader->exit_signal;
  2159. } else {
  2160. p->real_parent = current;
  2161. p->parent_exec_id = current->self_exec_id;
  2162. p->exit_signal = args->exit_signal;
  2163. }
  2164. klp_copy_process(p);
  2165. sched_core_fork(p);
  2166. spin_lock(&current->sighand->siglock);
  2167. rv_task_fork(p);
  2168. rseq_fork(p, clone_flags);
  2169. /* Don't start children in a dying pid namespace */
  2170. if (unlikely(!(ns_of_pid(pid)->pid_allocated & PIDNS_ADDING))) {
  2171. retval = -ENOMEM;
  2172. goto bad_fork_core_free;
  2173. }
  2174. /* Let kill terminate clone/fork in the middle */
  2175. if (fatal_signal_pending(current)) {
  2176. retval = -EINTR;
  2177. goto bad_fork_core_free;
  2178. }
  2179. /* No more failure paths after this point. */
  2180. /*
  2181. * Copy seccomp details explicitly here, in case they were changed
  2182. * before holding sighand lock.
  2183. */
  2184. copy_seccomp(p);
  2185. init_task_pid_links(p);
  2186. if (likely(p->pid)) {
  2187. ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace);
  2188. init_task_pid(p, PIDTYPE_PID, pid);
  2189. if (thread_group_leader(p)) {
  2190. init_task_pid(p, PIDTYPE_TGID, pid);
  2191. init_task_pid(p, PIDTYPE_PGID, task_pgrp(current));
  2192. init_task_pid(p, PIDTYPE_SID, task_session(current));
  2193. if (is_child_reaper(pid)) {
  2194. ns_of_pid(pid)->child_reaper = p;
  2195. p->signal->flags |= SIGNAL_UNKILLABLE;
  2196. }
  2197. p->signal->shared_pending.signal = delayed.signal;
  2198. p->signal->tty = tty_kref_get(current->signal->tty);
  2199. /*
  2200. * Inherit has_child_subreaper flag under the same
  2201. * tasklist_lock with adding child to the process tree
  2202. * for propagate_has_child_subreaper optimization.
  2203. */
  2204. p->signal->has_child_subreaper = p->real_parent->signal->has_child_subreaper ||
  2205. p->real_parent->signal->is_child_subreaper;
  2206. list_add_tail(&p->sibling, &p->real_parent->children);
  2207. list_add_tail_rcu(&p->tasks, &init_task.tasks);
  2208. attach_pid(p, PIDTYPE_TGID);
  2209. attach_pid(p, PIDTYPE_PGID);
  2210. attach_pid(p, PIDTYPE_SID);
  2211. __this_cpu_inc(process_counts);
  2212. } else {
  2213. current->signal->nr_threads++;
  2214. current->signal->quick_threads++;
  2215. atomic_inc(&current->signal->live);
  2216. refcount_inc(&current->signal->sigcnt);
  2217. task_join_group_stop(p);
  2218. list_add_tail_rcu(&p->thread_node,
  2219. &p->signal->thread_head);
  2220. }
  2221. attach_pid(p, PIDTYPE_PID);
  2222. nr_threads++;
  2223. }
  2224. total_forks++;
  2225. hlist_del_init(&delayed.node);
  2226. spin_unlock(&current->sighand->siglock);
  2227. syscall_tracepoint_update(p);
  2228. write_unlock_irq(&tasklist_lock);
  2229. if (pidfile)
  2230. fd_install(pidfd, pidfile);
  2231. proc_fork_connector(p);
  2232. sched_post_fork(p);
  2233. cgroup_post_fork(p, args);
  2234. perf_event_fork(p);
  2235. trace_task_newtask(p, clone_flags);
  2236. uprobe_copy_process(p, clone_flags);
  2237. user_events_fork(p, clone_flags);
  2238. copy_oom_score_adj(clone_flags, p);
  2239. return p;
  2240. bad_fork_core_free:
  2241. sched_core_free(p);
  2242. spin_unlock(&current->sighand->siglock);
  2243. write_unlock_irq(&tasklist_lock);
  2244. bad_fork_cancel_cgroup:
  2245. cgroup_cancel_fork(p, args);
  2246. bad_fork_put_pidfd:
  2247. if (clone_flags & CLONE_PIDFD) {
  2248. fput(pidfile);
  2249. put_unused_fd(pidfd);
  2250. }
  2251. bad_fork_free_pid:
  2252. if (pid != &init_struct_pid)
  2253. free_pid(pid);
  2254. bad_fork_cleanup_thread:
  2255. exit_thread(p);
  2256. bad_fork_cleanup_io:
  2257. if (p->io_context)
  2258. exit_io_context(p);
  2259. bad_fork_cleanup_namespaces:
  2260. exit_task_namespaces(p);
  2261. bad_fork_cleanup_mm:
  2262. if (p->mm) {
  2263. mm_clear_owner(p->mm, p);
  2264. mmput(p->mm);
  2265. }
  2266. bad_fork_cleanup_signal:
  2267. if (!(clone_flags & CLONE_THREAD))
  2268. free_signal_struct(p->signal);
  2269. bad_fork_cleanup_sighand:
  2270. __cleanup_sighand(p->sighand);
  2271. bad_fork_cleanup_fs:
  2272. exit_fs(p); /* blocking */
  2273. bad_fork_cleanup_files:
  2274. exit_files(p); /* blocking */
  2275. bad_fork_cleanup_semundo:
  2276. exit_sem(p);
  2277. bad_fork_cleanup_security:
  2278. security_task_free(p);
  2279. bad_fork_cleanup_audit:
  2280. audit_free(p);
  2281. bad_fork_cleanup_perf:
  2282. perf_event_free_task(p);
  2283. bad_fork_sched_cancel_fork:
  2284. sched_cancel_fork(p);
  2285. bad_fork_cleanup_policy:
  2286. lockdep_free_task(p);
  2287. #ifdef CONFIG_NUMA
  2288. mpol_put(p->mempolicy);
  2289. #endif
  2290. bad_fork_cleanup_delayacct:
  2291. delayacct_tsk_free(p);
  2292. bad_fork_cleanup_count:
  2293. dec_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
  2294. exit_creds(p);
  2295. bad_fork_free:
  2296. WRITE_ONCE(p->__state, TASK_DEAD);
  2297. exit_task_stack_account(p);
  2298. put_task_stack(p);
  2299. delayed_free_task(p);
  2300. fork_out:
  2301. spin_lock_irq(&current->sighand->siglock);
  2302. hlist_del_init(&delayed.node);
  2303. spin_unlock_irq(&current->sighand->siglock);
  2304. return ERR_PTR(retval);
  2305. }
  2306. static inline void init_idle_pids(struct task_struct *idle)
  2307. {
  2308. enum pid_type type;
  2309. for (type = PIDTYPE_PID; type < PIDTYPE_MAX; ++type) {
  2310. INIT_HLIST_NODE(&idle->pid_links[type]); /* not really needed */
  2311. init_task_pid(idle, type, &init_struct_pid);
  2312. }
  2313. }
  2314. static int idle_dummy(void *dummy)
  2315. {
  2316. /* This function is never called */
  2317. return 0;
  2318. }
  2319. struct task_struct * __init fork_idle(int cpu)
  2320. {
  2321. struct task_struct *task;
  2322. struct kernel_clone_args args = {
  2323. .flags = CLONE_VM,
  2324. .fn = &idle_dummy,
  2325. .fn_arg = NULL,
  2326. .kthread = 1,
  2327. .idle = 1,
  2328. };
  2329. task = copy_process(&init_struct_pid, 0, cpu_to_node(cpu), &args);
  2330. if (!IS_ERR(task)) {
  2331. init_idle_pids(task);
  2332. init_idle(task, cpu);
  2333. }
  2334. return task;
  2335. }
  2336. /*
  2337. * This is like kernel_clone(), but shaved down and tailored to just
  2338. * creating io_uring workers. It returns a created task, or an error pointer.
  2339. * The returned task is inactive, and the caller must fire it up through
  2340. * wake_up_new_task(p). All signals are blocked in the created task.
  2341. */
  2342. struct task_struct *create_io_thread(int (*fn)(void *), void *arg, int node)
  2343. {
  2344. unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
  2345. CLONE_IO;
  2346. struct kernel_clone_args args = {
  2347. .flags = ((lower_32_bits(flags) | CLONE_VM |
  2348. CLONE_UNTRACED) & ~CSIGNAL),
  2349. .exit_signal = (lower_32_bits(flags) & CSIGNAL),
  2350. .fn = fn,
  2351. .fn_arg = arg,
  2352. .io_thread = 1,
  2353. .user_worker = 1,
  2354. };
  2355. return copy_process(NULL, 0, node, &args);
  2356. }
  2357. /*
  2358. * Ok, this is the main fork-routine.
  2359. *
  2360. * It copies the process, and if successful kick-starts
  2361. * it and waits for it to finish using the VM if required.
  2362. *
  2363. * args->exit_signal is expected to be checked for sanity by the caller.
  2364. */
  2365. pid_t kernel_clone(struct kernel_clone_args *args)
  2366. {
  2367. u64 clone_flags = args->flags;
  2368. struct completion vfork;
  2369. struct pid *pid;
  2370. struct task_struct *p;
  2371. int trace = 0;
  2372. pid_t nr;
  2373. /*
  2374. * For legacy clone() calls, CLONE_PIDFD uses the parent_tid argument
  2375. * to return the pidfd. Hence, CLONE_PIDFD and CLONE_PARENT_SETTID are
  2376. * mutually exclusive. With clone3() CLONE_PIDFD has grown a separate
  2377. * field in struct clone_args and it still doesn't make sense to have
  2378. * them both point at the same memory location. Performing this check
  2379. * here has the advantage that we don't need to have a separate helper
  2380. * to check for legacy clone().
  2381. */
  2382. if ((clone_flags & CLONE_PIDFD) &&
  2383. (clone_flags & CLONE_PARENT_SETTID) &&
  2384. (args->pidfd == args->parent_tid))
  2385. return -EINVAL;
  2386. /*
  2387. * Determine whether and which event to report to ptracer. When
  2388. * called from kernel_thread or CLONE_UNTRACED is explicitly
  2389. * requested, no event is reported; otherwise, report if the event
  2390. * for the type of forking is enabled.
  2391. */
  2392. if (!(clone_flags & CLONE_UNTRACED)) {
  2393. if (clone_flags & CLONE_VFORK)
  2394. trace = PTRACE_EVENT_VFORK;
  2395. else if (args->exit_signal != SIGCHLD)
  2396. trace = PTRACE_EVENT_CLONE;
  2397. else
  2398. trace = PTRACE_EVENT_FORK;
  2399. if (likely(!ptrace_event_enabled(current, trace)))
  2400. trace = 0;
  2401. }
  2402. p = copy_process(NULL, trace, NUMA_NO_NODE, args);
  2403. add_latent_entropy();
  2404. if (IS_ERR(p))
  2405. return PTR_ERR(p);
  2406. /*
  2407. * Do this prior waking up the new thread - the thread pointer
  2408. * might get invalid after that point, if the thread exits quickly.
  2409. */
  2410. trace_sched_process_fork(current, p);
  2411. pid = get_task_pid(p, PIDTYPE_PID);
  2412. nr = pid_vnr(pid);
  2413. if (clone_flags & CLONE_PARENT_SETTID)
  2414. put_user(nr, args->parent_tid);
  2415. if (clone_flags & CLONE_VFORK) {
  2416. p->vfork_done = &vfork;
  2417. init_completion(&vfork);
  2418. get_task_struct(p);
  2419. }
  2420. if (IS_ENABLED(CONFIG_LRU_GEN_WALKS_MMU) && !(clone_flags & CLONE_VM)) {
  2421. /* lock the task to synchronize with memcg migration */
  2422. task_lock(p);
  2423. lru_gen_add_mm(p->mm);
  2424. task_unlock(p);
  2425. }
  2426. wake_up_new_task(p);
  2427. /* forking complete and child started to run, tell ptracer */
  2428. if (unlikely(trace))
  2429. ptrace_event_pid(trace, pid);
  2430. if (clone_flags & CLONE_VFORK) {
  2431. if (!wait_for_vfork_done(p, &vfork))
  2432. ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid);
  2433. }
  2434. put_pid(pid);
  2435. return nr;
  2436. }
  2437. /*
  2438. * Create a kernel thread.
  2439. */
  2440. pid_t kernel_thread(int (*fn)(void *), void *arg, const char *name,
  2441. unsigned long flags)
  2442. {
  2443. struct kernel_clone_args args = {
  2444. .flags = ((lower_32_bits(flags) | CLONE_VM |
  2445. CLONE_UNTRACED) & ~CSIGNAL),
  2446. .exit_signal = (lower_32_bits(flags) & CSIGNAL),
  2447. .fn = fn,
  2448. .fn_arg = arg,
  2449. .name = name,
  2450. .kthread = 1,
  2451. };
  2452. return kernel_clone(&args);
  2453. }
  2454. /*
  2455. * Create a user mode thread.
  2456. */
  2457. pid_t user_mode_thread(int (*fn)(void *), void *arg, unsigned long flags)
  2458. {
  2459. struct kernel_clone_args args = {
  2460. .flags = ((lower_32_bits(flags) | CLONE_VM |
  2461. CLONE_UNTRACED) & ~CSIGNAL),
  2462. .exit_signal = (lower_32_bits(flags) & CSIGNAL),
  2463. .fn = fn,
  2464. .fn_arg = arg,
  2465. };
  2466. return kernel_clone(&args);
  2467. }
  2468. #ifdef __ARCH_WANT_SYS_FORK
  2469. SYSCALL_DEFINE0(fork)
  2470. {
  2471. #ifdef CONFIG_MMU
  2472. struct kernel_clone_args args = {
  2473. .exit_signal = SIGCHLD,
  2474. };
  2475. return kernel_clone(&args);
  2476. #else
  2477. /* can not support in nommu mode */
  2478. return -EINVAL;
  2479. #endif
  2480. }
  2481. #endif
  2482. #ifdef __ARCH_WANT_SYS_VFORK
  2483. SYSCALL_DEFINE0(vfork)
  2484. {
  2485. struct kernel_clone_args args = {
  2486. .flags = CLONE_VFORK | CLONE_VM,
  2487. .exit_signal = SIGCHLD,
  2488. };
  2489. return kernel_clone(&args);
  2490. }
  2491. #endif
  2492. #ifdef __ARCH_WANT_SYS_CLONE
  2493. #ifdef CONFIG_CLONE_BACKWARDS
  2494. SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
  2495. int __user *, parent_tidptr,
  2496. unsigned long, tls,
  2497. int __user *, child_tidptr)
  2498. #elif defined(CONFIG_CLONE_BACKWARDS2)
  2499. SYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,
  2500. int __user *, parent_tidptr,
  2501. int __user *, child_tidptr,
  2502. unsigned long, tls)
  2503. #elif defined(CONFIG_CLONE_BACKWARDS3)
  2504. SYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,
  2505. int, stack_size,
  2506. int __user *, parent_tidptr,
  2507. int __user *, child_tidptr,
  2508. unsigned long, tls)
  2509. #else
  2510. SYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,
  2511. int __user *, parent_tidptr,
  2512. int __user *, child_tidptr,
  2513. unsigned long, tls)
  2514. #endif
  2515. {
  2516. struct kernel_clone_args args = {
  2517. .flags = (lower_32_bits(clone_flags) & ~CSIGNAL),
  2518. .pidfd = parent_tidptr,
  2519. .child_tid = child_tidptr,
  2520. .parent_tid = parent_tidptr,
  2521. .exit_signal = (lower_32_bits(clone_flags) & CSIGNAL),
  2522. .stack = newsp,
  2523. .tls = tls,
  2524. };
  2525. return kernel_clone(&args);
  2526. }
  2527. #endif
  2528. noinline static int copy_clone_args_from_user(struct kernel_clone_args *kargs,
  2529. struct clone_args __user *uargs,
  2530. size_t usize)
  2531. {
  2532. int err;
  2533. struct clone_args args;
  2534. pid_t *kset_tid = kargs->set_tid;
  2535. BUILD_BUG_ON(offsetofend(struct clone_args, tls) !=
  2536. CLONE_ARGS_SIZE_VER0);
  2537. BUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=
  2538. CLONE_ARGS_SIZE_VER1);
  2539. BUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=
  2540. CLONE_ARGS_SIZE_VER2);
  2541. BUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);
  2542. if (unlikely(usize > PAGE_SIZE))
  2543. return -E2BIG;
  2544. if (unlikely(usize < CLONE_ARGS_SIZE_VER0))
  2545. return -EINVAL;
  2546. err = copy_struct_from_user(&args, sizeof(args), uargs, usize);
  2547. if (err)
  2548. return err;
  2549. if (unlikely(args.set_tid_size > MAX_PID_NS_LEVEL))
  2550. return -EINVAL;
  2551. if (unlikely(!args.set_tid && args.set_tid_size > 0))
  2552. return -EINVAL;
  2553. if (unlikely(args.set_tid && args.set_tid_size == 0))
  2554. return -EINVAL;
  2555. /*
  2556. * Verify that higher 32bits of exit_signal are unset and that
  2557. * it is a valid signal
  2558. */
  2559. if (unlikely((args.exit_signal & ~((u64)CSIGNAL)) ||
  2560. !valid_signal(args.exit_signal)))
  2561. return -EINVAL;
  2562. if ((args.flags & CLONE_INTO_CGROUP) &&
  2563. (args.cgroup > INT_MAX || usize < CLONE_ARGS_SIZE_VER2))
  2564. return -EINVAL;
  2565. *kargs = (struct kernel_clone_args){
  2566. .flags = args.flags,
  2567. .pidfd = u64_to_user_ptr(args.pidfd),
  2568. .child_tid = u64_to_user_ptr(args.child_tid),
  2569. .parent_tid = u64_to_user_ptr(args.parent_tid),
  2570. .exit_signal = args.exit_signal,
  2571. .stack = args.stack,
  2572. .stack_size = args.stack_size,
  2573. .tls = args.tls,
  2574. .set_tid_size = args.set_tid_size,
  2575. .cgroup = args.cgroup,
  2576. };
  2577. if (args.set_tid &&
  2578. copy_from_user(kset_tid, u64_to_user_ptr(args.set_tid),
  2579. (kargs->set_tid_size * sizeof(pid_t))))
  2580. return -EFAULT;
  2581. kargs->set_tid = kset_tid;
  2582. return 0;
  2583. }
  2584. /**
  2585. * clone3_stack_valid - check and prepare stack
  2586. * @kargs: kernel clone args
  2587. *
  2588. * Verify that the stack arguments userspace gave us are sane.
  2589. * In addition, set the stack direction for userspace since it's easy for us to
  2590. * determine.
  2591. */
  2592. static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)
  2593. {
  2594. if (kargs->stack == 0) {
  2595. if (kargs->stack_size > 0)
  2596. return false;
  2597. } else {
  2598. if (kargs->stack_size == 0)
  2599. return false;
  2600. if (!access_ok((void __user *)kargs->stack, kargs->stack_size))
  2601. return false;
  2602. #if !defined(CONFIG_STACK_GROWSUP)
  2603. kargs->stack += kargs->stack_size;
  2604. #endif
  2605. }
  2606. return true;
  2607. }
  2608. static bool clone3_args_valid(struct kernel_clone_args *kargs)
  2609. {
  2610. /* Verify that no unknown flags are passed along. */
  2611. if (kargs->flags &
  2612. ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP))
  2613. return false;
  2614. /*
  2615. * - make the CLONE_DETACHED bit reusable for clone3
  2616. * - make the CSIGNAL bits reusable for clone3
  2617. */
  2618. if (kargs->flags & (CLONE_DETACHED | (CSIGNAL & (~CLONE_NEWTIME))))
  2619. return false;
  2620. if ((kargs->flags & (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND)) ==
  2621. (CLONE_SIGHAND | CLONE_CLEAR_SIGHAND))
  2622. return false;
  2623. if ((kargs->flags & (CLONE_THREAD | CLONE_PARENT)) &&
  2624. kargs->exit_signal)
  2625. return false;
  2626. if (!clone3_stack_valid(kargs))
  2627. return false;
  2628. return true;
  2629. }
  2630. /**
  2631. * sys_clone3 - create a new process with specific properties
  2632. * @uargs: argument structure
  2633. * @size: size of @uargs
  2634. *
  2635. * clone3() is the extensible successor to clone()/clone2().
  2636. * It takes a struct as argument that is versioned by its size.
  2637. *
  2638. * Return: On success, a positive PID for the child process.
  2639. * On error, a negative errno number.
  2640. */
  2641. SYSCALL_DEFINE2(clone3, struct clone_args __user *, uargs, size_t, size)
  2642. {
  2643. int err;
  2644. struct kernel_clone_args kargs;
  2645. pid_t set_tid[MAX_PID_NS_LEVEL];
  2646. #ifdef __ARCH_BROKEN_SYS_CLONE3
  2647. #warning clone3() entry point is missing, please fix
  2648. return -ENOSYS;
  2649. #endif
  2650. kargs.set_tid = set_tid;
  2651. err = copy_clone_args_from_user(&kargs, uargs, size);
  2652. if (err)
  2653. return err;
  2654. if (!clone3_args_valid(&kargs))
  2655. return -EINVAL;
  2656. return kernel_clone(&kargs);
  2657. }
  2658. void walk_process_tree(struct task_struct *top, proc_visitor visitor, void *data)
  2659. {
  2660. struct task_struct *leader, *parent, *child;
  2661. int res;
  2662. read_lock(&tasklist_lock);
  2663. leader = top = top->group_leader;
  2664. down:
  2665. for_each_thread(leader, parent) {
  2666. list_for_each_entry(child, &parent->children, sibling) {
  2667. res = visitor(child, data);
  2668. if (res) {
  2669. if (res < 0)
  2670. goto out;
  2671. leader = child;
  2672. goto down;
  2673. }
  2674. up:
  2675. ;
  2676. }
  2677. }
  2678. if (leader != top) {
  2679. child = leader;
  2680. parent = child->real_parent;
  2681. leader = parent->group_leader;
  2682. goto up;
  2683. }
  2684. out:
  2685. read_unlock(&tasklist_lock);
  2686. }
  2687. #ifndef ARCH_MIN_MMSTRUCT_ALIGN
  2688. #define ARCH_MIN_MMSTRUCT_ALIGN 0
  2689. #endif
  2690. static void sighand_ctor(void *data)
  2691. {
  2692. struct sighand_struct *sighand = data;
  2693. spin_lock_init(&sighand->siglock);
  2694. init_waitqueue_head(&sighand->signalfd_wqh);
  2695. }
  2696. void __init mm_cache_init(void)
  2697. {
  2698. unsigned int mm_size;
  2699. /*
  2700. * The mm_cpumask is located at the end of mm_struct, and is
  2701. * dynamically sized based on the maximum CPU number this system
  2702. * can have, taking hotplug into account (nr_cpu_ids).
  2703. */
  2704. mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
  2705. mm_cachep = kmem_cache_create_usercopy("mm_struct",
  2706. mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
  2707. SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
  2708. offsetof(struct mm_struct, saved_auxv),
  2709. sizeof_field(struct mm_struct, saved_auxv),
  2710. NULL);
  2711. }
  2712. void __init proc_caches_init(void)
  2713. {
  2714. sighand_cachep = kmem_cache_create("sighand_cache",
  2715. sizeof(struct sighand_struct), 0,
  2716. SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_TYPESAFE_BY_RCU|
  2717. SLAB_ACCOUNT, sighand_ctor);
  2718. signal_cachep = kmem_cache_create("signal_cache",
  2719. sizeof(struct signal_struct), 0,
  2720. SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
  2721. NULL);
  2722. files_cachep = kmem_cache_create("files_cache",
  2723. sizeof(struct files_struct), 0,
  2724. SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
  2725. NULL);
  2726. fs_cachep = kmem_cache_create("fs_cache",
  2727. sizeof(struct fs_struct), 0,
  2728. SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT,
  2729. NULL);
  2730. vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC|SLAB_ACCOUNT);
  2731. #ifdef CONFIG_PER_VMA_LOCK
  2732. vma_lock_cachep = KMEM_CACHE(vma_lock, SLAB_PANIC|SLAB_ACCOUNT);
  2733. #endif
  2734. mmap_init();
  2735. nsproxy_cache_init();
  2736. }
  2737. /*
  2738. * Check constraints on flags passed to the unshare system call.
  2739. */
  2740. static int check_unshare_flags(unsigned long unshare_flags)
  2741. {
  2742. if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
  2743. CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
  2744. CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET|
  2745. CLONE_NEWUSER|CLONE_NEWPID|CLONE_NEWCGROUP|
  2746. CLONE_NEWTIME))
  2747. return -EINVAL;
  2748. /*
  2749. * Not implemented, but pretend it works if there is nothing
  2750. * to unshare. Note that unsharing the address space or the
  2751. * signal handlers also need to unshare the signal queues (aka
  2752. * CLONE_THREAD).
  2753. */
  2754. if (unshare_flags & (CLONE_THREAD | CLONE_SIGHAND | CLONE_VM)) {
  2755. if (!thread_group_empty(current))
  2756. return -EINVAL;
  2757. }
  2758. if (unshare_flags & (CLONE_SIGHAND | CLONE_VM)) {
  2759. if (refcount_read(&current->sighand->count) > 1)
  2760. return -EINVAL;
  2761. }
  2762. if (unshare_flags & CLONE_VM) {
  2763. if (!current_is_single_threaded())
  2764. return -EINVAL;
  2765. }
  2766. return 0;
  2767. }
  2768. /*
  2769. * Unshare the filesystem structure if it is being shared
  2770. */
  2771. static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
  2772. {
  2773. struct fs_struct *fs = current->fs;
  2774. if (!(unshare_flags & CLONE_FS) || !fs)
  2775. return 0;
  2776. /* don't need lock here; in the worst case we'll do useless copy */
  2777. if (fs->users == 1)
  2778. return 0;
  2779. *new_fsp = copy_fs_struct(fs);
  2780. if (!*new_fsp)
  2781. return -ENOMEM;
  2782. return 0;
  2783. }
  2784. /*
  2785. * Unshare file descriptor table if it is being shared
  2786. */
  2787. static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
  2788. {
  2789. struct files_struct *fd = current->files;
  2790. if ((unshare_flags & CLONE_FILES) &&
  2791. (fd && atomic_read(&fd->count) > 1)) {
  2792. fd = dup_fd(fd, NULL);
  2793. if (IS_ERR(fd))
  2794. return PTR_ERR(fd);
  2795. *new_fdp = fd;
  2796. }
  2797. return 0;
  2798. }
  2799. /*
  2800. * unshare allows a process to 'unshare' part of the process
  2801. * context which was originally shared using clone. copy_*
  2802. * functions used by kernel_clone() cannot be used here directly
  2803. * because they modify an inactive task_struct that is being
  2804. * constructed. Here we are modifying the current, active,
  2805. * task_struct.
  2806. */
  2807. int ksys_unshare(unsigned long unshare_flags)
  2808. {
  2809. struct fs_struct *fs, *new_fs = NULL;
  2810. struct files_struct *new_fd = NULL;
  2811. struct cred *new_cred = NULL;
  2812. struct nsproxy *new_nsproxy = NULL;
  2813. int do_sysvsem = 0;
  2814. int err;
  2815. /*
  2816. * If unsharing a user namespace must also unshare the thread group
  2817. * and unshare the filesystem root and working directories.
  2818. */
  2819. if (unshare_flags & CLONE_NEWUSER)
  2820. unshare_flags |= CLONE_THREAD | CLONE_FS;
  2821. /*
  2822. * If unsharing vm, must also unshare signal handlers.
  2823. */
  2824. if (unshare_flags & CLONE_VM)
  2825. unshare_flags |= CLONE_SIGHAND;
  2826. /*
  2827. * If unsharing a signal handlers, must also unshare the signal queues.
  2828. */
  2829. if (unshare_flags & CLONE_SIGHAND)
  2830. unshare_flags |= CLONE_THREAD;
  2831. /*
  2832. * If unsharing namespace, must also unshare filesystem information.
  2833. */
  2834. if (unshare_flags & CLONE_NEWNS)
  2835. unshare_flags |= CLONE_FS;
  2836. err = check_unshare_flags(unshare_flags);
  2837. if (err)
  2838. goto bad_unshare_out;
  2839. /*
  2840. * CLONE_NEWIPC must also detach from the undolist: after switching
  2841. * to a new ipc namespace, the semaphore arrays from the old
  2842. * namespace are unreachable.
  2843. */
  2844. if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
  2845. do_sysvsem = 1;
  2846. err = unshare_fs(unshare_flags, &new_fs);
  2847. if (err)
  2848. goto bad_unshare_out;
  2849. err = unshare_fd(unshare_flags, &new_fd);
  2850. if (err)
  2851. goto bad_unshare_cleanup_fs;
  2852. err = unshare_userns(unshare_flags, &new_cred);
  2853. if (err)
  2854. goto bad_unshare_cleanup_fd;
  2855. err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
  2856. new_cred, new_fs);
  2857. if (err)
  2858. goto bad_unshare_cleanup_cred;
  2859. if (new_cred) {
  2860. err = set_cred_ucounts(new_cred);
  2861. if (err)
  2862. goto bad_unshare_cleanup_cred;
  2863. }
  2864. if (new_fs || new_fd || do_sysvsem || new_cred || new_nsproxy) {
  2865. if (do_sysvsem) {
  2866. /*
  2867. * CLONE_SYSVSEM is equivalent to sys_exit().
  2868. */
  2869. exit_sem(current);
  2870. }
  2871. if (unshare_flags & CLONE_NEWIPC) {
  2872. /* Orphan segments in old ns (see sem above). */
  2873. exit_shm(current);
  2874. shm_init_task(current);
  2875. }
  2876. if (new_nsproxy)
  2877. switch_task_namespaces(current, new_nsproxy);
  2878. task_lock(current);
  2879. if (new_fs) {
  2880. fs = current->fs;
  2881. spin_lock(&fs->lock);
  2882. current->fs = new_fs;
  2883. if (--fs->users)
  2884. new_fs = NULL;
  2885. else
  2886. new_fs = fs;
  2887. spin_unlock(&fs->lock);
  2888. }
  2889. if (new_fd)
  2890. swap(current->files, new_fd);
  2891. task_unlock(current);
  2892. if (new_cred) {
  2893. /* Install the new user namespace */
  2894. commit_creds(new_cred);
  2895. new_cred = NULL;
  2896. }
  2897. }
  2898. perf_event_namespaces(current);
  2899. bad_unshare_cleanup_cred:
  2900. if (new_cred)
  2901. put_cred(new_cred);
  2902. bad_unshare_cleanup_fd:
  2903. if (new_fd)
  2904. put_files_struct(new_fd);
  2905. bad_unshare_cleanup_fs:
  2906. if (new_fs)
  2907. free_fs_struct(new_fs);
  2908. bad_unshare_out:
  2909. return err;
  2910. }
  2911. SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
  2912. {
  2913. return ksys_unshare(unshare_flags);
  2914. }
  2915. /*
  2916. * Helper to unshare the files of the current task.
  2917. * We don't want to expose copy_files internals to
  2918. * the exec layer of the kernel.
  2919. */
  2920. int unshare_files(void)
  2921. {
  2922. struct task_struct *task = current;
  2923. struct files_struct *old, *copy = NULL;
  2924. int error;
  2925. error = unshare_fd(CLONE_FILES, &copy);
  2926. if (error || !copy)
  2927. return error;
  2928. old = task->files;
  2929. task_lock(task);
  2930. task->files = copy;
  2931. task_unlock(task);
  2932. put_files_struct(old);
  2933. return 0;
  2934. }
  2935. int sysctl_max_threads(const struct ctl_table *table, int write,
  2936. void *buffer, size_t *lenp, loff_t *ppos)
  2937. {
  2938. struct ctl_table t;
  2939. int ret;
  2940. int threads = max_threads;
  2941. int min = 1;
  2942. int max = MAX_THREADS;
  2943. t = *table;
  2944. t.data = &threads;
  2945. t.extra1 = &min;
  2946. t.extra2 = &max;
  2947. ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  2948. if (ret || !write)
  2949. return ret;
  2950. max_threads = threads;
  2951. return 0;
  2952. }