PTYMultiplexer.cpp 1.5 KB

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