descriptor.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2009 Corey Tabaka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files
  6. * (the "Software"), to deal in the Software without restriction,
  7. * including without limitation the rights to use, copy, modify, merge,
  8. * publish, distribute, sublicense, and/or sell copies of the Software,
  9. * and to permit persons to whom the Software is furnished to do so,
  10. * subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be
  13. * included in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include <compiler.h>
  24. #include <arch/x86/descriptor.h>
  25. /* not the best way to do this, but easy for now */
  26. typedef struct {
  27. uint16_t limit_15_0;
  28. uint16_t base_15_0;
  29. uint8_t base_23_16;
  30. uint8_t type : 4;
  31. uint8_t s : 1;
  32. uint8_t dpl : 2;
  33. uint8_t p : 1;
  34. uint8_t limit_19_16 : 4;
  35. uint8_t avl : 1;
  36. uint8_t reserved_0 : 1;
  37. uint8_t d_b : 1;
  38. uint8_t g : 1;
  39. uint8_t base_31_24;
  40. } __PACKED seg_desc_t;
  41. extern seg_desc_t _gdt[];
  42. void set_global_desc(seg_sel_t sel, void *base, uint32_t limit,
  43. uint8_t present, uint8_t ring, uint8_t sys, uint8_t type, uint8_t gran, uint8_t bits)
  44. {
  45. // convert selector into index
  46. uint16_t index = sel >> 3;
  47. _gdt[index].limit_15_0 = limit & 0x0000ffff;
  48. _gdt[index].limit_19_16 = (limit & 0x000f0000) >> 16;
  49. _gdt[index].base_15_0 = ((uint32_t) base) & 0x0000ffff;
  50. _gdt[index].base_23_16 = (((uint32_t) base) & 0x00ff0000) >> 16;
  51. _gdt[index].base_31_24 = ((uint32_t) base) >> 24;
  52. _gdt[index].type = type & 0x0f; // segment type
  53. _gdt[index].p = present != 0; // present
  54. _gdt[index].dpl = ring & 0x03; // descriptor privilege level
  55. _gdt[index].g = gran != 0; // granularity
  56. _gdt[index].s = sys != 0; // system / non-system
  57. _gdt[index].d_b = bits != 0; // 16 / 32 bit
  58. }