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