PTYMultiplexer.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 = FileDescription::try_create(*master);
  42. if (!description.is_error()) {
  43. description.value()->set_rw_mode(options);
  44. description.value()->set_file_flags(options);
  45. }
  46. return description;
  47. });
  48. }
  49. void PTYMultiplexer::notify_master_destroyed(Badge<MasterPTY>, unsigned index)
  50. {
  51. m_freelist.with_exclusive([&](auto& freelist) {
  52. freelist.append(index);
  53. dbgln_if(PTMX_DEBUG, "PTYMultiplexer: {} added to freelist", index);
  54. });
  55. }
  56. }