fork.c 83 KB

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