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