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