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