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