serial.c 2.1 KB

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