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