PTYMultiplexer.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Singleton.h>
  7. #include <Kernel/Debug.h>
  8. #include <Kernel/FileSystem/FileDescription.h>
  9. #include <Kernel/Sections.h>
  10. #include <Kernel/TTY/MasterPTY.h>
  11. #include <Kernel/TTY/PTYMultiplexer.h>
  12. #include <LibC/errno_numbers.h>
  13. namespace Kernel {
  14. static Singleton<PTYMultiplexer> s_the;
  15. PTYMultiplexer& PTYMultiplexer::the()
  16. {
  17. return *s_the;
  18. }
  19. UNMAP_AFTER_INIT PTYMultiplexer::PTYMultiplexer()
  20. : CharacterDevice(5, 2)
  21. {
  22. m_freelist.with_exclusive([&](auto& freelist) {
  23. freelist.ensure_capacity(max_pty_pairs);
  24. for (int i = max_pty_pairs; i > 0; --i)
  25. freelist.unchecked_append(i - 1);
  26. });
  27. }
  28. UNMAP_AFTER_INIT PTYMultiplexer::~PTYMultiplexer()
  29. {
  30. }
  31. KResultOr<NonnullRefPtr<FileDescription>> PTYMultiplexer::open(int options)
  32. {
  33. return m_freelist.with_exclusive([&](auto& freelist) -> KResultOr<NonnullRefPtr<FileDescription>> {
  34. if (freelist.is_empty())
  35. return EBUSY;
  36. auto master_index = freelist.take_last();
  37. auto master = MasterPTY::try_create(master_index);
  38. if (!master)
  39. return ENOMEM;
  40. dbgln_if(PTMX_DEBUG, "PTYMultiplexer::open: Vending master {}", master->index());
  41. auto description = TRY(FileDescription::try_create(*master));
  42. description->set_rw_mode(options);
  43. description->set_file_flags(options);
  44. return description;
  45. });
  46. }
  47. void PTYMultiplexer::notify_master_destroyed(Badge<MasterPTY>, unsigned index)
  48. {
  49. m_freelist.with_exclusive([&](auto& freelist) {
  50. freelist.append(index);
  51. dbgln_if(PTMX_DEBUG, "PTYMultiplexer: {} added to freelist", index);
  52. });
  53. }
  54. }