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