kernel.org linux-2.6.10
[linux-2.6.git] / kernel / fork.c
1 /*
2  *  linux/kernel/fork.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
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
14 #include <linux/config.h>
15 #include <linux/slab.h>
16 #include <linux/init.h>
17 #include <linux/unistd.h>
18 #include <linux/smp_lock.h>
19 #include <linux/module.h>
20 #include <linux/vmalloc.h>
21 #include <linux/completion.h>
22 #include <linux/namespace.h>
23 #include <linux/personality.h>
24 #include <linux/mempolicy.h>
25 #include <linux/sem.h>
26 #include <linux/file.h>
27 #include <linux/key.h>
28 #include <linux/binfmts.h>
29 #include <linux/mman.h>
30 #include <linux/fs.h>
31 #include <linux/cpu.h>
32 #include <linux/security.h>
33 #include <linux/swap.h>
34 #include <linux/syscalls.h>
35 #include <linux/jiffies.h>
36 #include <linux/futex.h>
37 #include <linux/ptrace.h>
38 #include <linux/mount.h>
39 #include <linux/audit.h>
40 #include <linux/profile.h>
41 #include <linux/rmap.h>
42
43 #include <asm/pgtable.h>
44 #include <asm/pgalloc.h>
45 #include <asm/uaccess.h>
46 #include <asm/mmu_context.h>
47 #include <asm/cacheflush.h>
48 #include <asm/tlbflush.h>
49
50 /* The idle threads do not count..
51  * Protected by write_lock_irq(&tasklist_lock)
52  */
53 int nr_threads;
54
55 int max_threads;
56 unsigned long total_forks;      /* Handle normal Linux uptimes. */
57
58 DEFINE_PER_CPU(unsigned long, process_counts) = 0;
59
60 rwlock_t tasklist_lock __cacheline_aligned = RW_LOCK_UNLOCKED;  /* outer */
61
62 EXPORT_SYMBOL(tasklist_lock);
63
64 int nr_processes(void)
65 {
66         int cpu;
67         int total = 0;
68
69         for_each_online_cpu(cpu)
70                 total += per_cpu(process_counts, cpu);
71
72         return total;
73 }
74
75 #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
76 # define alloc_task_struct()    kmem_cache_alloc(task_struct_cachep, GFP_KERNEL)
77 # define free_task_struct(tsk)  kmem_cache_free(task_struct_cachep, (tsk))
78 static kmem_cache_t *task_struct_cachep;
79 #endif
80
81 void free_task(struct task_struct *tsk)
82 {
83         free_thread_info(tsk->thread_info);
84         free_task_struct(tsk);
85 }
86 EXPORT_SYMBOL(free_task);
87
88 void __put_task_struct(struct task_struct *tsk)
89 {
90         WARN_ON(!(tsk->exit_state & (EXIT_DEAD | EXIT_ZOMBIE)));
91         WARN_ON(atomic_read(&tsk->usage));
92         WARN_ON(tsk == current);
93
94         if (unlikely(tsk->audit_context))
95                 audit_free(tsk);
96         security_task_free(tsk);
97         free_uid(tsk->user);
98         put_group_info(tsk->group_info);
99
100         if (!profile_handoff_task(tsk))
101                 free_task(tsk);
102 }
103
104 void __init fork_init(unsigned long mempages)
105 {
106 #ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
107 #ifndef ARCH_MIN_TASKALIGN
108 #define ARCH_MIN_TASKALIGN      L1_CACHE_BYTES
109 #endif
110         /* create a slab on which task_structs can be allocated */
111         task_struct_cachep =
112                 kmem_cache_create("task_struct", sizeof(struct task_struct),
113                         ARCH_MIN_TASKALIGN, SLAB_PANIC, NULL, NULL);
114 #endif
115
116         /*
117          * The default maximum number of threads is set to a safe
118          * value: the thread structures can take up at most half
119          * of memory.
120          */
121         max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
122
123         /*
124          * we need to allow at least 20 threads to boot a system
125          */
126         if(max_threads < 20)
127                 max_threads = 20;
128
129         init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
130         init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
131 }
132
133 static struct task_struct *dup_task_struct(struct task_struct *orig)
134 {
135         struct task_struct *tsk;
136         struct thread_info *ti;
137
138         prepare_to_copy(orig);
139
140         tsk = alloc_task_struct();
141         if (!tsk)
142                 return NULL;
143
144         ti = alloc_thread_info(tsk);
145         if (!ti) {
146                 free_task_struct(tsk);
147                 return NULL;
148         }
149
150         *ti = *orig->thread_info;
151         *tsk = *orig;
152         tsk->thread_info = ti;
153         ti->task = tsk;
154
155         /* One for us, one for whoever does the "release_task()" (usually parent) */
156         atomic_set(&tsk->usage,2);
157         return tsk;
158 }
159
160 #ifdef CONFIG_MMU
161 static inline int dup_mmap(struct mm_struct * mm, struct mm_struct * oldmm)
162 {
163         struct vm_area_struct * mpnt, *tmp, **pprev;
164         struct rb_node **rb_link, *rb_parent;
165         int retval;
166         unsigned long charge;
167         struct mempolicy *pol;
168
169         down_write(&oldmm->mmap_sem);
170         flush_cache_mm(current->mm);
171         mm->locked_vm = 0;
172         mm->mmap = NULL;
173         mm->mmap_cache = NULL;
174         mm->free_area_cache = oldmm->mmap_base;
175         mm->map_count = 0;
176         mm->rss = 0;
177         mm->anon_rss = 0;
178         cpus_clear(mm->cpu_vm_mask);
179         mm->mm_rb = RB_ROOT;
180         rb_link = &mm->mm_rb.rb_node;
181         rb_parent = NULL;
182         pprev = &mm->mmap;
183
184         for (mpnt = current->mm->mmap ; mpnt ; mpnt = mpnt->vm_next) {
185                 struct file *file;
186
187                 if (mpnt->vm_flags & VM_DONTCOPY) {
188                         __vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
189                                                         -vma_pages(mpnt));
190                         continue;
191                 }
192                 charge = 0;
193                 if (mpnt->vm_flags & VM_ACCOUNT) {
194                         unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
195                         if (security_vm_enough_memory(len))
196                                 goto fail_nomem;
197                         charge = len;
198                 }
199                 tmp = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
200                 if (!tmp)
201                         goto fail_nomem;
202                 *tmp = *mpnt;
203                 pol = mpol_copy(vma_policy(mpnt));
204                 retval = PTR_ERR(pol);
205                 if (IS_ERR(pol))
206                         goto fail_nomem_policy;
207                 vma_set_policy(tmp, pol);
208                 tmp->vm_flags &= ~VM_LOCKED;
209                 tmp->vm_mm = mm;
210                 tmp->vm_next = NULL;
211                 anon_vma_link(tmp);
212                 file = tmp->vm_file;
213                 if (file) {
214                         struct inode *inode = file->f_dentry->d_inode;
215                         get_file(file);
216                         if (tmp->vm_flags & VM_DENYWRITE)
217                                 atomic_dec(&inode->i_writecount);
218       
219                         /* insert tmp into the share list, just after mpnt */
220                         spin_lock(&file->f_mapping->i_mmap_lock);
221                         flush_dcache_mmap_lock(file->f_mapping);
222                         vma_prio_tree_add(tmp, mpnt);
223                         flush_dcache_mmap_unlock(file->f_mapping);
224                         spin_unlock(&file->f_mapping->i_mmap_lock);
225                 }
226
227                 /*
228                  * Link in the new vma and copy the page table entries:
229                  * link in first so that swapoff can see swap entries,
230                  * and try_to_unmap_one's find_vma find the new vma.
231                  */
232                 spin_lock(&mm->page_table_lock);
233                 *pprev = tmp;
234                 pprev = &tmp->vm_next;
235
236                 __vma_link_rb(mm, tmp, rb_link, rb_parent);
237                 rb_link = &tmp->vm_rb.rb_right;
238                 rb_parent = &tmp->vm_rb;
239
240                 mm->map_count++;
241                 retval = copy_page_range(mm, current->mm, tmp);
242                 spin_unlock(&mm->page_table_lock);
243
244                 if (tmp->vm_ops && tmp->vm_ops->open)
245                         tmp->vm_ops->open(tmp);
246
247                 if (retval)
248                         goto out;
249         }
250         retval = 0;
251
252 out:
253         flush_tlb_mm(current->mm);
254         up_write(&oldmm->mmap_sem);
255         return retval;
256 fail_nomem_policy:
257         kmem_cache_free(vm_area_cachep, tmp);
258 fail_nomem:
259         retval = -ENOMEM;
260         vm_unacct_memory(charge);
261         goto out;
262 }
263
264 static inline int mm_alloc_pgd(struct mm_struct * mm)
265 {
266         mm->pgd = pgd_alloc(mm);
267         if (unlikely(!mm->pgd))
268                 return -ENOMEM;
269         return 0;
270 }
271
272 static inline void mm_free_pgd(struct mm_struct * mm)
273 {
274         pgd_free(mm->pgd);
275 }
276 #else
277 #define dup_mmap(mm, oldmm)     (0)
278 #define mm_alloc_pgd(mm)        (0)
279 #define mm_free_pgd(mm)
280 #endif /* CONFIG_MMU */
281
282 spinlock_t mmlist_lock __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
283
284 #define allocate_mm()   (kmem_cache_alloc(mm_cachep, SLAB_KERNEL))
285 #define free_mm(mm)     (kmem_cache_free(mm_cachep, (mm)))
286
287 #include <linux/init_task.h>
288
289 static struct mm_struct * mm_init(struct mm_struct * mm)
290 {
291         atomic_set(&mm->mm_users, 1);
292         atomic_set(&mm->mm_count, 1);
293         init_rwsem(&mm->mmap_sem);
294         INIT_LIST_HEAD(&mm->mmlist);
295         mm->core_waiters = 0;
296         mm->nr_ptes = 0;
297         spin_lock_init(&mm->page_table_lock);
298         rwlock_init(&mm->ioctx_list_lock);
299         mm->ioctx_list = NULL;
300         mm->default_kioctx = (struct kioctx)INIT_KIOCTX(mm->default_kioctx, *mm);
301         mm->free_area_cache = TASK_UNMAPPED_BASE;
302
303         if (likely(!mm_alloc_pgd(mm))) {
304                 mm->def_flags = 0;
305                 return mm;
306         }
307         free_mm(mm);
308         return NULL;
309 }
310
311 /*
312  * Allocate and initialize an mm_struct.
313  */
314 struct mm_struct * mm_alloc(void)
315 {
316         struct mm_struct * mm;
317
318         mm = allocate_mm();
319         if (mm) {
320                 memset(mm, 0, sizeof(*mm));
321                 mm = mm_init(mm);
322         }
323         return mm;
324 }
325
326 /*
327  * Called when the last reference to the mm
328  * is dropped: either by a lazy thread or by
329  * mmput. Free the page directory and the mm.
330  */
331 void fastcall __mmdrop(struct mm_struct *mm)
332 {
333         BUG_ON(mm == &init_mm);
334         mm_free_pgd(mm);
335         destroy_context(mm);
336         free_mm(mm);
337 }
338
339 /*
340  * Decrement the use count and release all resources for an mm.
341  */
342 void mmput(struct mm_struct *mm)
343 {
344         if (atomic_dec_and_test(&mm->mm_users)) {
345                 exit_aio(mm);
346                 exit_mmap(mm);
347                 if (!list_empty(&mm->mmlist)) {
348                         spin_lock(&mmlist_lock);
349                         list_del(&mm->mmlist);
350                         spin_unlock(&mmlist_lock);
351                 }
352                 put_swap_token(mm);
353                 mmdrop(mm);
354         }
355 }
356 EXPORT_SYMBOL_GPL(mmput);
357
358 /**
359  * get_task_mm - acquire a reference to the task's mm
360  *
361  * Returns %NULL if the task has no mm.  Checks PF_BORROWED_MM (meaning
362  * this kernel workthread has transiently adopted a user mm with use_mm,
363  * to do its AIO) is not set and if so returns a reference to it, after
364  * bumping up the use count.  User must release the mm via mmput()
365  * after use.  Typically used by /proc and ptrace.
366  */
367 struct mm_struct *get_task_mm(struct task_struct *task)
368 {
369         struct mm_struct *mm;
370
371         task_lock(task);
372         mm = task->mm;
373         if (mm) {
374                 if (task->flags & PF_BORROWED_MM)
375                         mm = NULL;
376                 else
377                         atomic_inc(&mm->mm_users);
378         }
379         task_unlock(task);
380         return mm;
381 }
382 EXPORT_SYMBOL_GPL(get_task_mm);
383
384 /* Please note the differences between mmput and mm_release.
385  * mmput is called whenever we stop holding onto a mm_struct,
386  * error success whatever.
387  *
388  * mm_release is called after a mm_struct has been removed
389  * from the current process.
390  *
391  * This difference is important for error handling, when we
392  * only half set up a mm_struct for a new process and need to restore
393  * the old one.  Because we mmput the new mm_struct before
394  * restoring the old one. . .
395  * Eric Biederman 10 January 1998
396  */
397 void mm_release(struct task_struct *tsk, struct mm_struct *mm)
398 {
399         struct completion *vfork_done = tsk->vfork_done;
400
401         /* Get rid of any cached register state */
402         deactivate_mm(tsk, mm);
403
404         /* notify parent sleeping on vfork() */
405         if (vfork_done) {
406                 tsk->vfork_done = NULL;
407                 complete(vfork_done);
408         }
409         if (tsk->clear_child_tid && atomic_read(&mm->mm_users) > 1) {
410                 u32 __user * tidptr = tsk->clear_child_tid;
411                 tsk->clear_child_tid = NULL;
412
413                 /*
414                  * We don't check the error code - if userspace has
415                  * not set up a proper pointer then tough luck.
416                  */
417                 put_user(0, tidptr);
418                 sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0);
419         }
420 }
421
422 static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
423 {
424         struct mm_struct * mm, *oldmm;
425         int retval;
426
427         tsk->min_flt = tsk->maj_flt = 0;
428         tsk->nvcsw = tsk->nivcsw = 0;
429
430         tsk->mm = NULL;
431         tsk->active_mm = NULL;
432
433         /*
434          * Are we cloning a kernel thread?
435          *
436          * We need to steal a active VM for that..
437          */
438         oldmm = current->mm;
439         if (!oldmm)
440                 return 0;
441
442         if (clone_flags & CLONE_VM) {
443                 atomic_inc(&oldmm->mm_users);
444                 mm = oldmm;
445                 /*
446                  * There are cases where the PTL is held to ensure no
447                  * new threads start up in user mode using an mm, which
448                  * allows optimizing out ipis; the tlb_gather_mmu code
449                  * is an example.
450                  */
451                 spin_unlock_wait(&oldmm->page_table_lock);
452                 goto good_mm;
453         }
454
455         retval = -ENOMEM;
456         mm = allocate_mm();
457         if (!mm)
458                 goto fail_nomem;
459
460         /* Copy the current MM stuff.. */
461         memcpy(mm, oldmm, sizeof(*mm));
462         if (!mm_init(mm))
463                 goto fail_nomem;
464
465         if (init_new_context(tsk,mm))
466                 goto fail_nocontext;
467
468         retval = dup_mmap(mm, oldmm);
469         if (retval)
470                 goto free_pt;
471
472 good_mm:
473         tsk->mm = mm;
474         tsk->active_mm = mm;
475         return 0;
476
477 free_pt:
478         mmput(mm);
479 fail_nomem:
480         return retval;
481
482 fail_nocontext:
483         /*
484          * If init_new_context() failed, we cannot use mmput() to free the mm
485          * because it calls destroy_context()
486          */
487         mm_free_pgd(mm);
488         free_mm(mm);
489         return retval;
490 }
491
492 static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old)
493 {
494         struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL);
495         /* We don't need to lock fs - think why ;-) */
496         if (fs) {
497                 atomic_set(&fs->count, 1);
498                 rwlock_init(&fs->lock);
499                 fs->umask = old->umask;
500                 read_lock(&old->lock);
501                 fs->rootmnt = mntget(old->rootmnt);
502                 fs->root = dget(old->root);
503                 fs->pwdmnt = mntget(old->pwdmnt);
504                 fs->pwd = dget(old->pwd);
505                 if (old->altroot) {
506                         fs->altrootmnt = mntget(old->altrootmnt);
507                         fs->altroot = dget(old->altroot);
508                 } else {
509                         fs->altrootmnt = NULL;
510                         fs->altroot = NULL;
511                 }
512                 read_unlock(&old->lock);
513         }
514         return fs;
515 }
516
517 struct fs_struct *copy_fs_struct(struct fs_struct *old)
518 {
519         return __copy_fs_struct(old);
520 }
521
522 EXPORT_SYMBOL_GPL(copy_fs_struct);
523
524 static inline int copy_fs(unsigned long clone_flags, struct task_struct * tsk)
525 {
526         if (clone_flags & CLONE_FS) {
527                 atomic_inc(&current->fs->count);
528                 return 0;
529         }
530         tsk->fs = __copy_fs_struct(current->fs);
531         if (!tsk->fs)
532                 return -ENOMEM;
533         return 0;
534 }
535
536 static int count_open_files(struct files_struct *files, int size)
537 {
538         int i;
539
540         /* Find the last open fd */
541         for (i = size/(8*sizeof(long)); i > 0; ) {
542                 if (files->open_fds->fds_bits[--i])
543                         break;
544         }
545         i = (i+1) * 8 * sizeof(long);
546         return i;
547 }
548
549 static int copy_files(unsigned long clone_flags, struct task_struct * tsk)
550 {
551         struct files_struct *oldf, *newf;
552         struct file **old_fds, **new_fds;
553         int open_files, nfds, size, i, error = 0;
554
555         /*
556          * A background process may not have any files ...
557          */
558         oldf = current->files;
559         if (!oldf)
560                 goto out;
561
562         if (clone_flags & CLONE_FILES) {
563                 atomic_inc(&oldf->count);
564                 goto out;
565         }
566
567         /*
568          * Note: we may be using current for both targets (See exec.c)
569          * This works because we cache current->files (old) as oldf. Don't
570          * break this.
571          */
572         tsk->files = NULL;
573         error = -ENOMEM;
574         newf = kmem_cache_alloc(files_cachep, SLAB_KERNEL);
575         if (!newf) 
576                 goto out;
577
578         atomic_set(&newf->count, 1);
579
580         spin_lock_init(&newf->file_lock);
581         newf->next_fd       = 0;
582         newf->max_fds       = NR_OPEN_DEFAULT;
583         newf->max_fdset     = __FD_SETSIZE;
584         newf->close_on_exec = &newf->close_on_exec_init;
585         newf->open_fds      = &newf->open_fds_init;
586         newf->fd            = &newf->fd_array[0];
587
588         /* We don't yet have the oldf readlock, but even if the old
589            fdset gets grown now, we'll only copy up to "size" fds */
590         size = oldf->max_fdset;
591         if (size > __FD_SETSIZE) {
592                 newf->max_fdset = 0;
593                 spin_lock(&newf->file_lock);
594                 error = expand_fdset(newf, size-1);
595                 spin_unlock(&newf->file_lock);
596                 if (error)
597                         goto out_release;
598         }
599         spin_lock(&oldf->file_lock);
600
601         open_files = count_open_files(oldf, size);
602
603         /*
604          * Check whether we need to allocate a larger fd array.
605          * Note: we're not a clone task, so the open count won't
606          * change.
607          */
608         nfds = NR_OPEN_DEFAULT;
609         if (open_files > nfds) {
610                 spin_unlock(&oldf->file_lock);
611                 newf->max_fds = 0;
612                 spin_lock(&newf->file_lock);
613                 error = expand_fd_array(newf, open_files-1);
614                 spin_unlock(&newf->file_lock);
615                 if (error) 
616                         goto out_release;
617                 nfds = newf->max_fds;
618                 spin_lock(&oldf->file_lock);
619         }
620
621         old_fds = oldf->fd;
622         new_fds = newf->fd;
623
624         memcpy(newf->open_fds->fds_bits, oldf->open_fds->fds_bits, open_files/8);
625         memcpy(newf->close_on_exec->fds_bits, oldf->close_on_exec->fds_bits, open_files/8);
626
627         for (i = open_files; i != 0; i--) {
628                 struct file *f = *old_fds++;
629                 if (f) {
630                         get_file(f);
631                 } else {
632                         /*
633                          * The fd may be claimed in the fd bitmap but not yet
634                          * instantiated in the files array if a sibling thread
635                          * is partway through open().  So make sure that this
636                          * fd is available to the new process.
637                          */
638                         FD_CLR(open_files - i, newf->open_fds);
639                 }
640                 *new_fds++ = f;
641         }
642         spin_unlock(&oldf->file_lock);
643
644         /* compute the remainder to be cleared */
645         size = (newf->max_fds - open_files) * sizeof(struct file *);
646
647         /* This is long word aligned thus could use a optimized version */ 
648         memset(new_fds, 0, size); 
649
650         if (newf->max_fdset > open_files) {
651                 int left = (newf->max_fdset-open_files)/8;
652                 int start = open_files / (8 * sizeof(unsigned long));
653
654                 memset(&newf->open_fds->fds_bits[start], 0, left);
655                 memset(&newf->close_on_exec->fds_bits[start], 0, left);
656         }
657
658         tsk->files = newf;
659         error = 0;
660 out:
661         return error;
662
663 out_release:
664         free_fdset (newf->close_on_exec, newf->max_fdset);
665         free_fdset (newf->open_fds, newf->max_fdset);
666         kmem_cache_free(files_cachep, newf);
667         goto out;
668 }
669
670 /*
671  *      Helper to unshare the files of the current task.
672  *      We don't want to expose copy_files internals to
673  *      the exec layer of the kernel.
674  */
675
676 int unshare_files(void)
677 {
678         struct files_struct *files  = current->files;
679         int rc;
680
681         if(!files)
682                 BUG();
683
684         /* This can race but the race causes us to copy when we don't
685            need to and drop the copy */
686         if(atomic_read(&files->count) == 1)
687         {
688                 atomic_inc(&files->count);
689                 return 0;
690         }
691         rc = copy_files(0, current);
692         if(rc)
693                 current->files = files;
694         return rc;
695 }
696
697 EXPORT_SYMBOL(unshare_files);
698
699 static inline int copy_sighand(unsigned long clone_flags, struct task_struct * tsk)
700 {
701         struct sighand_struct *sig;
702
703         if (clone_flags & (CLONE_SIGHAND | CLONE_THREAD)) {
704                 atomic_inc(&current->sighand->count);
705                 return 0;
706         }
707         sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
708         tsk->sighand = sig;
709         if (!sig)
710                 return -ENOMEM;
711         spin_lock_init(&sig->siglock);
712         atomic_set(&sig->count, 1);
713         memcpy(sig->action, current->sighand->action, sizeof(sig->action));
714         return 0;
715 }
716
717 static inline int copy_signal(unsigned long clone_flags, struct task_struct * tsk)
718 {
719         struct signal_struct *sig;
720
721         if (clone_flags & CLONE_THREAD) {
722                 atomic_inc(&current->signal->count);
723                 atomic_inc(&current->signal->live);
724                 return 0;
725         }
726         sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
727         tsk->signal = sig;
728         if (!sig)
729                 return -ENOMEM;
730         atomic_set(&sig->count, 1);
731         atomic_set(&sig->live, 1);
732         sig->group_exit = 0;
733         sig->group_exit_code = 0;
734         sig->group_exit_task = NULL;
735         sig->group_stop_count = 0;
736         sig->stop_state = 0;
737         sig->curr_target = NULL;
738         init_sigpending(&sig->shared_pending);
739         INIT_LIST_HEAD(&sig->posix_timers);
740
741         sig->tty = current->signal->tty;
742         sig->pgrp = process_group(current);
743         sig->session = current->signal->session;
744         sig->leader = 0;        /* session leadership doesn't inherit */
745         sig->tty_old_pgrp = 0;
746
747         sig->utime = sig->stime = sig->cutime = sig->cstime = 0;
748         sig->nvcsw = sig->nivcsw = sig->cnvcsw = sig->cnivcsw = 0;
749         sig->min_flt = sig->maj_flt = sig->cmin_flt = sig->cmaj_flt = 0;
750
751         task_lock(current->group_leader);
752         memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
753         task_unlock(current->group_leader);
754
755         return 0;
756 }
757
758 static inline void copy_flags(unsigned long clone_flags, struct task_struct *p)
759 {
760         unsigned long new_flags = p->flags;
761
762         new_flags &= ~PF_SUPERPRIV;
763         new_flags |= PF_FORKNOEXEC;
764         if (!(clone_flags & CLONE_PTRACE))
765                 p->ptrace = 0;
766         p->flags = new_flags;
767 }
768
769 asmlinkage long sys_set_tid_address(int __user *tidptr)
770 {
771         current->clear_child_tid = tidptr;
772
773         return current->pid;
774 }
775
776 /*
777  * This creates a new process as a copy of the old one,
778  * but does not actually start it yet.
779  *
780  * It copies the registers, and all the appropriate
781  * parts of the process environment (as per the clone
782  * flags). The actual kick-off is left to the caller.
783  */
784 static task_t *copy_process(unsigned long clone_flags,
785                                  unsigned long stack_start,
786                                  struct pt_regs *regs,
787                                  unsigned long stack_size,
788                                  int __user *parent_tidptr,
789                                  int __user *child_tidptr,
790                                  int pid)
791 {
792         int retval;
793         struct task_struct *p = NULL;
794
795         if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
796                 return ERR_PTR(-EINVAL);
797
798         /*
799          * Thread groups must share signals as well, and detached threads
800          * can only be started up within the thread group.
801          */
802         if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
803                 return ERR_PTR(-EINVAL);
804
805         /*
806          * Shared signal handlers imply shared VM. By way of the above,
807          * thread groups also imply shared VM. Blocking this case allows
808          * for various simplifications in other code.
809          */
810         if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
811                 return ERR_PTR(-EINVAL);
812
813         retval = security_task_create(clone_flags);
814         if (retval)
815                 goto fork_out;
816
817         retval = -ENOMEM;
818         p = dup_task_struct(current);
819         if (!p)
820                 goto fork_out;
821
822         retval = -EAGAIN;
823         if (atomic_read(&p->user->processes) >=
824                         p->signal->rlim[RLIMIT_NPROC].rlim_cur) {
825                 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
826                                 p->user != &root_user)
827                         goto bad_fork_free;
828         }
829
830         atomic_inc(&p->user->__count);
831         atomic_inc(&p->user->processes);
832         get_group_info(p->group_info);
833
834         /*
835          * If multiple threads are within copy_process(), then this check
836          * triggers too late. This doesn't hurt, the check is only there
837          * to stop root fork bombs.
838          */
839         if (nr_threads >= max_threads)
840                 goto bad_fork_cleanup_count;
841
842         if (!try_module_get(p->thread_info->exec_domain->module))
843                 goto bad_fork_cleanup_count;
844
845         if (p->binfmt && !try_module_get(p->binfmt->module))
846                 goto bad_fork_cleanup_put_domain;
847
848         p->did_exec = 0;
849         copy_flags(clone_flags, p);
850         p->pid = pid;
851         retval = -EFAULT;
852         if (clone_flags & CLONE_PARENT_SETTID)
853                 if (put_user(p->pid, parent_tidptr))
854                         goto bad_fork_cleanup;
855
856         p->proc_dentry = NULL;
857
858         INIT_LIST_HEAD(&p->children);
859         INIT_LIST_HEAD(&p->sibling);
860         init_waitqueue_head(&p->wait_chldexit);
861         p->vfork_done = NULL;
862         spin_lock_init(&p->alloc_lock);
863         spin_lock_init(&p->proc_lock);
864
865         clear_tsk_thread_flag(p, TIF_SIGPENDING);
866         init_sigpending(&p->pending);
867
868         p->it_real_value = p->it_virt_value = p->it_prof_value = 0;
869         p->it_real_incr = p->it_virt_incr = p->it_prof_incr = 0;
870         init_timer(&p->real_timer);
871         p->real_timer.data = (unsigned long) p;
872
873         p->utime = p->stime = 0;
874         p->lock_depth = -1;             /* -1 = no lock */
875         do_posix_clock_monotonic_gettime(&p->start_time);
876         p->security = NULL;
877         p->io_context = NULL;
878         p->io_wait = NULL;
879         p->audit_context = NULL;
880 #ifdef CONFIG_NUMA
881         p->mempolicy = mpol_copy(p->mempolicy);
882         if (IS_ERR(p->mempolicy)) {
883                 retval = PTR_ERR(p->mempolicy);
884                 p->mempolicy = NULL;
885                 goto bad_fork_cleanup;
886         }
887 #endif
888
889         p->tgid = p->pid;
890         if (clone_flags & CLONE_THREAD)
891                 p->tgid = current->tgid;
892
893         if ((retval = security_task_alloc(p)))
894                 goto bad_fork_cleanup_policy;
895         if ((retval = audit_alloc(p)))
896                 goto bad_fork_cleanup_security;
897         /* copy all the process information */
898         if ((retval = copy_semundo(clone_flags, p)))
899                 goto bad_fork_cleanup_audit;
900         if ((retval = copy_files(clone_flags, p)))
901                 goto bad_fork_cleanup_semundo;
902         if ((retval = copy_fs(clone_flags, p)))
903                 goto bad_fork_cleanup_files;
904         if ((retval = copy_sighand(clone_flags, p)))
905                 goto bad_fork_cleanup_fs;
906         if ((retval = copy_signal(clone_flags, p)))
907                 goto bad_fork_cleanup_sighand;
908         if ((retval = copy_mm(clone_flags, p)))
909                 goto bad_fork_cleanup_signal;
910         if ((retval = copy_keys(clone_flags, p)))
911                 goto bad_fork_cleanup_mm;
912         if ((retval = copy_namespace(clone_flags, p)))
913                 goto bad_fork_cleanup_keys;
914         retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs);
915         if (retval)
916                 goto bad_fork_cleanup_namespace;
917
918         p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
919         /*
920          * Clear TID on mm_release()?
921          */
922         p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
923
924         /*
925          * Syscall tracing should be turned off in the child regardless
926          * of CLONE_PTRACE.
927          */
928         clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
929
930         /* Our parent execution domain becomes current domain
931            These must match for thread signalling to apply */
932            
933         p->parent_exec_id = p->self_exec_id;
934
935         /* ok, now we should be set up.. */
936         p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
937         p->pdeath_signal = 0;
938         p->exit_state = 0;
939
940         /* Perform scheduler related setup */
941         sched_fork(p);
942
943         /*
944          * Ok, make it visible to the rest of the system.
945          * We dont wake it up yet.
946          */
947         p->group_leader = p;
948         INIT_LIST_HEAD(&p->ptrace_children);
949         INIT_LIST_HEAD(&p->ptrace_list);
950
951         /* Need tasklist lock for parent etc handling! */
952         write_lock_irq(&tasklist_lock);
953
954         /*
955          * The task hasn't been attached yet, so cpus_allowed mask cannot
956          * have changed. The cpus_allowed mask of the parent may have
957          * changed after it was copied first time, and it may then move to
958          * another CPU - so we re-copy it here and set the child's CPU to
959          * the parent's CPU. This avoids alot of nasty races.
960          */
961         p->cpus_allowed = current->cpus_allowed;
962         set_task_cpu(p, smp_processor_id());
963
964         /*
965          * Check for pending SIGKILL! The new thread should not be allowed
966          * to slip out of an OOM kill. (or normal SIGKILL.)
967          */
968         if (sigismember(&current->pending.signal, SIGKILL)) {
969                 write_unlock_irq(&tasklist_lock);
970                 retval = -EINTR;
971                 goto bad_fork_cleanup_namespace;
972         }
973
974         /* CLONE_PARENT re-uses the old parent */
975         if (clone_flags & (CLONE_PARENT|CLONE_THREAD))
976                 p->real_parent = current->real_parent;
977         else
978                 p->real_parent = current;
979         p->parent = p->real_parent;
980
981         if (clone_flags & CLONE_THREAD) {
982                 spin_lock(&current->sighand->siglock);
983                 /*
984                  * Important: if an exit-all has been started then
985                  * do not create this new thread - the whole thread
986                  * group is supposed to exit anyway.
987                  */
988                 if (current->signal->group_exit) {
989                         spin_unlock(&current->sighand->siglock);
990                         write_unlock_irq(&tasklist_lock);
991                         retval = -EAGAIN;
992                         goto bad_fork_cleanup_namespace;
993                 }
994                 p->group_leader = current->group_leader;
995
996                 if (current->signal->group_stop_count > 0) {
997                         /*
998                          * There is an all-stop in progress for the group.
999                          * We ourselves will stop as soon as we check signals.
1000                          * Make the new thread part of that group stop too.
1001                          */
1002                         current->signal->group_stop_count++;
1003                         set_tsk_thread_flag(p, TIF_SIGPENDING);
1004                 }
1005
1006                 spin_unlock(&current->sighand->siglock);
1007         }
1008
1009         SET_LINKS(p);
1010         if (unlikely(p->ptrace & PT_PTRACED))
1011                 __ptrace_link(p, current->parent);
1012
1013         attach_pid(p, PIDTYPE_PID, p->pid);
1014         attach_pid(p, PIDTYPE_TGID, p->tgid);
1015         if (thread_group_leader(p)) {
1016                 attach_pid(p, PIDTYPE_PGID, process_group(p));
1017                 attach_pid(p, PIDTYPE_SID, p->signal->session);
1018                 if (p->pid)
1019                         __get_cpu_var(process_counts)++;
1020         }
1021
1022         nr_threads++;
1023         write_unlock_irq(&tasklist_lock);
1024         retval = 0;
1025
1026 fork_out:
1027         if (retval)
1028                 return ERR_PTR(retval);
1029         return p;
1030
1031 bad_fork_cleanup_namespace:
1032         exit_namespace(p);
1033 bad_fork_cleanup_keys:
1034         exit_keys(p);
1035 bad_fork_cleanup_mm:
1036         if (p->mm)
1037                 mmput(p->mm);
1038 bad_fork_cleanup_signal:
1039         exit_signal(p);
1040 bad_fork_cleanup_sighand:
1041         exit_sighand(p);
1042 bad_fork_cleanup_fs:
1043         exit_fs(p); /* blocking */
1044 bad_fork_cleanup_files:
1045         exit_files(p); /* blocking */
1046 bad_fork_cleanup_semundo:
1047         exit_sem(p);
1048 bad_fork_cleanup_audit:
1049         audit_free(p);
1050 bad_fork_cleanup_security:
1051         security_task_free(p);
1052 bad_fork_cleanup_policy:
1053 #ifdef CONFIG_NUMA
1054         mpol_free(p->mempolicy);
1055 #endif
1056 bad_fork_cleanup:
1057         if (p->binfmt)
1058                 module_put(p->binfmt->module);
1059 bad_fork_cleanup_put_domain:
1060         module_put(p->thread_info->exec_domain->module);
1061 bad_fork_cleanup_count:
1062         put_group_info(p->group_info);
1063         atomic_dec(&p->user->processes);
1064         free_uid(p->user);
1065 bad_fork_free:
1066         free_task(p);
1067         goto fork_out;
1068 }
1069
1070 struct pt_regs * __devinit __attribute__((weak)) idle_regs(struct pt_regs *regs)
1071 {
1072         memset(regs, 0, sizeof(struct pt_regs));
1073         return regs;
1074 }
1075
1076 task_t * __devinit fork_idle(int cpu)
1077 {
1078         task_t *task;
1079         struct pt_regs regs;
1080
1081         task = copy_process(CLONE_VM, 0, idle_regs(&regs), 0, NULL, NULL, 0);
1082         if (!task)
1083                 return ERR_PTR(-ENOMEM);
1084         init_idle(task, cpu);
1085         unhash_process(task);
1086         return task;
1087 }
1088
1089 static inline int fork_traceflag (unsigned clone_flags)
1090 {
1091         if (clone_flags & CLONE_UNTRACED)
1092                 return 0;
1093         else if (clone_flags & CLONE_VFORK) {
1094                 if (current->ptrace & PT_TRACE_VFORK)
1095                         return PTRACE_EVENT_VFORK;
1096         } else if ((clone_flags & CSIGNAL) != SIGCHLD) {
1097                 if (current->ptrace & PT_TRACE_CLONE)
1098                         return PTRACE_EVENT_CLONE;
1099         } else if (current->ptrace & PT_TRACE_FORK)
1100                 return PTRACE_EVENT_FORK;
1101
1102         return 0;
1103 }
1104
1105 /*
1106  *  Ok, this is the main fork-routine.
1107  *
1108  * It copies the process, and if successful kick-starts
1109  * it and waits for it to finish using the VM if required.
1110  */
1111 long do_fork(unsigned long clone_flags,
1112               unsigned long stack_start,
1113               struct pt_regs *regs,
1114               unsigned long stack_size,
1115               int __user *parent_tidptr,
1116               int __user *child_tidptr)
1117 {
1118         struct task_struct *p;
1119         int trace = 0;
1120         long pid = alloc_pidmap();
1121
1122         if (pid < 0)
1123                 return -EAGAIN;
1124         if (unlikely(current->ptrace)) {
1125                 trace = fork_traceflag (clone_flags);
1126                 if (trace)
1127                         clone_flags |= CLONE_PTRACE;
1128         }
1129
1130         p = copy_process(clone_flags, stack_start, regs, stack_size, parent_tidptr, child_tidptr, pid);
1131         /*
1132          * Do this prior waking up the new thread - the thread pointer
1133          * might get invalid after that point, if the thread exits quickly.
1134          */
1135         if (!IS_ERR(p)) {
1136                 struct completion vfork;
1137
1138                 if (clone_flags & CLONE_VFORK) {
1139                         p->vfork_done = &vfork;
1140                         init_completion(&vfork);
1141                 }
1142
1143                 if ((p->ptrace & PT_PTRACED) || (clone_flags & CLONE_STOPPED)) {
1144                         /*
1145                          * We'll start up with an immediate SIGSTOP.
1146                          */
1147                         sigaddset(&p->pending.signal, SIGSTOP);
1148                         set_tsk_thread_flag(p, TIF_SIGPENDING);
1149                 }
1150
1151                 if (!(clone_flags & CLONE_STOPPED))
1152                         wake_up_new_task(p, clone_flags);
1153                 else
1154                         p->state = TASK_STOPPED;
1155                 ++total_forks;
1156
1157                 if (unlikely (trace)) {
1158                         current->ptrace_message = pid;
1159                         ptrace_notify ((trace << 8) | SIGTRAP);
1160                 }
1161
1162                 if (clone_flags & CLONE_VFORK) {
1163                         wait_for_completion(&vfork);
1164                         if (unlikely (current->ptrace & PT_TRACE_VFORK_DONE))
1165                                 ptrace_notify ((PTRACE_EVENT_VFORK_DONE << 8) | SIGTRAP);
1166                 }
1167         } else {
1168                 free_pidmap(pid);
1169                 pid = PTR_ERR(p);
1170         }
1171         return pid;
1172 }
1173
1174 /* SLAB cache for signal_struct structures (tsk->signal) */
1175 kmem_cache_t *signal_cachep;
1176
1177 /* SLAB cache for sighand_struct structures (tsk->sighand) */
1178 kmem_cache_t *sighand_cachep;
1179
1180 /* SLAB cache for files_struct structures (tsk->files) */
1181 kmem_cache_t *files_cachep;
1182
1183 /* SLAB cache for fs_struct structures (tsk->fs) */
1184 kmem_cache_t *fs_cachep;
1185
1186 /* SLAB cache for vm_area_struct structures */
1187 kmem_cache_t *vm_area_cachep;
1188
1189 /* SLAB cache for mm_struct structures (tsk->mm) */
1190 kmem_cache_t *mm_cachep;
1191
1192 void __init proc_caches_init(void)
1193 {
1194         sighand_cachep = kmem_cache_create("sighand_cache",
1195                         sizeof(struct sighand_struct), 0,
1196                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1197         signal_cachep = kmem_cache_create("signal_cache",
1198                         sizeof(struct signal_struct), 0,
1199                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1200         files_cachep = kmem_cache_create("files_cache", 
1201                         sizeof(struct files_struct), 0,
1202                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1203         fs_cachep = kmem_cache_create("fs_cache", 
1204                         sizeof(struct fs_struct), 0,
1205                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1206         vm_area_cachep = kmem_cache_create("vm_area_struct",
1207                         sizeof(struct vm_area_struct), 0,
1208                         SLAB_PANIC, NULL, NULL);
1209         mm_cachep = kmem_cache_create("mm_struct",
1210                         sizeof(struct mm_struct), 0,
1211                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1212 }