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