i8254.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * (C) Copyright 2002
  4. * Daniel Engström, Omicron Ceti AB, <daniel@omicron.se>
  5. */
  6. #include <common.h>
  7. #include <asm/io.h>
  8. #include <asm/i8254.h>
  9. #define TIMER1_VALUE 18 /* 15.6us */
  10. #define BEEP_FREQUENCY_HZ 440
  11. #define SYSCTL_PORTB 0x61
  12. #define PORTB_BEEP_ENABLE 0x3
  13. static void i8254_set_beep_freq(uint frequency_hz)
  14. {
  15. uint countdown;
  16. countdown = PIT_TICK_RATE / frequency_hz;
  17. outb(countdown & 0xff, PIT_BASE + PIT_T2);
  18. outb((countdown >> 8) & 0xff, PIT_BASE + PIT_T2);
  19. }
  20. int i8254_init(void)
  21. {
  22. /*
  23. * Initialize counter 1, used to refresh request signal.
  24. * This is required for legacy purpose as some codes like
  25. * vgabios utilizes counter 1 to provide delay functionality.
  26. */
  27. outb(PIT_CMD_CTR1 | PIT_CMD_LOW | PIT_CMD_MODE2,
  28. PIT_BASE + PIT_COMMAND);
  29. outb(TIMER1_VALUE, PIT_BASE + PIT_T1);
  30. /*
  31. * Initialize counter 2, used to drive the speaker.
  32. * To start a beep, set both bit0 and bit1 of port 0x61.
  33. * To stop it, clear both bit0 and bit1 of port 0x61.
  34. */
  35. outb(PIT_CMD_CTR2 | PIT_CMD_BOTH | PIT_CMD_MODE3,
  36. PIT_BASE + PIT_COMMAND);
  37. i8254_set_beep_freq(BEEP_FREQUENCY_HZ);
  38. return 0;
  39. }
  40. int i8254_enable_beep(uint frequency_hz)
  41. {
  42. if (!frequency_hz)
  43. return -EINVAL;
  44. /* make sure i8254 is setup correctly before generating beeps */
  45. outb(PIT_CMD_CTR2 | PIT_CMD_BOTH | PIT_CMD_MODE3,
  46. PIT_BASE + PIT_COMMAND);
  47. i8254_set_beep_freq(frequency_hz);
  48. setio_8(SYSCTL_PORTB, PORTB_BEEP_ENABLE);
  49. return 0;
  50. }
  51. void i8254_disable_beep(void)
  52. {
  53. clrio_8(SYSCTL_PORTB, PORTB_BEEP_ENABLE);
  54. }