serial.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "serial.h"
  2. #include "serial_ring_buf.h"
  3. #include "pci.h"
  4. #include "timer.h"
  5. void serial_init(unsigned int port)
  6. {
  7. port_outb(port + 1, 0x00);
  8. port_outb(port + 3, 0x80);
  9. port_outb(port + 0, 0x01); /* divisor low = 1 -> 115200 baud */
  10. port_outb(port + 1, 0x00); /* divisor high = 0 */
  11. port_outb(port + 3, 0x03);
  12. port_outb(port + 2, 0xC7);
  13. port_outb(port + 4, 0x03);
  14. }
  15. void serial_putc(unsigned int port, char c)
  16. {
  17. while (!(port_inb(port + 5) & 0x20))
  18. ;
  19. port_outb(port, (unsigned char)c);
  20. }
  21. void serial_puts(unsigned int port, const char *s)
  22. {
  23. while (*s) {
  24. if (*s == '\n')
  25. serial_putc(port, '\r');
  26. serial_putc(port, *s++);
  27. }
  28. }
  29. void serial_puthex(unsigned int port, unsigned int n)
  30. {
  31. static const char hex[] = "0123456789ABCDEF";
  32. int i;
  33. serial_puts(port, "0x");
  34. for (i = 28; i >= 0; i -= 4)
  35. serial_putc(port, hex[(n >> i) & 0xF]);
  36. }
  37. void serial_putdec(unsigned int port, unsigned int n)
  38. {
  39. char buf[12];
  40. char *p = buf + sizeof(buf) - 1;
  41. *p = '\0';
  42. if (n == 0) {
  43. serial_putc(port, '0');
  44. return;
  45. }
  46. while (n) {
  47. *--p = (char)('0' + (n % 10));
  48. n /= 10;
  49. }
  50. serial_puts(port, p);
  51. }
  52. int serial_has_data(unsigned int port)
  53. {
  54. (void)port;
  55. return serial_ring_count() > 0;
  56. }
  57. void serial_poll(void)
  58. {
  59. unsigned char c;
  60. while ((port_inb(SERIAL_COM1 + 5) & 0x01) != 0) {
  61. c = (unsigned char)port_inb(SERIAL_COM1);
  62. serial_ring_push(c);
  63. }
  64. }
  65. int serial_ring_getc(void)
  66. {
  67. unsigned char c;
  68. if (serial_ring_pop(&c))
  69. return (int)c;
  70. return 0;
  71. }
  72. int serial_ring_wait(unsigned int timeout_ms, unsigned char *out)
  73. {
  74. unsigned int start = get_ticks_ms();
  75. while (get_ticks_ms() - start < timeout_ms) {
  76. if (serial_ring_pop(out))
  77. return 1;
  78. __asm__ volatile ("hlt");
  79. }
  80. return 0;
  81. }