sandbox.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (c) 2011 The Chromium OS Authors.
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. */
  6. /*
  7. * This provide a test serial port. It provides an emulated serial port where
  8. * a test program and read out the serial output and inject serial input for
  9. * U-Boot.
  10. */
  11. #include <common.h>
  12. #include <lcd.h>
  13. #include <os.h>
  14. #include <serial.h>
  15. #include <linux/compiler.h>
  16. /*
  17. *
  18. * serial_buf: A buffer that holds keyboard characters for the
  19. * Sandbox U-boot.
  20. *
  21. * invariants:
  22. * serial_buf_write == serial_buf_read -> empty buffer
  23. * (serial_buf_write + 1) % 16 == serial_buf_read -> full buffer
  24. */
  25. static char serial_buf[16];
  26. static unsigned int serial_buf_write;
  27. static unsigned int serial_buf_read;
  28. static int sandbox_serial_init(void)
  29. {
  30. os_tty_raw(0);
  31. return 0;
  32. }
  33. static void sandbox_serial_setbrg(void)
  34. {
  35. }
  36. static void sandbox_serial_putc(const char ch)
  37. {
  38. os_write(1, &ch, 1);
  39. }
  40. static void sandbox_serial_puts(const char *str)
  41. {
  42. os_write(1, str, strlen(str));
  43. }
  44. static unsigned int increment_buffer_index(unsigned int index)
  45. {
  46. return (index + 1) % ARRAY_SIZE(serial_buf);
  47. }
  48. static int sandbox_serial_tstc(void)
  49. {
  50. const unsigned int next_index =
  51. increment_buffer_index(serial_buf_write);
  52. ssize_t count;
  53. os_usleep(100);
  54. #ifdef CONFIG_LCD
  55. lcd_sync();
  56. #endif
  57. if (next_index == serial_buf_read)
  58. return 1; /* buffer full */
  59. count = os_read_no_block(0, &serial_buf[serial_buf_write], 1);
  60. if (count == 1)
  61. serial_buf_write = next_index;
  62. return serial_buf_write != serial_buf_read;
  63. }
  64. static int sandbox_serial_getc(void)
  65. {
  66. int result;
  67. while (!sandbox_serial_tstc())
  68. ; /* buffer empty */
  69. result = serial_buf[serial_buf_read];
  70. serial_buf_read = increment_buffer_index(serial_buf_read);
  71. return result;
  72. }
  73. static struct serial_device sandbox_serial_drv = {
  74. .name = "sandbox_serial",
  75. .start = sandbox_serial_init,
  76. .stop = NULL,
  77. .setbrg = sandbox_serial_setbrg,
  78. .putc = sandbox_serial_putc,
  79. .puts = sandbox_serial_puts,
  80. .getc = sandbox_serial_getc,
  81. .tstc = sandbox_serial_tstc,
  82. };
  83. void sandbox_serial_initialize(void)
  84. {
  85. serial_register(&sandbox_serial_drv);
  86. }
  87. __weak struct serial_device *default_serial_console(void)
  88. {
  89. return &sandbox_serial_drv;
  90. }