serial.c 1.9 KB

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