8e28c1fec202652210a7ed53596760195e4ba987
[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;
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                 charge = 0;
308                 if (mpnt->vm_flags & VM_ACCOUNT) {
309                         unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
310                         if (security_vm_enough_memory(len))
311                                 goto fail_nomem;
312                         charge = len;
313                 }
314                 tmp = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL);
315                 if (!tmp)
316                         goto fail_nomem;
317                 *tmp = *mpnt;
318                 pol = mpol_copy(vma_policy(mpnt));
319                 retval = PTR_ERR(pol);
320                 if (IS_ERR(pol))
321                         goto fail_nomem_policy;
322                 vma_set_policy(tmp, pol);
323                 tmp->vm_flags &= ~VM_LOCKED;
324                 tmp->vm_mm = mm;
325                 tmp->vm_next = NULL;
326                 anon_vma_link(tmp);
327                 vma_prio_tree_init(tmp);
328                 file = tmp->vm_file;
329                 if (file) {
330                         struct inode *inode = file->f_dentry->d_inode;
331                         get_file(file);
332                         if (tmp->vm_flags & VM_DENYWRITE)
333                                 atomic_dec(&inode->i_writecount);
334       
335                         /* insert tmp into the share list, just after mpnt */
336                         spin_lock(&file->f_mapping->i_mmap_lock);
337                         flush_dcache_mmap_lock(file->f_mapping);
338                         vma_prio_tree_add(tmp, mpnt);
339                         flush_dcache_mmap_unlock(file->f_mapping);
340                         spin_unlock(&file->f_mapping->i_mmap_lock);
341                 }
342
343                 /*
344                  * Link in the new vma and copy the page table entries:
345                  * link in first so that swapoff can see swap entries,
346                  * and try_to_unmap_one's find_vma find the new vma.
347                  */
348                 spin_lock(&mm->page_table_lock);
349                 *pprev = tmp;
350                 pprev = &tmp->vm_next;
351
352                 __vma_link_rb(mm, tmp, rb_link, rb_parent);
353                 rb_link = &tmp->vm_rb.rb_right;
354                 rb_parent = &tmp->vm_rb;
355
356                 mm->map_count++;
357                 retval = copy_page_range(mm, current->mm, tmp);
358                 spin_unlock(&mm->page_table_lock);
359
360                 if (tmp->vm_ops && tmp->vm_ops->open)
361                         tmp->vm_ops->open(tmp);
362
363                 if (retval)
364                         goto out;
365         }
366         retval = 0;
367
368 out:
369         flush_tlb_mm(current->mm);
370         up_write(&oldmm->mmap_sem);
371         return retval;
372 fail_nomem_policy:
373         kmem_cache_free(vm_area_cachep, tmp);
374 fail_nomem:
375         retval = -ENOMEM;
376         vm_unacct_memory(charge);
377         goto out;
378 }
379
380 static inline int mm_alloc_pgd(struct mm_struct * mm)
381 {
382         mm->pgd = pgd_alloc(mm);
383         if (unlikely(!mm->pgd))
384                 return -ENOMEM;
385         return 0;
386 }
387
388 static inline void mm_free_pgd(struct mm_struct * mm)
389 {
390         pgd_free(mm->pgd);
391 }
392 #else
393 #define dup_mmap(mm, oldmm)     (0)
394 #define mm_alloc_pgd(mm)        (0)
395 #define mm_free_pgd(mm)
396 #endif /* CONFIG_MMU */
397
398 spinlock_t mmlist_lock __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
399 int mmlist_nr;
400
401 #define allocate_mm()   (kmem_cache_alloc(mm_cachep, SLAB_KERNEL))
402 #define free_mm(mm)     (kmem_cache_free(mm_cachep, (mm)))
403
404 #include <linux/init_task.h>
405
406 static struct mm_struct * mm_init(struct mm_struct * mm)
407 {
408         atomic_set(&mm->mm_users, 1);
409         atomic_set(&mm->mm_count, 1);
410         init_rwsem(&mm->mmap_sem);
411         mm->core_waiters = 0;
412         mm->page_table_lock = SPIN_LOCK_UNLOCKED;
413         mm->ioctx_list_lock = RW_LOCK_UNLOCKED;
414         mm->ioctx_list = NULL;
415         mm->default_kioctx = (struct kioctx)INIT_KIOCTX(mm->default_kioctx, *mm);
416         mm->free_area_cache = TASK_UNMAPPED_BASE;
417
418         if (likely(!mm_alloc_pgd(mm))) {
419                 mm->def_flags = 0;
420                 return mm;
421         }
422         free_mm(mm);
423         return NULL;
424 }
425
426 /*
427  * Allocate and initialize an mm_struct.
428  */
429 struct mm_struct * mm_alloc(void)
430 {
431         struct mm_struct * mm;
432
433         mm = allocate_mm();
434         if (mm) {
435                 memset(mm, 0, sizeof(*mm));
436                 mm = mm_init(mm);
437         }
438         return mm;
439 }
440
441 /*
442  * Called when the last reference to the mm
443  * is dropped: either by a lazy thread or by
444  * mmput. Free the page directory and the mm.
445  */
446 void fastcall __mmdrop(struct mm_struct *mm)
447 {
448         BUG_ON(mm == &init_mm);
449         mm_free_pgd(mm);
450         destroy_context(mm);
451         free_mm(mm);
452 }
453
454 /*
455  * Decrement the use count and release all resources for an mm.
456  */
457 void mmput(struct mm_struct *mm)
458 {
459         if (atomic_dec_and_lock(&mm->mm_users, &mmlist_lock)) {
460                 list_del(&mm->mmlist);
461                 mmlist_nr--;
462                 spin_unlock(&mmlist_lock);
463                 exit_aio(mm);
464                 exit_mmap(mm);
465                 mmdrop(mm);
466         }
467 }
468
469 /*
470  * Checks if the use count of an mm is non-zero and if so
471  * returns a reference to it after bumping up the use count.
472  * If the use count is zero, it means this mm is going away,
473  * so return NULL.
474  */
475 struct mm_struct *mmgrab(struct mm_struct *mm)
476 {
477         spin_lock(&mmlist_lock);
478         if (!atomic_read(&mm->mm_users))
479                 mm = NULL;
480         else
481                 atomic_inc(&mm->mm_users);
482         spin_unlock(&mmlist_lock);
483         return mm;
484 }
485
486 /* Please note the differences between mmput and mm_release.
487  * mmput is called whenever we stop holding onto a mm_struct,
488  * error success whatever.
489  *
490  * mm_release is called after a mm_struct has been removed
491  * from the current process.
492  *
493  * This difference is important for error handling, when we
494  * only half set up a mm_struct for a new process and need to restore
495  * the old one.  Because we mmput the new mm_struct before
496  * restoring the old one. . .
497  * Eric Biederman 10 January 1998
498  */
499 void mm_release(struct task_struct *tsk, struct mm_struct *mm)
500 {
501         struct completion *vfork_done = tsk->vfork_done;
502
503         /* Get rid of any cached register state */
504         deactivate_mm(tsk, mm);
505
506         /* notify parent sleeping on vfork() */
507         if (vfork_done) {
508                 tsk->vfork_done = NULL;
509                 complete(vfork_done);
510         }
511         if (tsk->clear_child_tid && atomic_read(&mm->mm_users) > 1) {
512                 u32 __user * tidptr = tsk->clear_child_tid;
513                 tsk->clear_child_tid = NULL;
514
515                 /*
516                  * We don't check the error code - if userspace has
517                  * not set up a proper pointer then tough luck.
518                  */
519                 put_user(0, tidptr);
520                 sys_futex(tidptr, FUTEX_WAKE, 1, NULL, NULL, 0);
521         }
522 }
523
524 static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
525 {
526         struct mm_struct * mm, *oldmm;
527         int retval;
528
529         tsk->min_flt = tsk->maj_flt = 0;
530         tsk->cmin_flt = tsk->cmaj_flt = 0;
531         tsk->nvcsw = tsk->nivcsw = tsk->cnvcsw = tsk->cnivcsw = 0;
532
533         tsk->mm = NULL;
534         tsk->active_mm = NULL;
535
536         /*
537          * Are we cloning a kernel thread?
538          *
539          * We need to steal a active VM for that..
540          */
541         oldmm = current->mm;
542         if (!oldmm)
543                 return 0;
544
545         if (clone_flags & CLONE_VM) {
546                 atomic_inc(&oldmm->mm_users);
547                 mm = oldmm;
548                 /*
549                  * There are cases where the PTL is held to ensure no
550                  * new threads start up in user mode using an mm, which
551                  * allows optimizing out ipis; the tlb_gather_mmu code
552                  * is an example.
553                  */
554                 spin_unlock_wait(&oldmm->page_table_lock);
555                 goto good_mm;
556         }
557
558         retval = -ENOMEM;
559         mm = allocate_mm();
560         if (!mm)
561                 goto fail_nomem;
562
563         /* Copy the current MM stuff.. */
564         memcpy(mm, oldmm, sizeof(*mm));
565         if (!mm_init(mm))
566                 goto fail_nomem;
567
568         if (init_new_context(tsk,mm))
569                 goto fail_nocontext;
570
571         retval = dup_mmap(mm, oldmm);
572         if (retval)
573                 goto free_pt;
574
575 good_mm:
576         tsk->mm = mm;
577         tsk->active_mm = mm;
578         return 0;
579
580 free_pt:
581         mmput(mm);
582 fail_nomem:
583         return retval;
584
585 fail_nocontext:
586         /*
587          * If init_new_context() failed, we cannot use mmput() to free the mm
588          * because it calls destroy_context()
589          */
590         mm_free_pgd(mm);
591         free_mm(mm);
592         return retval;
593 }
594
595 static inline struct fs_struct *__copy_fs_struct(struct fs_struct *old)
596 {
597         struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL);
598         /* We don't need to lock fs - think why ;-) */
599         if (fs) {
600                 atomic_set(&fs->count, 1);
601                 fs->lock = RW_LOCK_UNLOCKED;
602                 fs->umask = old->umask;
603                 read_lock(&old->lock);
604                 fs->rootmnt = mntget(old->rootmnt);
605                 fs->root = dget(old->root);
606                 fs->pwdmnt = mntget(old->pwdmnt);
607                 fs->pwd = dget(old->pwd);
608                 if (old->altroot) {
609                         fs->altrootmnt = mntget(old->altrootmnt);
610                         fs->altroot = dget(old->altroot);
611                 } else {
612                         fs->altrootmnt = NULL;
613                         fs->altroot = NULL;
614                 }
615                 read_unlock(&old->lock);
616         }
617         return fs;
618 }
619
620 struct fs_struct *copy_fs_struct(struct fs_struct *old)
621 {
622         return __copy_fs_struct(old);
623 }
624
625 EXPORT_SYMBOL_GPL(copy_fs_struct);
626
627 static inline int copy_fs(unsigned long clone_flags, struct task_struct * tsk)
628 {
629         if (clone_flags & CLONE_FS) {
630                 atomic_inc(&current->fs->count);
631                 return 0;
632         }
633         tsk->fs = __copy_fs_struct(current->fs);
634         if (!tsk->fs)
635                 return -ENOMEM;
636         return 0;
637 }
638
639 static int count_open_files(struct files_struct *files, int size)
640 {
641         int i;
642
643         /* Find the last open fd */
644         for (i = size/(8*sizeof(long)); i > 0; ) {
645                 if (files->open_fds->fds_bits[--i])
646                         break;
647         }
648         i = (i+1) * 8 * sizeof(long);
649         return i;
650 }
651
652 static int copy_files(unsigned long clone_flags, struct task_struct * tsk)
653 {
654         struct files_struct *oldf, *newf;
655         struct file **old_fds, **new_fds;
656         int open_files, nfds, size, i, error = 0;
657
658         /*
659          * A background process may not have any files ...
660          */
661         oldf = current->files;
662         if (!oldf)
663                 goto out;
664
665         if (clone_flags & CLONE_FILES) {
666                 atomic_inc(&oldf->count);
667                 goto out;
668         }
669
670         /*
671          * Note: we may be using current for both targets (See exec.c)
672          * This works because we cache current->files (old) as oldf. Don't
673          * break this.
674          */
675         tsk->files = NULL;
676         error = -ENOMEM;
677         newf = kmem_cache_alloc(files_cachep, SLAB_KERNEL);
678         if (!newf) 
679                 goto out;
680
681         atomic_set(&newf->count, 1);
682
683         newf->file_lock     = SPIN_LOCK_UNLOCKED;
684         newf->next_fd       = 0;
685         newf->max_fds       = NR_OPEN_DEFAULT;
686         newf->max_fdset     = __FD_SETSIZE;
687         newf->close_on_exec = &newf->close_on_exec_init;
688         newf->open_fds      = &newf->open_fds_init;
689         newf->fd            = &newf->fd_array[0];
690
691         /* We don't yet have the oldf readlock, but even if the old
692            fdset gets grown now, we'll only copy up to "size" fds */
693         size = oldf->max_fdset;
694         if (size > __FD_SETSIZE) {
695                 newf->max_fdset = 0;
696                 spin_lock(&newf->file_lock);
697                 error = expand_fdset(newf, size-1);
698                 spin_unlock(&newf->file_lock);
699                 if (error)
700                         goto out_release;
701         }
702         spin_lock(&oldf->file_lock);
703
704         open_files = count_open_files(oldf, size);
705
706         /*
707          * Check whether we need to allocate a larger fd array.
708          * Note: we're not a clone task, so the open count won't
709          * change.
710          */
711         nfds = NR_OPEN_DEFAULT;
712         if (open_files > nfds) {
713                 spin_unlock(&oldf->file_lock);
714                 newf->max_fds = 0;
715                 spin_lock(&newf->file_lock);
716                 error = expand_fd_array(newf, open_files-1);
717                 spin_unlock(&newf->file_lock);
718                 if (error) 
719                         goto out_release;
720                 nfds = newf->max_fds;
721                 spin_lock(&oldf->file_lock);
722         }
723
724         old_fds = oldf->fd;
725         new_fds = newf->fd;
726
727         memcpy(newf->open_fds->fds_bits, oldf->open_fds->fds_bits, open_files/8);
728         memcpy(newf->close_on_exec->fds_bits, oldf->close_on_exec->fds_bits, open_files/8);
729
730         for (i = open_files; i != 0; i--) {
731                 struct file *f = *old_fds++;
732                 if (f)
733                         get_file(f);
734                 *new_fds++ = f;
735         }
736         spin_unlock(&oldf->file_lock);
737
738         /* compute the remainder to be cleared */
739         size = (newf->max_fds - open_files) * sizeof(struct file *);
740
741         /* This is long word aligned thus could use a optimized version */ 
742         memset(new_fds, 0, size); 
743
744         if (newf->max_fdset > open_files) {
745                 int left = (newf->max_fdset-open_files)/8;
746                 int start = open_files / (8 * sizeof(unsigned long));
747
748                 memset(&newf->open_fds->fds_bits[start], 0, left);
749                 memset(&newf->close_on_exec->fds_bits[start], 0, left);
750         }
751
752         tsk->files = newf;
753         error = 0;
754 out:
755         return error;
756
757 out_release:
758         free_fdset (newf->close_on_exec, newf->max_fdset);
759         free_fdset (newf->open_fds, newf->max_fdset);
760         kmem_cache_free(files_cachep, newf);
761         goto out;
762 }
763
764 /*
765  *      Helper to unshare the files of the current task.
766  *      We don't want to expose copy_files internals to
767  *      the exec layer of the kernel.
768  */
769
770 int unshare_files(void)
771 {
772         struct files_struct *files  = current->files;
773         int rc;
774
775         if(!files)
776                 BUG();
777
778         /* This can race but the race causes us to copy when we don't
779            need to and drop the copy */
780         if(atomic_read(&files->count) == 1)
781         {
782                 atomic_inc(&files->count);
783                 return 0;
784         }
785         rc = copy_files(0, current);
786         if(rc)
787                 current->files = files;
788         return rc;
789 }
790
791 EXPORT_SYMBOL(unshare_files);
792
793 static inline int copy_sighand(unsigned long clone_flags, struct task_struct * tsk)
794 {
795         struct sighand_struct *sig;
796
797         if (clone_flags & (CLONE_SIGHAND | CLONE_THREAD)) {
798                 atomic_inc(&current->sighand->count);
799                 return 0;
800         }
801         sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
802         tsk->sighand = sig;
803         if (!sig)
804                 return -ENOMEM;
805         spin_lock_init(&sig->siglock);
806         atomic_set(&sig->count, 1);
807         memcpy(sig->action, current->sighand->action, sizeof(sig->action));
808         return 0;
809 }
810
811 static inline int copy_signal(unsigned long clone_flags, struct task_struct * tsk)
812 {
813         struct signal_struct *sig;
814
815         if (clone_flags & CLONE_THREAD) {
816                 atomic_inc(&current->signal->count);
817                 return 0;
818         }
819         sig = kmem_cache_alloc(signal_cachep, GFP_KERNEL);
820         tsk->signal = sig;
821         if (!sig)
822                 return -ENOMEM;
823         atomic_set(&sig->count, 1);
824         sig->group_exit = 0;
825         sig->group_exit_code = 0;
826         sig->group_exit_task = NULL;
827         sig->group_stop_count = 0;
828         sig->curr_target = NULL;
829         init_sigpending(&sig->shared_pending);
830         INIT_LIST_HEAD(&sig->posix_timers);
831
832         sig->tty = current->signal->tty;
833         sig->pgrp = process_group(current);
834         sig->session = current->signal->session;
835         sig->leader = 0;        /* session leadership doesn't inherit */
836         sig->tty_old_pgrp = 0;
837
838         return 0;
839 }
840
841 static inline void copy_flags(unsigned long clone_flags, struct task_struct *p)
842 {
843         unsigned long new_flags = p->flags;
844
845         new_flags &= ~PF_SUPERPRIV;
846         new_flags |= PF_FORKNOEXEC;
847         if (!(clone_flags & CLONE_PTRACE))
848                 p->ptrace = 0;
849         p->flags = new_flags;
850 }
851
852 asmlinkage long sys_set_tid_address(int __user *tidptr)
853 {
854         current->clear_child_tid = tidptr;
855
856         return current->pid;
857 }
858
859 /*
860  * This creates a new process as a copy of the old one,
861  * but does not actually start it yet.
862  *
863  * It copies the registers, and all the appropriate
864  * parts of the process environment (as per the clone
865  * flags). The actual kick-off is left to the caller.
866  */
867 struct task_struct *copy_process(unsigned long clone_flags,
868                                  unsigned long stack_start,
869                                  struct pt_regs *regs,
870                                  unsigned long stack_size,
871                                  int __user *parent_tidptr,
872                                  int __user *child_tidptr)
873 {
874         int retval;
875         struct task_struct *p = NULL;
876
877         if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
878                 return ERR_PTR(-EINVAL);
879
880         /*
881          * Thread groups must share signals as well, and detached threads
882          * can only be started up within the thread group.
883          */
884         if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
885                 return ERR_PTR(-EINVAL);
886
887         /*
888          * Shared signal handlers imply shared VM. By way of the above,
889          * thread groups also imply shared VM. Blocking this case allows
890          * for various simplifications in other code.
891          */
892         if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
893                 return ERR_PTR(-EINVAL);
894
895         retval = security_task_create(clone_flags);
896         if (retval)
897                 goto fork_out;
898
899         retval = -ENOMEM;
900         p = dup_task_struct(current);
901         if (!p)
902                 goto fork_out;
903
904         retval = -EAGAIN;
905         if (atomic_read(&p->user->processes) >=
906                         p->rlim[RLIMIT_NPROC].rlim_cur) {
907                 if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
908                                 p->user != &root_user)
909                         goto bad_fork_free;
910         }
911
912         atomic_inc(&p->user->__count);
913         atomic_inc(&p->user->processes);
914         get_group_info(p->group_info);
915
916         /*
917          * If multiple threads are within copy_process(), then this check
918          * triggers too late. This doesn't hurt, the check is only there
919          * to stop root fork bombs.
920          */
921         if (nr_threads >= max_threads)
922                 goto bad_fork_cleanup_count;
923
924         if (!try_module_get(p->thread_info->exec_domain->module))
925                 goto bad_fork_cleanup_count;
926
927         if (p->binfmt && !try_module_get(p->binfmt->module))
928                 goto bad_fork_cleanup_put_domain;
929
930         p->did_exec = 0;
931         copy_flags(clone_flags, p);
932         if (clone_flags & CLONE_IDLETASK)
933                 p->pid = 0;
934         else {
935                 p->pid = alloc_pidmap();
936                 if (p->pid == -1)
937                         goto bad_fork_cleanup;
938         }
939         retval = -EFAULT;
940         if (clone_flags & CLONE_PARENT_SETTID)
941                 if (put_user(p->pid, parent_tidptr))
942                         goto bad_fork_cleanup;
943
944         p->proc_dentry = NULL;
945
946         INIT_LIST_HEAD(&p->children);
947         INIT_LIST_HEAD(&p->sibling);
948         init_waitqueue_head(&p->wait_chldexit);
949         p->vfork_done = NULL;
950         spin_lock_init(&p->alloc_lock);
951         spin_lock_init(&p->proc_lock);
952
953         clear_tsk_thread_flag(p, TIF_SIGPENDING);
954         init_sigpending(&p->pending);
955
956         p->it_real_value = p->it_virt_value = p->it_prof_value = 0;
957         p->it_real_incr = p->it_virt_incr = p->it_prof_incr = 0;
958         init_timer(&p->real_timer);
959         p->real_timer.data = (unsigned long) p;
960
961         p->utime = p->stime = 0;
962         p->cutime = p->cstime = 0;
963         p->lock_depth = -1;             /* -1 = no lock */
964         p->start_time = get_jiffies_64();
965         p->security = NULL;
966         p->io_context = NULL;
967         p->audit_context = NULL;
968 #ifdef CONFIG_NUMA
969         p->mempolicy = mpol_copy(p->mempolicy);
970         if (IS_ERR(p->mempolicy)) {
971                 retval = PTR_ERR(p->mempolicy);
972                 p->mempolicy = NULL;
973                 goto bad_fork_cleanup;
974         }
975 #endif
976
977         if ((retval = security_task_alloc(p)))
978                 goto bad_fork_cleanup_policy;
979         if ((retval = audit_alloc(p)))
980                 goto bad_fork_cleanup_security;
981         /* copy all the process information */
982         if ((retval = copy_semundo(clone_flags, p)))
983                 goto bad_fork_cleanup_audit;
984         if ((retval = copy_files(clone_flags, p)))
985                 goto bad_fork_cleanup_semundo;
986         if ((retval = copy_fs(clone_flags, p)))
987                 goto bad_fork_cleanup_files;
988         if ((retval = copy_sighand(clone_flags, p)))
989                 goto bad_fork_cleanup_fs;
990         if ((retval = copy_signal(clone_flags, p)))
991                 goto bad_fork_cleanup_sighand;
992         if ((retval = copy_mm(clone_flags, p)))
993                 goto bad_fork_cleanup_signal;
994         if ((retval = copy_namespace(clone_flags, p)))
995                 goto bad_fork_cleanup_mm;
996         retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs);
997         if (retval)
998                 goto bad_fork_cleanup_namespace;
999
1000         p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
1001         /*
1002          * Clear TID on mm_release()?
1003          */
1004         p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
1005
1006         /*
1007          * Syscall tracing should be turned off in the child regardless
1008          * of CLONE_PTRACE.
1009          */
1010         clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
1011
1012         /* Our parent execution domain becomes current domain
1013            These must match for thread signalling to apply */
1014            
1015         p->parent_exec_id = p->self_exec_id;
1016
1017         /* ok, now we should be set up.. */
1018         p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
1019         p->pdeath_signal = 0;
1020
1021         /* Perform scheduler related setup */
1022         sched_fork(p);
1023
1024         /*
1025          * Ok, make it visible to the rest of the system.
1026          * We dont wake it up yet.
1027          */
1028         p->tgid = p->pid;
1029         p->group_leader = p;
1030         INIT_LIST_HEAD(&p->ptrace_children);
1031         INIT_LIST_HEAD(&p->ptrace_list);
1032
1033         /* Need tasklist lock for parent etc handling! */
1034         write_lock_irq(&tasklist_lock);
1035         /*
1036          * Check for pending SIGKILL! The new thread should not be allowed
1037          * to slip out of an OOM kill. (or normal SIGKILL.)
1038          */
1039         if (sigismember(&current->pending.signal, SIGKILL)) {
1040                 write_unlock_irq(&tasklist_lock);
1041                 retval = -EINTR;
1042                 goto bad_fork_cleanup_namespace;
1043         }
1044
1045         /* CLONE_PARENT re-uses the old parent */
1046         if (clone_flags & CLONE_PARENT)
1047                 p->real_parent = current->real_parent;
1048         else
1049                 p->real_parent = current;
1050         p->parent = p->real_parent;
1051
1052         if (clone_flags & CLONE_THREAD) {
1053                 spin_lock(&current->sighand->siglock);
1054                 /*
1055                  * Important: if an exit-all has been started then
1056                  * do not create this new thread - the whole thread
1057                  * group is supposed to exit anyway.
1058                  */
1059                 if (current->signal->group_exit) {
1060                         spin_unlock(&current->sighand->siglock);
1061                         write_unlock_irq(&tasklist_lock);
1062                         retval = -EAGAIN;
1063                         goto bad_fork_cleanup_namespace;
1064                 }
1065                 p->tgid = current->tgid;
1066                 p->group_leader = current->group_leader;
1067
1068                 if (current->signal->group_stop_count > 0) {
1069                         /*
1070                          * There is an all-stop in progress for the group.
1071                          * We ourselves will stop as soon as we check signals.
1072                          * Make the new thread part of that group stop too.
1073                          */
1074                         current->signal->group_stop_count++;
1075                         set_tsk_thread_flag(p, TIF_SIGPENDING);
1076                 }
1077
1078                 spin_unlock(&current->sighand->siglock);
1079         }
1080
1081         SET_LINKS(p);
1082         if (p->ptrace & PT_PTRACED)
1083                 __ptrace_link(p, current->parent);
1084
1085         attach_pid(p, PIDTYPE_PID, p->pid);
1086         if (thread_group_leader(p)) {
1087                 attach_pid(p, PIDTYPE_TGID, p->tgid);
1088                 attach_pid(p, PIDTYPE_PGID, process_group(p));
1089                 attach_pid(p, PIDTYPE_SID, p->signal->session);
1090                 if (p->pid)
1091                         __get_cpu_var(process_counts)++;
1092         } else
1093                 link_pid(p, p->pids + PIDTYPE_TGID, &p->group_leader->pids[PIDTYPE_TGID].pid);
1094
1095         nr_threads++;
1096         write_unlock_irq(&tasklist_lock);
1097         retval = 0;
1098
1099 fork_out:
1100         if (retval)
1101                 return ERR_PTR(retval);
1102         return p;
1103
1104 bad_fork_cleanup_namespace:
1105         exit_namespace(p);
1106 bad_fork_cleanup_mm:
1107         exit_mm(p);
1108         if (p->active_mm)
1109                 mmdrop(p->active_mm);
1110 bad_fork_cleanup_signal:
1111         exit_signal(p);
1112 bad_fork_cleanup_sighand:
1113         exit_sighand(p);
1114 bad_fork_cleanup_fs:
1115         exit_fs(p); /* blocking */
1116 bad_fork_cleanup_files:
1117         exit_files(p); /* blocking */
1118 bad_fork_cleanup_semundo:
1119         exit_sem(p);
1120 bad_fork_cleanup_audit:
1121         audit_free(p);
1122 bad_fork_cleanup_security:
1123         security_task_free(p);
1124 bad_fork_cleanup_policy:
1125 #ifdef CONFIG_NUMA
1126         mpol_free(p->mempolicy);
1127 #endif
1128 bad_fork_cleanup:
1129         if (p->pid > 0)
1130                 free_pidmap(p->pid);
1131         if (p->binfmt)
1132                 module_put(p->binfmt->module);
1133 bad_fork_cleanup_put_domain:
1134         module_put(p->thread_info->exec_domain->module);
1135 bad_fork_cleanup_count:
1136         put_group_info(p->group_info);
1137         atomic_dec(&p->user->processes);
1138         free_uid(p->user);
1139 bad_fork_free:
1140         free_task(p);
1141         goto fork_out;
1142 }
1143
1144 static inline int fork_traceflag (unsigned clone_flags)
1145 {
1146         if (clone_flags & (CLONE_UNTRACED | CLONE_IDLETASK))
1147                 return 0;
1148         else if (clone_flags & CLONE_VFORK) {
1149                 if (current->ptrace & PT_TRACE_VFORK)
1150                         return PTRACE_EVENT_VFORK;
1151         } else if ((clone_flags & CSIGNAL) != SIGCHLD) {
1152                 if (current->ptrace & PT_TRACE_CLONE)
1153                         return PTRACE_EVENT_CLONE;
1154         } else if (current->ptrace & PT_TRACE_FORK)
1155                 return PTRACE_EVENT_FORK;
1156
1157         return 0;
1158 }
1159
1160 /*
1161  *  Ok, this is the main fork-routine.
1162  *
1163  * It copies the process, and if successful kick-starts
1164  * it and waits for it to finish using the VM if required.
1165  */
1166 long do_fork(unsigned long clone_flags,
1167               unsigned long stack_start,
1168               struct pt_regs *regs,
1169               unsigned long stack_size,
1170               int __user *parent_tidptr,
1171               int __user *child_tidptr)
1172 {
1173         struct task_struct *p;
1174         int trace = 0;
1175         long pid;
1176
1177         if (unlikely(current->ptrace)) {
1178                 trace = fork_traceflag (clone_flags);
1179                 if (trace)
1180                         clone_flags |= CLONE_PTRACE;
1181         }
1182
1183         p = copy_process(clone_flags, stack_start, regs, stack_size, parent_tidptr, child_tidptr);
1184         /*
1185          * Do this prior waking up the new thread - the thread pointer
1186          * might get invalid after that point, if the thread exits quickly.
1187          */
1188         pid = IS_ERR(p) ? PTR_ERR(p) : p->pid;
1189
1190         if (!IS_ERR(p)) {
1191                 struct completion vfork;
1192
1193                 if (clone_flags & CLONE_VFORK) {
1194                         p->vfork_done = &vfork;
1195                         init_completion(&vfork);
1196                 }
1197
1198                 if ((p->ptrace & PT_PTRACED) || (clone_flags & CLONE_STOPPED)) {
1199                         /*
1200                          * We'll start up with an immediate SIGSTOP.
1201                          */
1202                         sigaddset(&p->pending.signal, SIGSTOP);
1203                         set_tsk_thread_flag(p, TIF_SIGPENDING);
1204                 }
1205
1206                 if (!(clone_flags & CLONE_STOPPED)) {
1207                         /*
1208                          * Do the wakeup last. On SMP we treat fork() and
1209                          * CLONE_VM separately, because fork() has already
1210                          * created cache footprint on this CPU (due to
1211                          * copying the pagetables), hence migration would
1212                          * probably be costy. Threads on the other hand
1213                          * have less traction to the current CPU, and if
1214                          * there's an imbalance then the scheduler can
1215                          * migrate this fresh thread now, before it
1216                          * accumulates a larger cache footprint:
1217                          */
1218                         if (clone_flags & CLONE_VM)
1219                                 wake_up_forked_thread(p);
1220                         else
1221                                 wake_up_forked_process(p);
1222                 } else {
1223                         int cpu = get_cpu();
1224
1225                         p->state = TASK_STOPPED;
1226                         if (cpu_is_offline(task_cpu(p)))
1227                                 set_task_cpu(p, cpu);
1228
1229                         put_cpu();
1230                 }
1231                 ++total_forks;
1232
1233                 if (unlikely (trace)) {
1234                         current->ptrace_message = pid;
1235                         ptrace_notify ((trace << 8) | SIGTRAP);
1236                 }
1237
1238                 if (clone_flags & CLONE_VFORK) {
1239                         wait_for_completion(&vfork);
1240                         if (unlikely (current->ptrace & PT_TRACE_VFORK_DONE))
1241                                 ptrace_notify ((PTRACE_EVENT_VFORK_DONE << 8) | SIGTRAP);
1242                 } else
1243                         /*
1244                          * Let the child process run first, to avoid most of the
1245                          * COW overhead when the child exec()s afterwards.
1246                          */
1247                         set_need_resched();
1248         }
1249         return pid;
1250 }
1251
1252 /* SLAB cache for signal_struct structures (tsk->signal) */
1253 kmem_cache_t *signal_cachep;
1254
1255 /* SLAB cache for sighand_struct structures (tsk->sighand) */
1256 kmem_cache_t *sighand_cachep;
1257
1258 /* SLAB cache for files_struct structures (tsk->files) */
1259 kmem_cache_t *files_cachep;
1260
1261 /* SLAB cache for fs_struct structures (tsk->fs) */
1262 kmem_cache_t *fs_cachep;
1263
1264 /* SLAB cache for vm_area_struct structures */
1265 kmem_cache_t *vm_area_cachep;
1266
1267 /* SLAB cache for mm_struct structures (tsk->mm) */
1268 kmem_cache_t *mm_cachep;
1269
1270 void __init proc_caches_init(void)
1271 {
1272         sighand_cachep = kmem_cache_create("sighand_cache",
1273                         sizeof(struct sighand_struct), 0,
1274                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1275         signal_cachep = kmem_cache_create("signal_cache",
1276                         sizeof(struct signal_struct), 0,
1277                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1278         files_cachep = kmem_cache_create("files_cache", 
1279                         sizeof(struct files_struct), 0,
1280                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1281         fs_cachep = kmem_cache_create("fs_cache", 
1282                         sizeof(struct fs_struct), 0,
1283                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1284         vm_area_cachep = kmem_cache_create("vm_area_struct",
1285                         sizeof(struct vm_area_struct), 0,
1286                         SLAB_PANIC, NULL, NULL);
1287         mm_cachep = kmem_cache_create("mm_struct",
1288                         sizeof(struct mm_struct), 0,
1289                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
1290 }