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