Merge to Fedora kernel-2.6.7-1.441
[linux-2.6.git] / arch / i386 / kernel / process.c
1 /*
2  *  linux/arch/i386/kernel/process.c
3  *
4  *  Copyright (C) 1995  Linus Torvalds
5  *
6  *  Pentium III FXSR, SSE support
7  *      Gareth Hughes <gareth@valinux.com>, May 2000
8  */
9
10 /*
11  * This file handles the architecture-dependent parts of process handling..
12  */
13
14 #include <stdarg.h>
15
16 #include <linux/errno.h>
17 #include <linux/sched.h>
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/mm.h>
21 #include <linux/elfcore.h>
22 #include <linux/smp.h>
23 #include <linux/smp_lock.h>
24 #include <linux/stddef.h>
25 #include <linux/slab.h>
26 #include <linux/vmalloc.h>
27 #include <linux/user.h>
28 #include <linux/a.out.h>
29 #include <linux/interrupt.h>
30 #include <linux/config.h>
31 #include <linux/version.h>
32 #include <linux/delay.h>
33 #include <linux/reboot.h>
34 #include <linux/init.h>
35 #include <linux/mc146818rtc.h>
36 #include <linux/module.h>
37 #include <linux/kallsyms.h>
38 #include <linux/ptrace.h>
39 #include <linux/mman.h>
40 #include <linux/random.h>
41
42 #include <asm/uaccess.h>
43 #include <asm/pgtable.h>
44 #include <asm/system.h>
45 #include <asm/io.h>
46 #include <asm/ldt.h>
47 #include <asm/processor.h>
48 #include <asm/i387.h>
49 #include <asm/irq.h>
50 #include <asm/desc.h>
51 #include <asm/atomic_kmap.h>
52 #ifdef CONFIG_MATH_EMULATION
53 #include <asm/math_emu.h>
54 #endif
55
56 #include <linux/irq.h>
57 #include <linux/err.h>
58
59 asmlinkage void ret_from_fork(void) __asm__("ret_from_fork");
60
61 int hlt_counter;
62
63 /*
64  * Return saved PC of a blocked thread.
65  */
66 unsigned long thread_saved_pc(struct task_struct *tsk)
67 {
68         return ((unsigned long *)tsk->thread.esp)[3];
69 }
70
71 /*
72  * Powermanagement idle function, if any..
73  */
74 void (*pm_idle)(void);
75
76 void disable_hlt(void)
77 {
78         hlt_counter++;
79 }
80
81 EXPORT_SYMBOL(disable_hlt);
82
83 void enable_hlt(void)
84 {
85         hlt_counter--;
86 }
87
88 EXPORT_SYMBOL(enable_hlt);
89
90 /*
91  * We use this if we don't have any better
92  * idle routine..
93  */
94 void default_idle(void)
95 {
96         if (!hlt_counter && current_cpu_data.hlt_works_ok) {
97                 local_irq_disable();
98                 if (!need_resched())
99                         safe_halt();
100                 else
101                         local_irq_enable();
102         }
103 }
104
105 /*
106  * On SMP it's slightly faster (but much more power-consuming!)
107  * to poll the ->work.need_resched flag instead of waiting for the
108  * cross-CPU IPI to arrive. Use this option with caution.
109  */
110 static void poll_idle (void)
111 {
112         int oldval;
113
114         local_irq_enable();
115
116         /*
117          * Deal with another CPU just having chosen a thread to
118          * run here:
119          */
120         oldval = test_and_clear_thread_flag(TIF_NEED_RESCHED);
121
122         if (!oldval) {
123                 set_thread_flag(TIF_POLLING_NRFLAG);
124                 asm volatile(
125                         "2:"
126                         "testl %0, %1;"
127                         "rep; nop;"
128                         "je 2b;"
129                         : : "i"(_TIF_NEED_RESCHED), "m" (current_thread_info()->flags));
130
131                 clear_thread_flag(TIF_POLLING_NRFLAG);
132         } else {
133                 set_need_resched();
134         }
135 }
136
137 /*
138  * The idle thread. There's no useful work to be
139  * done, so just try to conserve power and have a
140  * low exit latency (ie sit in a loop waiting for
141  * somebody to say that they'd like to reschedule)
142  */
143 void cpu_idle (void)
144 {
145         /* endless idle loop with no priority at all */
146         while (1) {
147                 while (!need_resched()) {
148                         void (*idle)(void) = pm_idle;
149
150                         if (!idle)
151                                 idle = default_idle;
152
153                         irq_stat[smp_processor_id()].idle_timestamp = jiffies;
154                         idle();
155                 }
156                 schedule();
157         }
158 }
159
160 /*
161  * This uses new MONITOR/MWAIT instructions on P4 processors with PNI,
162  * which can obviate IPI to trigger checking of need_resched.
163  * We execute MONITOR against need_resched and enter optimized wait state
164  * through MWAIT. Whenever someone changes need_resched, we would be woken
165  * up from MWAIT (without an IPI).
166  */
167 static void mwait_idle(void)
168 {
169         local_irq_enable();
170
171         if (!need_resched()) {
172                 set_thread_flag(TIF_POLLING_NRFLAG);
173                 do {
174                         __monitor((void *)&current_thread_info()->flags, 0, 0);
175                         if (need_resched())
176                                 break;
177                         __mwait(0, 0);
178                 } while (!need_resched());
179                 clear_thread_flag(TIF_POLLING_NRFLAG);
180         }
181 }
182
183 void __init select_idle_routine(const struct cpuinfo_x86 *c)
184 {
185         if (cpu_has(c, X86_FEATURE_MWAIT)) {
186                 printk("monitor/mwait feature present.\n");
187                 /*
188                  * Skip, if setup has overridden idle.
189                  * Also, take care of system with asymmetric CPUs.
190                  * Use, mwait_idle only if all cpus support it.
191                  * If not, we fallback to default_idle()
192                  */
193                 if (!pm_idle) {
194                         printk("using mwait in idle threads.\n");
195                         pm_idle = mwait_idle;
196                 }
197                 return;
198         }
199         pm_idle = default_idle;
200         return;
201 }
202
203 static int __init idle_setup (char *str)
204 {
205         if (!strncmp(str, "poll", 4)) {
206                 printk("using polling idle threads.\n");
207                 pm_idle = poll_idle;
208 #ifdef CONFIG_X86_SMP
209                 if (smp_num_siblings > 1)
210                         printk("WARNING: polling idle and HT enabled, performance may degrade.\n");
211 #endif
212         } else if (!strncmp(str, "halt", 4)) {
213                 printk("using halt in idle threads.\n");
214                 pm_idle = default_idle;
215         }
216
217         return 1;
218 }
219
220 __setup("idle=", idle_setup);
221
222 void show_regs(struct pt_regs * regs)
223 {
224         unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L;
225
226         printk("\n");
227         printk("Pid: %d, comm: %20s\n", current->pid, current->comm);
228         printk("EIP: %04x:[<%08lx>] CPU: %d\n",0xffff & regs->xcs,regs->eip, smp_processor_id());
229         print_symbol("EIP is at %s\n", regs->eip);
230
231         if (regs->xcs & 3)
232                 printk(" ESP: %04x:%08lx",0xffff & regs->xss,regs->esp);
233         printk(" EFLAGS: %08lx    %s  (%s)\n",regs->eflags, print_tainted(),UTS_RELEASE);
234         printk("EAX: %08lx EBX: %08lx ECX: %08lx EDX: %08lx\n",
235                 regs->eax,regs->ebx,regs->ecx,regs->edx);
236         printk("ESI: %08lx EDI: %08lx EBP: %08lx",
237                 regs->esi, regs->edi, regs->ebp);
238         printk(" DS: %04x ES: %04x\n",
239                 0xffff & regs->xds,0xffff & regs->xes);
240
241         __asm__("movl %%cr0, %0": "=r" (cr0));
242         __asm__("movl %%cr2, %0": "=r" (cr2));
243         __asm__("movl %%cr3, %0": "=r" (cr3));
244         /* This could fault if %cr4 does not exist */
245         __asm__("1: movl %%cr4, %0              \n"
246                 "2:                             \n"
247                 ".section __ex_table,\"a\"      \n"
248                 ".long 1b,2b                    \n"
249                 ".previous                      \n"
250                 : "=r" (cr4): "0" (0));
251         printk("CR0: %08lx CR2: %08lx CR3: %08lx CR4: %08lx\n", cr0, cr2, cr3, cr4);
252         show_trace(NULL, &regs->esp);
253 }
254
255 /*
256  * This gets run with %ebx containing the
257  * function to call, and %edx containing
258  * the "args".
259  */
260 extern void kernel_thread_helper(void);
261 __asm__(".section .text\n"
262         ".align 4\n"
263         "kernel_thread_helper:\n\t"
264         "movl %edx,%eax\n\t"
265         "pushl %edx\n\t"
266         "call *%ebx\n\t"
267         "pushl %eax\n\t"
268         "call do_exit\n"
269         ".previous");
270
271 /*
272  * Create a kernel thread
273  */
274 int kernel_thread(int (*fn)(void *), void * arg, unsigned long flags)
275 {
276         struct pt_regs regs;
277
278         memset(&regs, 0, sizeof(regs));
279
280         regs.ebx = (unsigned long) fn;
281         regs.edx = (unsigned long) arg;
282
283         regs.xds = __USER_DS;
284         regs.xes = __USER_DS;
285         regs.orig_eax = -1;
286         regs.eip = (unsigned long) kernel_thread_helper;
287         regs.xcs = __KERNEL_CS;
288         regs.eflags = X86_EFLAGS_IF | X86_EFLAGS_SF | X86_EFLAGS_PF | 0x2;
289
290         /* Ok, create the new process.. */
291         return do_fork(flags | CLONE_VM | CLONE_UNTRACED, 0, &regs, 0, NULL, NULL);
292 }
293
294 /*
295  * Free current thread data structures etc..
296  */
297 void exit_thread(void)
298 {
299         struct task_struct *tsk = current;
300
301         /* The process may have allocated an io port bitmap... nuke it. */
302         if (unlikely(NULL != tsk->thread.io_bitmap_ptr)) {
303                 int cpu = get_cpu();
304                 struct tss_struct *tss = init_tss + cpu;
305                 kfree(tsk->thread.io_bitmap_ptr);
306                 tsk->thread.io_bitmap_ptr = NULL;
307                 tss->io_bitmap_base = INVALID_IO_BITMAP_OFFSET;
308                 put_cpu();
309         }
310 }
311
312 void flush_thread(void)
313 {
314         struct task_struct *tsk = current;
315
316         memset(tsk->thread.debugreg, 0, sizeof(unsigned long)*8);
317 #ifdef CONFIG_X86_HIGH_ENTRY
318         clear_thread_flag(TIF_DB7);
319 #endif
320         memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array));        
321         /*
322          * Forget coprocessor state..
323          */
324         clear_fpu(tsk);
325         tsk->used_math = 0;
326 }
327
328 void release_thread(struct task_struct *dead_task)
329 {
330         if (dead_task->mm) {
331                 // temporary debugging check
332                 if (dead_task->mm->context.size) {
333                         printk("WARNING: dead process %8s still has LDT? <%d>\n",
334                                         dead_task->comm,
335                                         dead_task->mm->context.size);
336                         BUG();
337                 }
338         }
339
340         release_x86_irqs(dead_task);
341 }
342
343 /*
344  * This gets called before we allocate a new thread and copy
345  * the current task into it.
346  */
347 void prepare_to_copy(struct task_struct *tsk)
348 {
349         unlazy_fpu(tsk);
350 }
351
352 int copy_thread(int nr, unsigned long clone_flags, unsigned long esp,
353         unsigned long unused,
354         struct task_struct * p, struct pt_regs * regs)
355 {
356         struct pt_regs * childregs;
357         struct task_struct *tsk;
358         int err, i;
359
360         childregs = ((struct pt_regs *) (THREAD_SIZE + (unsigned long) p->thread_info)) - 1;
361         struct_cpy(childregs, regs);
362         childregs->eax = 0;
363         childregs->esp = esp;
364         p->set_child_tid = p->clear_child_tid = NULL;
365
366         p->thread.esp = (unsigned long) childregs;
367         p->thread.esp0 = (unsigned long) (childregs+1);
368
369         /*
370          * get the two stack pages, for the virtual stack.
371          *
372          * IMPORTANT: this code relies on the fact that the task
373          * structure is an THREAD_SIZE aligned piece of physical memory.
374          */
375         for (i = 0; i < ARRAY_SIZE(p->thread.stack_page); i++)
376                 p->thread.stack_page[i] =
377                                 virt_to_page((unsigned long)p->thread_info + (i*PAGE_SIZE));
378
379         p->thread.eip = (unsigned long) ret_from_fork;
380         p->thread_info->real_stack = p->thread_info;
381
382         savesegment(fs,p->thread.fs);
383         savesegment(gs,p->thread.gs);
384
385         tsk = current;
386         if (unlikely(NULL != tsk->thread.io_bitmap_ptr)) {
387                 p->thread.io_bitmap_ptr = kmalloc(IO_BITMAP_BYTES, GFP_KERNEL);
388                 if (!p->thread.io_bitmap_ptr)
389                         return -ENOMEM;
390                 memcpy(p->thread.io_bitmap_ptr, tsk->thread.io_bitmap_ptr,
391                         IO_BITMAP_BYTES);
392         }
393
394         /*
395          * Set a new TLS for the child thread?
396          */
397         if (clone_flags & CLONE_SETTLS) {
398                 struct desc_struct *desc;
399                 struct user_desc info;
400                 int idx;
401
402                 err = -EFAULT;
403                 if (copy_from_user(&info, (void __user *)childregs->esi, sizeof(info)))
404                         goto out;
405                 err = -EINVAL;
406                 if (LDT_empty(&info))
407                         goto out;
408
409                 idx = info.entry_number;
410                 if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
411                         goto out;
412
413                 desc = p->thread.tls_array + idx - GDT_ENTRY_TLS_MIN;
414                 desc->a = LDT_entry_a(&info);
415                 desc->b = LDT_entry_b(&info);
416         }
417
418         err = 0;
419  out:
420         if (err && p->thread.io_bitmap_ptr)
421                 kfree(p->thread.io_bitmap_ptr);
422         return err;
423 }
424
425 /*
426  * fill in the user structure for a core dump..
427  */
428 void dump_thread(struct pt_regs * regs, struct user * dump)
429 {
430         int i;
431
432 /* changed the size calculations - should hopefully work better. lbt */
433         dump->magic = CMAGIC;
434         dump->start_code = 0;
435         dump->start_stack = regs->esp & ~(PAGE_SIZE - 1);
436         dump->u_tsize = ((unsigned long) current->mm->end_code) >> PAGE_SHIFT;
437         dump->u_dsize = ((unsigned long) (current->mm->brk + (PAGE_SIZE-1))) >> PAGE_SHIFT;
438         dump->u_dsize -= dump->u_tsize;
439         dump->u_ssize = 0;
440         for (i = 0; i < 8; i++)
441                 dump->u_debugreg[i] = current->thread.debugreg[i];  
442
443         if (dump->start_stack < TASK_SIZE)
444                 dump->u_ssize = ((unsigned long) (TASK_SIZE - dump->start_stack)) >> PAGE_SHIFT;
445
446         dump->regs.ebx = regs->ebx;
447         dump->regs.ecx = regs->ecx;
448         dump->regs.edx = regs->edx;
449         dump->regs.esi = regs->esi;
450         dump->regs.edi = regs->edi;
451         dump->regs.ebp = regs->ebp;
452         dump->regs.eax = regs->eax;
453         dump->regs.ds = regs->xds;
454         dump->regs.es = regs->xes;
455         savesegment(fs,dump->regs.fs);
456         savesegment(gs,dump->regs.gs);
457         dump->regs.orig_eax = regs->orig_eax;
458         dump->regs.eip = regs->eip;
459         dump->regs.cs = regs->xcs;
460         dump->regs.eflags = regs->eflags;
461         dump->regs.esp = regs->esp;
462         dump->regs.ss = regs->xss;
463
464         dump->u_fpvalid = dump_fpu (regs, &dump->i387);
465 }
466
467 /* 
468  * Capture the user space registers if the task is not running (in user space)
469  */
470 int dump_task_regs(struct task_struct *tsk, elf_gregset_t *regs)
471 {
472         struct pt_regs ptregs;
473         
474         ptregs = *(struct pt_regs *)
475                 ((unsigned long)tsk->thread_info+THREAD_SIZE - sizeof(ptregs));
476         ptregs.xcs &= 0xffff;
477         ptregs.xds &= 0xffff;
478         ptregs.xes &= 0xffff;
479         ptregs.xss &= 0xffff;
480
481         elf_core_copy_regs(regs, &ptregs);
482
483         return 1;
484 }
485
486 /*
487  * This special macro can be used to load a debugging register
488  */
489 #define loaddebug(thread,register) \
490                 __asm__("movl %0,%%db" #register  \
491                         : /* no output */ \
492                         :"r" (thread->debugreg[register]))
493
494 /*
495  *      switch_to(x,yn) should switch tasks from x to y.
496  *
497  * We fsave/fwait so that an exception goes off at the right time
498  * (as a call from the fsave or fwait in effect) rather than to
499  * the wrong process. Lazy FP saving no longer makes any sense
500  * with modern CPU's, and this simplifies a lot of things (SMP
501  * and UP become the same).
502  *
503  * NOTE! We used to use the x86 hardware context switching. The
504  * reason for not using it any more becomes apparent when you
505  * try to recover gracefully from saved state that is no longer
506  * valid (stale segment register values in particular). With the
507  * hardware task-switch, there is no way to fix up bad state in
508  * a reasonable manner.
509  *
510  * The fact that Intel documents the hardware task-switching to
511  * be slow is a fairly red herring - this code is not noticeably
512  * faster. However, there _is_ some room for improvement here,
513  * so the performance issues may eventually be a valid point.
514  * More important, however, is the fact that this allows us much
515  * more flexibility.
516  *
517  * The return value (in %eax) will be the "prev" task after
518  * the task-switch, and shows up in ret_from_fork in entry.S,
519  * for example.
520  */
521 struct task_struct fastcall * __switch_to(struct task_struct *prev_p, struct task_struct *next_p)
522 {
523         struct thread_struct *prev = &prev_p->thread,
524                                  *next = &next_p->thread;
525         int cpu = smp_processor_id();
526         struct tss_struct *tss = init_tss + cpu;
527
528         /* never put a printk in __switch_to... printk() calls wake_up*() indirectly */
529
530         __unlazy_fpu(prev_p);
531         if (next_p->mm)
532                 load_user_cs_desc(cpu, next_p->mm);
533
534 #ifdef CONFIG_X86_HIGH_ENTRY
535 {
536         int i;
537         /*
538          * Set the ptes of the virtual stack. (NOTE: a one-page TLB flush is
539          * needed because otherwise NMIs could interrupt the
540          * user-return code with a virtual stack and stale TLBs.)
541          */
542         for (i = 0; i < ARRAY_SIZE(next->stack_page); i++) {
543                 __kunmap_atomic_type(KM_VSTACK_TOP-i);
544                 __kmap_atomic(next->stack_page[i], KM_VSTACK_TOP-i);
545         }
546         /*
547          * NOTE: here we rely on the task being the stack as well
548          */
549         next_p->thread_info->virtual_stack =
550                         (void *)__kmap_atomic_vaddr(KM_VSTACK_TOP);
551 }
552 #if defined(CONFIG_PREEMPT) && defined(CONFIG_SMP)
553         /*
554          * If next was preempted on entry from userspace to kernel,
555          * and now it's on a different cpu, we need to adjust %esp.
556          * This assumes that entry.S does not copy %esp while on the
557          * virtual stack (with interrupts enabled): which is so,
558          * except within __SWITCH_KERNELSPACE itself.
559          */
560         if (unlikely(next->esp >= TASK_SIZE)) {
561                 next->esp &= THREAD_SIZE - 1;
562                 next->esp |= (unsigned long) next_p->thread_info->virtual_stack;
563         }
564 #endif
565 #endif
566         /*
567          * Reload esp0, LDT and the page table pointer:
568          */
569         load_virtual_esp0(tss, next_p);
570
571         /*
572          * Load the per-thread Thread-Local Storage descriptor.
573          */
574         load_TLS(next, cpu);
575
576         /*
577          * Save away %fs and %gs. No need to save %es and %ds, as
578          * those are always kernel segments while inside the kernel.
579          */
580         asm volatile("movl %%fs,%0":"=m" (*(int *)&prev->fs));
581         asm volatile("movl %%gs,%0":"=m" (*(int *)&prev->gs));
582
583         /*
584          * Restore %fs and %gs if needed.
585          */
586         if (unlikely(prev->fs | prev->gs | next->fs | next->gs)) {
587                 loadsegment(fs, next->fs);
588                 loadsegment(gs, next->gs);
589         }
590
591         /*
592          * Now maybe reload the debug registers
593          */
594         if (unlikely(next->debugreg[7])) {
595                 loaddebug(next, 0);
596                 loaddebug(next, 1);
597                 loaddebug(next, 2);
598                 loaddebug(next, 3);
599                 /* no 4 and 5 */
600                 loaddebug(next, 6);
601                 loaddebug(next, 7);
602         }
603
604         if (unlikely(prev->io_bitmap_ptr || next->io_bitmap_ptr)) {
605                 if (next->io_bitmap_ptr) {
606                         /*
607                          * 4 cachelines copy ... not good, but not that
608                          * bad either. Anyone got something better?
609                          * This only affects processes which use ioperm().
610                          * [Putting the TSSs into 4k-tlb mapped regions
611                          * and playing VM tricks to switch the IO bitmap
612                          * is not really acceptable.]
613                          */
614                         memcpy(tss->io_bitmap, next->io_bitmap_ptr,
615                                 IO_BITMAP_BYTES);
616                         tss->io_bitmap_base = IO_BITMAP_OFFSET;
617                 } else
618                         /*
619                          * a bitmap offset pointing outside of the TSS limit
620                          * causes a nicely controllable SIGSEGV if a process
621                          * tries to use a port IO instruction. The first
622                          * sys_ioperm() call sets up the bitmap properly.
623                          */
624                         tss->io_bitmap_base = INVALID_IO_BITMAP_OFFSET;
625         }
626         return prev_p;
627 }
628
629 asmlinkage int sys_fork(struct pt_regs regs)
630 {
631         return do_fork(SIGCHLD, regs.esp, &regs, 0, NULL, NULL);
632 }
633
634 asmlinkage int sys_clone(struct pt_regs regs)
635 {
636         unsigned long clone_flags;
637         unsigned long newsp;
638         int __user *parent_tidptr, *child_tidptr;
639
640         clone_flags = regs.ebx;
641         newsp = regs.ecx;
642         parent_tidptr = (int __user *)regs.edx;
643         child_tidptr = (int __user *)regs.edi;
644         if (!newsp)
645                 newsp = regs.esp;
646         return do_fork(clone_flags & ~CLONE_IDLETASK, newsp, &regs, 0, parent_tidptr, child_tidptr);
647 }
648
649 /*
650  * This is trivial, and on the face of it looks like it
651  * could equally well be done in user mode.
652  *
653  * Not so, for quite unobvious reasons - register pressure.
654  * In user mode vfork() cannot have a stack frame, and if
655  * done by calling the "clone()" system call directly, you
656  * do not have enough call-clobbered registers to hold all
657  * the information you need.
658  */
659 asmlinkage int sys_vfork(struct pt_regs regs)
660 {
661         return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0, NULL, NULL);
662 }
663
664 /*
665  * sys_execve() executes a new program.
666  */
667 asmlinkage int sys_execve(struct pt_regs regs)
668 {
669         int error;
670         char * filename;
671
672         filename = getname((char __user *) regs.ebx);
673         error = PTR_ERR(filename);
674         if (IS_ERR(filename))
675                 goto out;
676         error = do_execve(filename,
677                         (char __user * __user *) regs.ecx,
678                         (char __user * __user *) regs.edx,
679                         &regs);
680         if (error == 0) {
681                 current->ptrace &= ~PT_DTRACE;
682                 /* Make sure we don't return using sysenter.. */
683                 set_thread_flag(TIF_IRET);
684         }
685         putname(filename);
686 out:
687         return error;
688 }
689
690 #define top_esp                (THREAD_SIZE - sizeof(unsigned long))
691 #define top_ebp                (THREAD_SIZE - 2*sizeof(unsigned long))
692
693 unsigned long get_wchan(struct task_struct *p)
694 {
695         unsigned long ebp, esp, eip;
696         unsigned long stack_page;
697         int count = 0;
698         if (!p || p == current || p->state == TASK_RUNNING)
699                 return 0;
700         stack_page = (unsigned long)p->thread_info;
701         esp = p->thread.esp;
702         if (!stack_page || esp < stack_page || esp > top_esp+stack_page)
703                 return 0;
704         /* include/asm-i386/system.h:switch_to() pushes ebp last. */
705         ebp = *(unsigned long *) esp;
706         do {
707                 if (ebp < stack_page || ebp > top_ebp+stack_page)
708                         return 0;
709                 eip = *(unsigned long *) (ebp+4);
710                 if (!in_sched_functions(eip))
711                         return eip;
712                 ebp = *(unsigned long *) ebp;
713         } while (count++ < 16);
714         return 0;
715 }
716
717 /*
718  * sys_alloc_thread_area: get a yet unused TLS descriptor index.
719  */
720 static int get_free_idx(void)
721 {
722         struct thread_struct *t = &current->thread;
723         int idx;
724
725         for (idx = 0; idx < GDT_ENTRY_TLS_ENTRIES; idx++)
726                 if (desc_empty(t->tls_array + idx))
727                         return idx + GDT_ENTRY_TLS_MIN;
728         return -ESRCH;
729 }
730
731 /*
732  * Set a given TLS descriptor:
733  */
734 asmlinkage int sys_set_thread_area(struct user_desc __user *u_info)
735 {
736         struct thread_struct *t = &current->thread;
737         struct user_desc info;
738         struct desc_struct *desc;
739         int cpu, idx;
740
741         if (copy_from_user(&info, u_info, sizeof(info)))
742                 return -EFAULT;
743         idx = info.entry_number;
744
745         /*
746          * index -1 means the kernel should try to find and
747          * allocate an empty descriptor:
748          */
749         if (idx == -1) {
750                 idx = get_free_idx();
751                 if (idx < 0)
752                         return idx;
753                 if (put_user(idx, &u_info->entry_number))
754                         return -EFAULT;
755         }
756
757         if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
758                 return -EINVAL;
759
760         desc = t->tls_array + idx - GDT_ENTRY_TLS_MIN;
761
762         /*
763          * We must not get preempted while modifying the TLS.
764          */
765         cpu = get_cpu();
766
767         if (LDT_empty(&info)) {
768                 desc->a = 0;
769                 desc->b = 0;
770         } else {
771                 desc->a = LDT_entry_a(&info);
772                 desc->b = LDT_entry_b(&info);
773         }
774         load_TLS(t, cpu);
775
776         put_cpu();
777
778         return 0;
779 }
780
781 /*
782  * Get the current Thread-Local Storage area:
783  */
784
785 #define GET_BASE(desc) ( \
786         (((desc)->a >> 16) & 0x0000ffff) | \
787         (((desc)->b << 16) & 0x00ff0000) | \
788         ( (desc)->b        & 0xff000000)   )
789
790 #define GET_LIMIT(desc) ( \
791         ((desc)->a & 0x0ffff) | \
792          ((desc)->b & 0xf0000) )
793         
794 #define GET_32BIT(desc)         (((desc)->b >> 22) & 1)
795 #define GET_CONTENTS(desc)      (((desc)->b >> 10) & 3)
796 #define GET_WRITABLE(desc)      (((desc)->b >>  9) & 1)
797 #define GET_LIMIT_PAGES(desc)   (((desc)->b >> 23) & 1)
798 #define GET_PRESENT(desc)       (((desc)->b >> 15) & 1)
799 #define GET_USEABLE(desc)       (((desc)->b >> 20) & 1)
800
801 asmlinkage int sys_get_thread_area(struct user_desc __user *u_info)
802 {
803         struct user_desc info;
804         struct desc_struct *desc;
805         int idx;
806
807         if (get_user(idx, &u_info->entry_number))
808                 return -EFAULT;
809         if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX)
810                 return -EINVAL;
811
812         desc = current->thread.tls_array + idx - GDT_ENTRY_TLS_MIN;
813
814         info.entry_number = idx;
815         info.base_addr = GET_BASE(desc);
816         info.limit = GET_LIMIT(desc);
817         info.seg_32bit = GET_32BIT(desc);
818         info.contents = GET_CONTENTS(desc);
819         info.read_exec_only = !GET_WRITABLE(desc);
820         info.limit_in_pages = GET_LIMIT_PAGES(desc);
821         info.seg_not_present = !GET_PRESENT(desc);
822         info.useable = GET_USEABLE(desc);
823
824         if (copy_to_user(u_info, &info, sizeof(info)))
825                 return -EFAULT;
826         return 0;
827 }
828
829 /*
830  * Get a random word:
831  */
832 static inline unsigned int get_random_int(void)
833 {
834         unsigned int val = 0;
835
836         if (!exec_shield_randomize)
837                 return 0;
838
839 #ifdef CONFIG_X86_HAS_TSC
840         rdtscl(val);
841 #endif
842         val += current->pid + jiffies + (int)&val;
843
844         /*
845          * Use IP's RNG. It suits our purpose perfectly: it re-keys itself
846          * every second, from the entropy pool (and thus creates a limited
847          * drain on it), and uses halfMD4Transform within the second. We
848          * also spice it with the TSC (if available), jiffies, PID and the
849          * stack address:
850          */
851         return secure_ip_id(val);
852 }
853
854 unsigned long arch_align_stack(unsigned long sp)
855 {
856         if (current->flags & PF_RELOCEXEC)
857                 sp -= ((get_random_int() % 65536) << 4);
858         return sp & ~0xf;
859 }
860
861 #if SHLIB_BASE >= 0x01000000
862 # error SHLIB_BASE must be under 16MB!
863 #endif
864
865 static unsigned long
866 arch_get_unmapped_nonexecutable_area(struct mm_struct *mm, unsigned long addr, unsigned long len)
867 {
868         struct vm_area_struct *vma, *prev_vma;
869         unsigned long stack_limit;
870         int first_time = 1;     
871
872         if (!mm->mmap_top) {
873                 printk("hm, %s:%d, !mmap_top.\n", current->comm, current->pid);
874                 mm->mmap_top = mmap_top();
875         }
876         stack_limit = mm->mmap_top;
877
878         /* requested length too big for entire address space */
879         if (len > TASK_SIZE) 
880                 return -ENOMEM;
881
882         /* dont allow allocations above current stack limit */
883         if (mm->non_executable_cache > stack_limit)
884                 mm->non_executable_cache = stack_limit;
885
886         /* requesting a specific address */
887         if (addr) {
888                 addr = PAGE_ALIGN(addr);
889                 vma = find_vma(mm, addr);
890                 if (TASK_SIZE - len >= addr && 
891                     (!vma || addr + len <= vma->vm_start))
892                         return addr;
893         }
894
895         /* make sure it can fit in the remaining address space */
896         if (mm->non_executable_cache < len)
897                 return -ENOMEM;
898
899         /* either no address requested or cant fit in requested address hole */
900 try_again:
901         addr = (mm->non_executable_cache - len)&PAGE_MASK;
902         do {
903                 if (!(vma = find_vma_prev(mm, addr, &prev_vma)))
904                         return -ENOMEM;
905
906                 /* new region fits between prev_vma->vm_end and vma->vm_start, use it */
907                 if (addr+len <= vma->vm_start && (!prev_vma || (addr >= prev_vma->vm_end))) {
908                         /* remember the address as a hint for next time */
909                         mm->non_executable_cache = addr;
910                         return addr;
911
912                 /* pull non_executable_cache down to the first hole */
913                 } else if (mm->non_executable_cache == vma->vm_end)
914                                 mm->non_executable_cache = vma->vm_start;       
915
916                 /* try just below the current vma->vm_start */
917                 addr = vma->vm_start-len;
918         } while (len <= vma->vm_start);
919         /* if hint left us with no space for the requested mapping try again */
920         if (first_time) {
921                 first_time = 0;
922                 mm->non_executable_cache = stack_limit;
923                 goto try_again;
924         }
925         return -ENOMEM;
926 }
927
928 static unsigned long randomize_range(unsigned long start, unsigned long end, unsigned long len)
929 {
930         unsigned long range = end - len - start;
931         if (end <= start + len)
932                 return 0;
933         return PAGE_ALIGN(get_random_int() % range + start);
934 }
935
936 static inline unsigned long
937 stock_arch_get_unmapped_area(struct file *filp, unsigned long addr,
938                 unsigned long len, unsigned long pgoff, unsigned long flags)
939 {
940         struct mm_struct *mm = current->mm;
941         struct vm_area_struct *vma;
942         unsigned long start_addr;
943
944         if (len > TASK_SIZE)
945                 return -ENOMEM;
946
947         if (addr) {
948                 addr = PAGE_ALIGN(addr);
949                 vma = find_vma(mm, addr);
950                 if (TASK_SIZE - len >= addr &&
951                     (!vma || addr + len <= vma->vm_start))
952                         return addr;
953         }
954         start_addr = addr = mm->free_area_cache;
955
956 full_search:
957         for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
958                 /* At this point:  (!vma || addr < vma->vm_end). */
959                 if (TASK_SIZE - len < addr) {
960                         /*
961                          * Start a new search - just in case we missed
962                          * some holes.
963                          */
964                         if (start_addr != TASK_UNMAPPED_BASE) {
965                                 start_addr = addr = TASK_UNMAPPED_BASE;
966                                 goto full_search;
967                         }
968                         return -ENOMEM;
969                 }
970                 if (!vma || addr + len <= vma->vm_start) {
971                         /*
972                          * Remember the place where we stopped the search:
973                          */
974                         mm->free_area_cache = addr + len;
975                         return addr;
976                 }
977                 addr = vma->vm_end;
978         }
979 }
980
981 unsigned long arch_get_unmapped_area(struct file *filp, unsigned long addr0,
982                 unsigned long len0, unsigned long pgoff, unsigned long flags,
983                 unsigned long prot)
984 {
985         unsigned long addr = addr0, len = len0;
986         struct mm_struct *mm = current->mm;
987         struct vm_area_struct *vma;
988         int ascii_shield = 0;
989         unsigned long tmp;
990
991         /*
992          * Fall back to the old layout:
993          */
994         if (!(current->flags & PF_RELOCEXEC))
995                return stock_arch_get_unmapped_area(filp, addr0, len0, pgoff, flags);
996         if (len > TASK_SIZE)
997                 return -ENOMEM;
998
999         if (!addr && (prot & PROT_EXEC) && !(flags & MAP_FIXED))
1000                 addr = randomize_range(SHLIB_BASE, 0x01000000, len);
1001
1002         if (addr) {
1003                 addr = PAGE_ALIGN(addr);
1004                 vma = find_vma(mm, addr);
1005                 if (TASK_SIZE - len >= addr &&
1006                     (!vma || addr + len <= vma->vm_start)) {
1007                         return addr;
1008                 }
1009         }
1010
1011         if (prot & PROT_EXEC) {
1012                 ascii_shield = 1;
1013                 addr = SHLIB_BASE;
1014         } else {
1015                 /* this can fail if the stack was unlimited */
1016                 if ((tmp = arch_get_unmapped_nonexecutable_area(mm, addr, len)) != -ENOMEM)
1017                         return tmp;
1018 search_upper:
1019                 addr = PAGE_ALIGN(arch_align_stack(TASK_UNMAPPED_BASE));
1020         }
1021
1022         for (vma = find_vma(mm, addr); ; vma = vma->vm_next) {
1023                 /* At this point:  (!vma || addr < vma->vm_end). */
1024                 if (TASK_SIZE - len < addr) {
1025                         return -ENOMEM;
1026                 }
1027                 if (!vma || addr + len <= vma->vm_start) {
1028                         /*
1029                          * Must not let a PROT_EXEC mapping get into the
1030                          * brk area:
1031                          */
1032                         if (ascii_shield && (addr + len > mm->brk)) {
1033                                 ascii_shield = 0;
1034                                 goto search_upper;
1035                         }
1036                         /*
1037                          * Up until the brk area we randomize addresses
1038                          * as much as possible:
1039                          */
1040                         if (ascii_shield && (addr >= 0x01000000)) {
1041                                 tmp = randomize_range(0x01000000, mm->brk, len);
1042                                 vma = find_vma(mm, tmp);
1043                                 if (TASK_SIZE - len >= tmp &&
1044                                     (!vma || tmp + len <= vma->vm_start))
1045                                         return tmp;
1046                         }
1047                         /*
1048                          * Ok, randomization didnt work out - return
1049                          * the result of the linear search:
1050                          */
1051                         return addr;
1052                 }
1053                 addr = vma->vm_end;
1054         }
1055 }
1056
1057 void arch_add_exec_range(struct mm_struct *mm, unsigned long limit)
1058 {
1059         if (limit > mm->context.exec_limit) {
1060                 mm->context.exec_limit = limit;
1061                 set_user_cs(&mm->context.user_cs, limit);
1062                 if (mm == current->mm)
1063                         load_user_cs_desc(smp_processor_id(), mm);
1064         }
1065 }
1066
1067 void arch_remove_exec_range(struct mm_struct *mm, unsigned long old_end)
1068 {
1069         struct vm_area_struct *vma;
1070         unsigned long limit = 0;
1071
1072         if (old_end == mm->context.exec_limit) {
1073                 for (vma = mm->mmap; vma; vma = vma->vm_next)
1074                         if ((vma->vm_flags & VM_EXEC) && (vma->vm_end > limit))
1075                                 limit = vma->vm_end;
1076
1077                 mm->context.exec_limit = limit;
1078                 set_user_cs(&mm->context.user_cs, limit);
1079                 if (mm == current->mm)
1080                         load_user_cs_desc(smp_processor_id(), mm);
1081         }
1082 }
1083
1084 void arch_flush_exec_range(struct mm_struct *mm)
1085 {
1086         mm->context.exec_limit = 0;
1087         set_user_cs(&mm->context.user_cs, 0);
1088 }
1089
1090 /*
1091  * Generate random brk address between 128MB and 196MB. (if the layout
1092  * allows it.)
1093  */
1094 void randomize_brk(unsigned long old_brk)
1095 {
1096         unsigned long new_brk, range_start, range_end;
1097
1098         range_start = 0x08000000;
1099         if (current->mm->brk >= range_start)
1100                 range_start = current->mm->brk;
1101         range_end = range_start + 0x02000000;
1102         new_brk = randomize_range(range_start, range_end, 0);
1103         if (new_brk)
1104                 current->mm->brk = new_brk;
1105 }
1106
1107 /*
1108  * Top of mmap area (just below the process stack).
1109  * leave an at least ~128 MB hole. Randomize it.
1110  */
1111 #define MIN_GAP (128*1024*1024)
1112 #define MAX_GAP (TASK_SIZE/6*5)
1113
1114 unsigned long mmap_top(void)
1115 {
1116         unsigned long gap = 0;
1117
1118         gap = current->rlim[RLIMIT_STACK].rlim_cur;
1119         if (gap < MIN_GAP)
1120                 gap = MIN_GAP;
1121         else if (gap > MAX_GAP)
1122                 gap = MAX_GAP;
1123
1124         gap = arch_align_stack(gap) & PAGE_MASK;
1125
1126         return TASK_SIZE - gap;
1127 }
1128