tty_port.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. use core::fmt::Debug;
  2. use alloc::sync::{Arc, Weak};
  3. use kdepends::thingbuf::mpsc;
  4. use system_error::SystemError;
  5. use crate::{
  6. libs::spinlock::{SpinLock, SpinLockGuard},
  7. net::event_poll::EventPoll,
  8. };
  9. use super::tty_core::TtyCore;
  10. const TTY_PORT_BUFSIZE: usize = 4096;
  11. #[allow(dead_code)]
  12. #[derive(Debug)]
  13. pub struct TtyPortData {
  14. flags: i32,
  15. iflags: TtyPortState,
  16. sender: mpsc::Sender<u8>,
  17. receiver: mpsc::Receiver<u8>,
  18. tty: Weak<TtyCore>,
  19. /// 内部tty,即与port直接相连的
  20. internal_tty: Weak<TtyCore>,
  21. }
  22. impl Default for TtyPortData {
  23. fn default() -> Self {
  24. Self::new()
  25. }
  26. }
  27. impl TtyPortData {
  28. pub fn new() -> Self {
  29. let (sender, receiver) = mpsc::channel::<u8>(TTY_PORT_BUFSIZE);
  30. Self {
  31. flags: 0,
  32. iflags: TtyPortState::Initialized,
  33. sender,
  34. receiver,
  35. tty: Weak::new(),
  36. internal_tty: Weak::new(),
  37. }
  38. }
  39. pub fn internal_tty(&self) -> Option<Arc<TtyCore>> {
  40. self.internal_tty.upgrade()
  41. }
  42. pub fn tty(&self) -> Option<Arc<TtyCore>> {
  43. self.tty.upgrade()
  44. }
  45. }
  46. #[allow(dead_code)]
  47. #[derive(Debug, PartialEq, Clone, Copy)]
  48. pub enum TtyPortState {
  49. Initialized,
  50. Suspended,
  51. Active,
  52. CtsFlow,
  53. CheckCD,
  54. KOPENED,
  55. }
  56. pub trait TtyPort: Sync + Send + Debug {
  57. fn port_data(&self) -> SpinLockGuard<TtyPortData>;
  58. /// 获取Port的状态
  59. fn state(&self) -> TtyPortState {
  60. self.port_data().iflags
  61. }
  62. /// 为port设置tty
  63. fn setup_internal_tty(&self, tty: Weak<TtyCore>) {
  64. self.port_data().internal_tty = tty;
  65. }
  66. /// 作为客户端的tty ports接收数据
  67. fn receive_buf(&self, buf: &[u8], _flags: &[u8], count: usize) -> Result<usize, SystemError> {
  68. let tty = self.port_data().internal_tty().unwrap();
  69. let ld = tty.ldisc();
  70. let ret = ld.receive_buf2(tty.clone(), buf, None, count);
  71. if ret.is_err() && ret.clone().unwrap_err() == SystemError::ENOSYS {
  72. return ld.receive_buf(tty, buf, None, count);
  73. }
  74. EventPoll::wakeup_epoll(tty.core().eptiems(), None)?;
  75. ret
  76. }
  77. }
  78. #[derive(Debug)]
  79. pub struct DefaultTtyPort {
  80. port_data: SpinLock<TtyPortData>,
  81. }
  82. impl DefaultTtyPort {
  83. pub fn new() -> Self {
  84. Self {
  85. port_data: SpinLock::new(TtyPortData::new()),
  86. }
  87. }
  88. }
  89. impl TtyPort for DefaultTtyPort {
  90. fn port_data(&self) -> SpinLockGuard<TtyPortData> {
  91. self.port_data.lock_irqsave()
  92. }
  93. }