PTYMultiplexer.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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/OpenFileDescription.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<OpenFileDescription>> PTYMultiplexer::open(int options)
  32. {
  33. return m_freelist.with_exclusive([&](auto& freelist) -> KResultOr<NonnullRefPtr<OpenFileDescription>> {
  34. if (freelist.is_empty())
  35. return EBUSY;
  36. auto master_index = freelist.take_last();
  37. auto master = TRY(MasterPTY::try_create(master_index));
  38. dbgln_if(PTMX_DEBUG, "PTYMultiplexer::open: Vending master {}", master->index());
  39. auto description = TRY(OpenFileDescription::try_create(*master));
  40. description->set_rw_mode(options);
  41. description->set_file_flags(options);
  42. return description;
  43. });
  44. }
  45. void PTYMultiplexer::notify_master_destroyed(Badge<MasterPTY>, unsigned index)
  46. {
  47. m_freelist.with_exclusive([&](auto& freelist) {
  48. freelist.append(index);
  49. dbgln_if(PTMX_DEBUG, "PTYMultiplexer: {} added to freelist", index);
  50. });
  51. }
  52. }