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