serial.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Serial (UART) driver: COM1 at 0x3F8, 115200 8N1, polled. */
  2. #include "serial.h"
  3. #include "timer.h"
  4. #define COM1_BASE 0x3F8
  5. #define RBR 0 /* Receive Buffer (DLAB=0) */
  6. #define THR 0 /* Transmit Holding (DLAB=0) */
  7. #define DLL 0 /* Divisor Latch Low (DLAB=1) */
  8. #define IER 1 /* Interrupt Enable */
  9. #define DLH 1 /* Divisor Latch High (DLAB=1) */
  10. #define LCR 3 /* Line Control */
  11. #define LSR 5 /* Line Status */
  12. #define LCR_8N1 0x03
  13. #define LCR_DLAB 0x80
  14. #define LSR_DR 0x01 /* Data Ready */
  15. #define LSR_THRE 0x20 /* Transmit Holding Register Empty */
  16. static inline unsigned char inb(unsigned short port)
  17. {
  18. unsigned char v;
  19. __asm__ volatile ("inb %1, %0" : "=a"(v) : "Nd"(port));
  20. return v;
  21. }
  22. static inline void outb(unsigned short port, unsigned char v)
  23. {
  24. __asm__ volatile ("outb %0, %1" : : "a"(v), "Nd"(port));
  25. }
  26. void serial_init(void)
  27. {
  28. /* Divisor for 115200: 115200 / 115200 = 1. Use 1. */
  29. outb(COM1_BASE + LCR, LCR_DLAB);
  30. outb(COM1_BASE + DLL, 1);
  31. outb(COM1_BASE + DLH, 0);
  32. outb(COM1_BASE + LCR, LCR_8N1);
  33. outb(COM1_BASE + IER, 0); /* No interrupts */
  34. }
  35. void serial_drain(void)
  36. {
  37. while (serial_getchar(0) >= 0)
  38. ;
  39. }
  40. void serial_putchar(char c)
  41. {
  42. unsigned int t0 = get_ticks_ms();
  43. while ((get_ticks_ms() - t0) < 100) {
  44. if (inb(COM1_BASE + LSR) & LSR_THRE) {
  45. outb(COM1_BASE + THR, (unsigned char)c);
  46. return;
  47. }
  48. }
  49. }
  50. void serial_putstr(const char *s)
  51. {
  52. while (*s)
  53. serial_putchar(*s++);
  54. }
  55. int serial_getchar(unsigned int timeout_ms)
  56. {
  57. unsigned int t0 = get_ticks_ms();
  58. while ((get_ticks_ms() - t0) < timeout_ms) {
  59. if (inb(COM1_BASE + LSR) & LSR_DR)
  60. return (unsigned char)inb(COM1_BASE + RBR);
  61. }
  62. return -1;
  63. }
  64. int serial_has_byte(void)
  65. {
  66. return (inb(COM1_BASE + LSR) & LSR_DR) ? 1 : 0;
  67. }