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