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