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