tss.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* TSS + flat GDT (kernel code/data, user code/data, TSS). */
  2. #include "tss.h"
  3. /* Top of the in-image bootstrap stack (see kernel.ld): used until the first
  4. * context switch replaces TSS.esp0 with the process's own kernel stack. */
  5. extern char __boot_stack_top[];
  6. struct tss tss;
  7. struct gdt_entry {
  8. unsigned short limit_low;
  9. unsigned short base_low;
  10. unsigned char base_mid;
  11. unsigned char access;
  12. unsigned char limit_high_flags;
  13. unsigned char base_high;
  14. } __attribute__((packed));
  15. struct gdt_ptr {
  16. unsigned short limit;
  17. unsigned int base;
  18. } __attribute__((packed));
  19. static struct gdt_entry gdt[6];
  20. static struct gdt_ptr gdtp;
  21. static void set_entry(int i, unsigned int base, unsigned int limit,
  22. unsigned char access, unsigned char flags)
  23. {
  24. gdt[i].limit_low = (unsigned short)(limit & 0xFFFF);
  25. gdt[i].base_low = (unsigned short)(base & 0xFFFF);
  26. gdt[i].base_mid = (unsigned char)((base >> 16) & 0xFF);
  27. gdt[i].access = access;
  28. gdt[i].limit_high_flags =
  29. (unsigned char)(((limit >> 16) & 0x0F) | (flags & 0xF0));
  30. gdt[i].base_high = (unsigned char)((base >> 24) & 0xFF);
  31. }
  32. void gdt_tss_init(void)
  33. {
  34. unsigned int i;
  35. for (i = 0; i < sizeof(gdt); i++)
  36. ((unsigned char *)gdt)[i] = 0;
  37. for (i = 0; i < sizeof(tss); i++)
  38. ((unsigned char *)&tss)[i] = 0;
  39. /* 0x00 null */
  40. /* 0x08 kernel code, 0x10 kernel data */
  41. set_entry(1, 0, 0xFFFFF, 0x9A, 0xCF);
  42. set_entry(2, 0, 0xFFFFF, 0x92, 0xCF);
  43. /* 0x18 user code, 0x20 user data (DPL=3) */
  44. set_entry(3, 0, 0xFFFFF, 0xFA, 0xCF);
  45. set_entry(4, 0, 0xFFFFF, 0xF2, 0xCF);
  46. /* 0x28 TSS */
  47. set_entry(5, (unsigned int)&tss, sizeof(tss) - 1, 0x89, 0x00);
  48. gdtp.limit = (unsigned short)(sizeof(gdt) - 1);
  49. gdtp.base = (unsigned int)gdt;
  50. __asm__ volatile ("lgdt %0" : : "m"(gdtp));
  51. tss.ss0 = 0x10; /* kernel data segment */
  52. tss.esp0 = (unsigned int)__boot_stack_top;
  53. tss.iomap_base = 0xFFFF; /* no I/O permission bitmap (deny ring-3 I/O) */
  54. __asm__ volatile ("ltr %0" : : "r"((unsigned short)0x28));
  55. }