Plan9FileSystem.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. /*
  2. * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <Kernel/FileSystem/Plan9FileSystem.h>
  27. #include <Kernel/Process.h>
  28. namespace Kernel {
  29. NonnullRefPtr<Plan9FS> Plan9FS::create(FileDescription& file_description)
  30. {
  31. return adopt(*new Plan9FS(file_description));
  32. }
  33. Plan9FS::Plan9FS(FileDescription& file_description)
  34. : FileBackedFS(file_description)
  35. , m_completion_blocker(*this)
  36. {
  37. }
  38. Plan9FS::~Plan9FS()
  39. {
  40. // Make sure to destroy the root inode before the FS gets destroyed.
  41. if (m_root_inode) {
  42. ASSERT(m_root_inode->ref_count() == 1);
  43. m_root_inode = nullptr;
  44. }
  45. }
  46. class Plan9FS::Message {
  47. public:
  48. enum class Type : u8 {
  49. // 9P2000.L
  50. Tlerror = 6,
  51. Rlerror = 7,
  52. Tstatfs = 8,
  53. Rstatfs = 9,
  54. Tlopen = 12,
  55. Rlopen = 13,
  56. Tlcreate = 14,
  57. Rlcreate = 15,
  58. Tsymlink = 16,
  59. Rsymlink = 17,
  60. Tmknod = 18,
  61. Rmknod = 19,
  62. Trename = 20,
  63. Rrename = 21,
  64. Treadlink = 22,
  65. Rreadlink = 23,
  66. Tgetattr = 24,
  67. Rgetattr = 25,
  68. Tsetattr = 26,
  69. Rsetattr = 27,
  70. Txattrwalk = 30,
  71. Rxattrwalk = 31,
  72. Txattrcreate = 32,
  73. Rxattrcreate = 33,
  74. Treaddir = 40,
  75. Rreaddir = 41,
  76. Tfsync = 50,
  77. Rfsync = 51,
  78. Tlock = 52,
  79. Rlock = 53,
  80. Tgetlock = 54,
  81. Rgetlock = 55,
  82. Tlink = 70,
  83. Rlink = 71,
  84. Tmkdir = 72,
  85. Rmkdir = 73,
  86. Trenameat = 74,
  87. Rrenameat = 75,
  88. Tunlinkat = 76,
  89. Runlinkat = 77,
  90. // 9P2000
  91. Tversion = 100,
  92. Rversion = 101,
  93. Tauth = 102,
  94. Rauth = 103,
  95. Tattach = 104,
  96. Rattach = 105,
  97. Terror = 106,
  98. Rerror = 107,
  99. Tflush = 108,
  100. Rflush = 109,
  101. Twalk = 110,
  102. Rwalk = 111,
  103. Topen = 112,
  104. Ropen = 113,
  105. Tcreate = 114,
  106. Rcreate = 115,
  107. Tread = 116,
  108. Rread = 117,
  109. Twrite = 118,
  110. Rwrite = 119,
  111. Tclunk = 120,
  112. Rclunk = 121,
  113. Tremove = 122,
  114. Rremove = 123,
  115. Tstat = 124,
  116. Rstat = 125,
  117. Twstat = 126,
  118. Rwstat = 127
  119. };
  120. class Decoder {
  121. public:
  122. explicit Decoder(const StringView& data)
  123. : m_data(data)
  124. {
  125. }
  126. Decoder& operator>>(u8&);
  127. Decoder& operator>>(u16&);
  128. Decoder& operator>>(u32&);
  129. Decoder& operator>>(u64&);
  130. Decoder& operator>>(StringView&);
  131. Decoder& operator>>(qid&);
  132. StringView read_data();
  133. bool has_more_data() const { return !m_data.is_empty(); }
  134. private:
  135. StringView m_data;
  136. template<typename N>
  137. Decoder& read_number(N& number)
  138. {
  139. ASSERT(sizeof(number) <= m_data.length());
  140. memcpy(&number, m_data.characters_without_null_termination(), sizeof(number));
  141. m_data = m_data.substring_view(sizeof(number), m_data.length() - sizeof(number));
  142. return *this;
  143. }
  144. };
  145. Message& operator<<(u8);
  146. Message& operator<<(u16);
  147. Message& operator<<(u32);
  148. Message& operator<<(u64);
  149. Message& operator<<(const StringView&);
  150. void append_data(const StringView&);
  151. template<typename T>
  152. Message& operator>>(T& t)
  153. {
  154. ASSERT(m_have_been_built);
  155. m_built.decoder >> t;
  156. return *this;
  157. }
  158. StringView read_data()
  159. {
  160. ASSERT(m_have_been_built);
  161. return m_built.decoder.read_data();
  162. }
  163. Type type() const { return m_type; }
  164. u16 tag() const { return m_tag; }
  165. Message(Plan9FS&, Type);
  166. Message(NonnullOwnPtr<KBuffer>&&);
  167. ~Message();
  168. Message& operator=(Message&&);
  169. const KBuffer& build();
  170. static constexpr ssize_t max_header_size = 24;
  171. private:
  172. template<typename N>
  173. Message& append_number(N number)
  174. {
  175. ASSERT(!m_have_been_built);
  176. m_builder.append(reinterpret_cast<const char*>(&number), sizeof(number));
  177. return *this;
  178. }
  179. union {
  180. KBufferBuilder m_builder;
  181. struct {
  182. NonnullOwnPtr<KBuffer> buffer;
  183. Decoder decoder;
  184. } m_built;
  185. };
  186. u16 m_tag { 0 };
  187. Type m_type { 0 };
  188. bool m_have_been_built { false };
  189. };
  190. bool Plan9FS::initialize()
  191. {
  192. ensure_thread();
  193. Message version_message { *this, Message::Type::Tversion };
  194. version_message << (u32)m_max_message_size << "9P2000.L";
  195. auto result = post_message_and_wait_for_a_reply(version_message);
  196. if (result.is_error())
  197. return false;
  198. u32 msize;
  199. StringView remote_protocol_version;
  200. version_message >> msize >> remote_protocol_version;
  201. dbgln("Remote supports msize={} and protocol version {}", msize, remote_protocol_version);
  202. m_remote_protocol_version = parse_protocol_version(remote_protocol_version);
  203. m_max_message_size = min(m_max_message_size, (size_t)msize);
  204. // TODO: auth
  205. u32 root_fid = allocate_fid();
  206. Message attach_message { *this, Message::Type::Tattach };
  207. // FIXME: This needs a user name and an "export" name; but how do we get them?
  208. // Perhaps initialize() should accept a string of FS-specific options...
  209. attach_message << root_fid << (u32)-1 << "sergey"
  210. << "/";
  211. if (m_remote_protocol_version >= ProtocolVersion::v9P2000u)
  212. attach_message << (u32)-1;
  213. result = post_message_and_wait_for_a_reply(attach_message);
  214. if (result.is_error()) {
  215. dbgln("Attaching failed");
  216. return false;
  217. }
  218. m_root_inode = Plan9FSInode::create(*this, root_fid);
  219. return true;
  220. }
  221. Plan9FS::ProtocolVersion Plan9FS::parse_protocol_version(const StringView& s) const
  222. {
  223. if (s == "9P2000.L")
  224. return ProtocolVersion::v9P2000L;
  225. if (s == "9P2000.u")
  226. return ProtocolVersion::v9P2000u;
  227. return ProtocolVersion::v9P2000;
  228. }
  229. NonnullRefPtr<Inode> Plan9FS::root_inode() const
  230. {
  231. return *m_root_inode;
  232. }
  233. Plan9FS::Message& Plan9FS::Message::operator<<(u8 number)
  234. {
  235. return append_number(number);
  236. }
  237. Plan9FS::Message& Plan9FS::Message::operator<<(u16 number)
  238. {
  239. return append_number(number);
  240. }
  241. Plan9FS::Message& Plan9FS::Message::operator<<(u32 number)
  242. {
  243. return append_number(number);
  244. }
  245. Plan9FS::Message& Plan9FS::Message::operator<<(u64 number)
  246. {
  247. return append_number(number);
  248. }
  249. Plan9FS::Message& Plan9FS::Message::operator<<(const StringView& string)
  250. {
  251. *this << static_cast<u16>(string.length());
  252. m_builder.append(string);
  253. return *this;
  254. }
  255. void Plan9FS::Message::append_data(const StringView& data)
  256. {
  257. *this << static_cast<u32>(data.length());
  258. m_builder.append(data);
  259. }
  260. Plan9FS::Message::Decoder& Plan9FS::Message::Decoder::operator>>(u8& number)
  261. {
  262. return read_number(number);
  263. }
  264. Plan9FS::Message::Decoder& Plan9FS::Message::Decoder::operator>>(u16& number)
  265. {
  266. return read_number(number);
  267. }
  268. Plan9FS::Message::Decoder& Plan9FS::Message::Decoder::operator>>(u32& number)
  269. {
  270. return read_number(number);
  271. }
  272. Plan9FS::Message::Decoder& Plan9FS::Message::Decoder::operator>>(u64& number)
  273. {
  274. return read_number(number);
  275. }
  276. Plan9FS::Message::Decoder& Plan9FS::Message::Decoder::operator>>(qid& qid)
  277. {
  278. return *this >> qid.type >> qid.version >> qid.path;
  279. }
  280. Plan9FS::Message::Decoder& Plan9FS::Message::Decoder::operator>>(StringView& string)
  281. {
  282. u16 length;
  283. *this >> length;
  284. ASSERT(length <= m_data.length());
  285. string = m_data.substring_view(0, length);
  286. m_data = m_data.substring_view_starting_after_substring(string);
  287. return *this;
  288. }
  289. StringView Plan9FS::Message::Decoder::read_data()
  290. {
  291. u32 length;
  292. *this >> length;
  293. ASSERT(length <= m_data.length());
  294. auto data = m_data.substring_view(0, length);
  295. m_data = m_data.substring_view_starting_after_substring(data);
  296. return data;
  297. }
  298. Plan9FS::Message::Message(Plan9FS& fs, Type type)
  299. : m_builder()
  300. , m_tag(fs.allocate_tag())
  301. , m_type(type)
  302. , m_have_been_built(false)
  303. {
  304. u32 size_placeholder = 0;
  305. *this << size_placeholder << (u8)type << m_tag;
  306. }
  307. Plan9FS::Message::Message(NonnullOwnPtr<KBuffer>&& buffer)
  308. : m_built { move(buffer), Decoder({ buffer->data(), buffer->size() }) }
  309. , m_have_been_built(true)
  310. {
  311. u32 size;
  312. u8 raw_type;
  313. *this >> size >> raw_type >> m_tag;
  314. m_type = (Type)raw_type;
  315. }
  316. Plan9FS::Message::~Message()
  317. {
  318. if (m_have_been_built) {
  319. m_built.buffer.~NonnullOwnPtr<KBuffer>();
  320. m_built.decoder.~Decoder();
  321. } else {
  322. m_builder.~KBufferBuilder();
  323. }
  324. }
  325. Plan9FS::Message& Plan9FS::Message::operator=(Message&& message)
  326. {
  327. m_tag = message.m_tag;
  328. m_type = message.m_type;
  329. if (m_have_been_built) {
  330. m_built.buffer.~NonnullOwnPtr<KBuffer>();
  331. m_built.decoder.~Decoder();
  332. } else {
  333. m_builder.~KBufferBuilder();
  334. }
  335. m_have_been_built = message.m_have_been_built;
  336. if (m_have_been_built) {
  337. new (&m_built.buffer) NonnullOwnPtr<KBuffer>(move(message.m_built.buffer));
  338. new (&m_built.decoder) Decoder(move(message.m_built.decoder));
  339. } else {
  340. new (&m_builder) KBufferBuilder(move(message.m_builder));
  341. }
  342. return *this;
  343. }
  344. const KBuffer& Plan9FS::Message::build()
  345. {
  346. ASSERT(!m_have_been_built);
  347. auto tmp_buffer = m_builder.build();
  348. // FIXME: We should not assume success here.
  349. ASSERT(tmp_buffer);
  350. m_have_been_built = true;
  351. m_builder.~KBufferBuilder();
  352. new (&m_built.buffer) NonnullOwnPtr<KBuffer>(tmp_buffer.release_nonnull());
  353. new (&m_built.decoder) Decoder({ m_built.buffer->data(), m_built.buffer->size() });
  354. u32* size = reinterpret_cast<u32*>(m_built.buffer->data());
  355. *size = m_built.buffer->size();
  356. return *m_built.buffer;
  357. }
  358. Plan9FS::ReceiveCompletion::ReceiveCompletion(u16 tag)
  359. : tag(tag)
  360. {
  361. }
  362. Plan9FS::ReceiveCompletion::~ReceiveCompletion()
  363. {
  364. }
  365. bool Plan9FS::Blocker::unblock(u16 tag)
  366. {
  367. {
  368. ScopedSpinLock lock(m_lock);
  369. if (m_did_unblock)
  370. return false;
  371. m_did_unblock = true;
  372. if (m_completion->tag != tag)
  373. return false;
  374. if (!m_completion->result.is_error())
  375. m_message = move(*m_completion->message);
  376. }
  377. return unblock();
  378. }
  379. void Plan9FS::Blocker::not_blocking(bool)
  380. {
  381. {
  382. ScopedSpinLock lock(m_lock);
  383. if (m_did_unblock)
  384. return;
  385. }
  386. m_fs.m_completion_blocker.try_unblock(*this);
  387. }
  388. bool Plan9FS::Blocker::is_completed() const
  389. {
  390. ScopedSpinLock lock(m_completion->lock);
  391. return m_completion->completed;
  392. }
  393. bool Plan9FS::Plan9FSBlockCondition::should_add_blocker(Thread::Blocker& b, void*)
  394. {
  395. // NOTE: m_lock is held already!
  396. auto& blocker = static_cast<Blocker&>(b);
  397. return !blocker.is_completed();
  398. }
  399. void Plan9FS::Plan9FSBlockCondition::unblock_completed(u16 tag)
  400. {
  401. unblock([&](Thread::Blocker& b, void*, bool&) {
  402. ASSERT(b.blocker_type() == Thread::Blocker::Type::Plan9FS);
  403. auto& blocker = static_cast<Blocker&>(b);
  404. return blocker.unblock(tag);
  405. });
  406. }
  407. void Plan9FS::Plan9FSBlockCondition::unblock_all()
  408. {
  409. unblock([&](Thread::Blocker& b, void*, bool&) {
  410. ASSERT(b.blocker_type() == Thread::Blocker::Type::Plan9FS);
  411. auto& blocker = static_cast<Blocker&>(b);
  412. return blocker.unblock();
  413. });
  414. }
  415. void Plan9FS::Plan9FSBlockCondition::try_unblock(Plan9FS::Blocker& blocker)
  416. {
  417. if (m_fs.is_complete(*blocker.completion())) {
  418. ScopedSpinLock lock(m_lock);
  419. blocker.unblock(blocker.completion()->tag);
  420. }
  421. }
  422. bool Plan9FS::is_complete(const ReceiveCompletion& completion)
  423. {
  424. LOCKER(m_lock);
  425. if (m_completions.contains(completion.tag)) {
  426. // If it's still in the map then it can't be complete
  427. ASSERT(!completion.completed);
  428. return false;
  429. }
  430. // if it's not in the map anymore, it must be complete. But we MUST
  431. // hold m_lock to be able to check completion.completed!
  432. ASSERT(completion.completed);
  433. return true;
  434. }
  435. KResult Plan9FS::post_message(Message& message, RefPtr<ReceiveCompletion> completion)
  436. {
  437. auto& buffer = message.build();
  438. const u8* data = buffer.data();
  439. size_t size = buffer.size();
  440. auto& description = file_description();
  441. LOCKER(m_send_lock);
  442. if (completion) {
  443. // Save the completion record *before* we send the message. This
  444. // ensures that it exists when the thread reads the response
  445. LOCKER(m_lock);
  446. auto tag = completion->tag;
  447. m_completions.set(tag, completion.release_nonnull());
  448. // TODO: What if there is a collision? Do we need to wait until
  449. // the existing record with the tag completes before queueing
  450. // this one?
  451. }
  452. while (size > 0) {
  453. if (!description.can_write()) {
  454. auto unblock_flags = Thread::FileBlocker::BlockFlags::None;
  455. if (Thread::current()->block<Thread::WriteBlocker>({}, description, unblock_flags).was_interrupted())
  456. return KResult(-EINTR);
  457. }
  458. auto data_buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>(data));
  459. auto nwritten_or_error = description.write(data_buffer, size);
  460. if (nwritten_or_error.is_error())
  461. return nwritten_or_error.error();
  462. auto nwritten = nwritten_or_error.value();
  463. data += nwritten;
  464. size -= nwritten;
  465. }
  466. return KSuccess;
  467. }
  468. KResult Plan9FS::do_read(u8* data, size_t size)
  469. {
  470. auto& description = file_description();
  471. while (size > 0) {
  472. if (!description.can_read()) {
  473. auto unblock_flags = Thread::FileBlocker::BlockFlags::None;
  474. if (Thread::current()->block<Thread::ReadBlocker>({}, description, unblock_flags).was_interrupted())
  475. return KResult(-EINTR);
  476. }
  477. auto data_buffer = UserOrKernelBuffer::for_kernel_buffer(data);
  478. auto nread_or_error = description.read(data_buffer, size);
  479. if (nread_or_error.is_error())
  480. return nread_or_error.error();
  481. auto nread = nread_or_error.value();
  482. if (nread == 0)
  483. return KResult(-EIO);
  484. data += nread;
  485. size -= nread;
  486. }
  487. return KSuccess;
  488. }
  489. KResult Plan9FS::read_and_dispatch_one_message()
  490. {
  491. struct [[gnu::packed]] Header {
  492. u32 size;
  493. u8 type;
  494. u16 tag;
  495. };
  496. Header header;
  497. KResult result = do_read(reinterpret_cast<u8*>(&header), sizeof(header));
  498. if (result.is_error())
  499. return result;
  500. auto buffer = KBuffer::try_create_with_size(header.size, Region::Access::Read | Region::Access::Write);
  501. if (!buffer)
  502. return KResult(-ENOMEM);
  503. // Copy the already read header into the buffer.
  504. memcpy(buffer->data(), &header, sizeof(header));
  505. result = do_read(buffer->data() + sizeof(header), header.size - sizeof(header));
  506. if (result.is_error())
  507. return result;
  508. LOCKER(m_lock);
  509. auto optional_completion = m_completions.get(header.tag);
  510. if (optional_completion.has_value()) {
  511. auto completion = optional_completion.value();
  512. ScopedSpinLock lock(completion->lock);
  513. completion->result = KSuccess;
  514. completion->message = new Message { buffer.release_nonnull() };
  515. completion->completed = true;
  516. m_completions.remove(header.tag);
  517. m_completion_blocker.unblock_completed(header.tag);
  518. } else {
  519. dbgln("Received a 9p message of type {} with an unexpected tag {}, dropping", header.type, header.tag);
  520. }
  521. return KSuccess;
  522. }
  523. KResult Plan9FS::post_message_and_explicitly_ignore_reply(Message& message)
  524. {
  525. return post_message(message, {});
  526. }
  527. KResult Plan9FS::post_message_and_wait_for_a_reply(Message& message)
  528. {
  529. auto request_type = message.type();
  530. auto tag = message.tag();
  531. auto completion = adopt(*new ReceiveCompletion(tag));
  532. auto result = post_message(message, completion);
  533. if (result.is_error())
  534. return result;
  535. if (Thread::current()->block<Plan9FS::Blocker>({}, *this, message, completion).was_interrupted())
  536. return KResult(-EINTR);
  537. if (completion->result.is_error()) {
  538. dbgln("Plan9FS: Message was aborted with error {}", completion->result.error());
  539. return KResult(-EIO);
  540. }
  541. auto reply_type = message.type();
  542. if (reply_type == Message::Type::Rlerror) {
  543. // Contains a numerical Linux errno; hopefully our errno numbers match.
  544. u32 error_code;
  545. message >> error_code;
  546. return KResult(-error_code);
  547. } else if (reply_type == Message::Type::Rerror) {
  548. // Contains an error message. We could attempt to parse it, but for now
  549. // we simply return -EIO instead. In 9P200.u, it can also contain a
  550. // numerical errno in an unspecified encoding; we ignore those too.
  551. StringView error_name;
  552. message >> error_name;
  553. dbgln("Plan9FS: Received error name {}", error_name);
  554. return KResult(-EIO);
  555. } else if ((u8)reply_type != (u8)request_type + 1) {
  556. // Other than those error messages. we only expect the matching reply
  557. // message type.
  558. dbgln("Plan9FS: Received unexpected message type {} in response to {}", (u8)reply_type, (u8)request_type);
  559. return KResult(-EIO);
  560. } else {
  561. return KSuccess;
  562. }
  563. }
  564. ssize_t Plan9FS::adjust_buffer_size(ssize_t size) const
  565. {
  566. ssize_t max_size = m_max_message_size - Message::max_header_size;
  567. return min(size, max_size);
  568. }
  569. void Plan9FS::thread_main()
  570. {
  571. dbgln("Plan9FS: Thread running");
  572. do {
  573. auto result = read_and_dispatch_one_message();
  574. if (result.is_error()) {
  575. // If we fail to read, wake up everyone with an error.
  576. LOCKER(m_lock);
  577. for (auto& it : m_completions) {
  578. it.value->result = result;
  579. it.value->completed = true;
  580. }
  581. m_completions.clear();
  582. m_completion_blocker.unblock_all();
  583. dbgln("Plan9FS: Thread terminating, error reading");
  584. return;
  585. }
  586. } while (!m_thread_shutdown);
  587. dbgln("Plan9FS: Thread terminating");
  588. }
  589. void Plan9FS::ensure_thread()
  590. {
  591. ScopedSpinLock lock(m_thread_lock);
  592. if (!m_thread_running.exchange(true, AK::MemoryOrder::memory_order_acq_rel)) {
  593. Process::create_kernel_process(m_thread, "Plan9FS", [&]() {
  594. thread_main();
  595. m_thread_running.store(false, AK::MemoryOrder::memory_order_release);
  596. });
  597. }
  598. }
  599. Plan9FSInode::Plan9FSInode(Plan9FS& fs, u32 fid)
  600. : Inode(fs, fid)
  601. {
  602. }
  603. NonnullRefPtr<Plan9FSInode> Plan9FSInode::create(Plan9FS& fs, u32 fid)
  604. {
  605. return adopt(*new Plan9FSInode(fs, fid));
  606. }
  607. Plan9FSInode::~Plan9FSInode()
  608. {
  609. Plan9FS::Message clunk_request { fs(), Plan9FS::Message::Type::Tclunk };
  610. clunk_request << fid();
  611. // FIXME: Should we observe this error somehow?
  612. [[maybe_unused]] auto rc = fs().post_message_and_explicitly_ignore_reply(clunk_request);
  613. }
  614. KResult Plan9FSInode::ensure_open_for_mode(int mode)
  615. {
  616. bool use_lopen = fs().m_remote_protocol_version >= Plan9FS::ProtocolVersion::v9P2000L;
  617. u32 l_mode = 0;
  618. u8 p9_mode = 0;
  619. {
  620. LOCKER(m_lock);
  621. // If it's already open in this mode, we're done.
  622. if ((m_open_mode & mode) == mode)
  623. return KSuccess;
  624. m_open_mode |= mode;
  625. if ((m_open_mode & O_RDWR) == O_RDWR) {
  626. l_mode |= 2;
  627. p9_mode |= 2;
  628. } else if (m_open_mode & O_WRONLY) {
  629. l_mode |= 1;
  630. p9_mode |= 1;
  631. } else if (m_open_mode & O_RDONLY) {
  632. // Leave the values at 0.
  633. }
  634. }
  635. if (use_lopen) {
  636. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Tlopen };
  637. message << fid() << l_mode;
  638. return fs().post_message_and_wait_for_a_reply(message);
  639. } else {
  640. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Topen };
  641. message << fid() << p9_mode;
  642. return fs().post_message_and_wait_for_a_reply(message);
  643. }
  644. }
  645. ssize_t Plan9FSInode::read_bytes(off_t offset, ssize_t size, UserOrKernelBuffer& buffer, FileDescription*) const
  646. {
  647. auto result = const_cast<Plan9FSInode&>(*this).ensure_open_for_mode(O_RDONLY);
  648. if (result.is_error())
  649. return result;
  650. size = fs().adjust_buffer_size(size);
  651. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Treadlink };
  652. StringView data;
  653. // Try readlink first.
  654. bool readlink_succeded = false;
  655. if (fs().m_remote_protocol_version >= Plan9FS::ProtocolVersion::v9P2000L && offset == 0) {
  656. message << fid();
  657. result = fs().post_message_and_wait_for_a_reply(message);
  658. if (result.is_success()) {
  659. readlink_succeded = true;
  660. message >> data;
  661. }
  662. }
  663. if (!readlink_succeded) {
  664. message = Plan9FS::Message { fs(), Plan9FS::Message::Type::Tread };
  665. message << fid() << (u64)offset << (u32)size;
  666. result = fs().post_message_and_wait_for_a_reply(message);
  667. if (result.is_error())
  668. return result.error();
  669. data = message.read_data();
  670. }
  671. // Guard against the server returning more data than requested.
  672. size_t nread = min(data.length(), (size_t)size);
  673. if (!buffer.write(data.characters_without_null_termination(), nread))
  674. return -EFAULT;
  675. return nread;
  676. }
  677. ssize_t Plan9FSInode::write_bytes(off_t offset, ssize_t size, const UserOrKernelBuffer& data, FileDescription*)
  678. {
  679. auto result = ensure_open_for_mode(O_WRONLY);
  680. if (result.is_error())
  681. return result;
  682. size = fs().adjust_buffer_size(size);
  683. auto data_copy = data.copy_into_string(size); // FIXME: this seems ugly
  684. if (data_copy.is_null())
  685. return -EFAULT;
  686. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Twrite };
  687. message << fid() << (u64)offset;
  688. message.append_data(data_copy);
  689. result = fs().post_message_and_wait_for_a_reply(message);
  690. if (result.is_error())
  691. return result.error();
  692. u32 nwritten;
  693. message >> nwritten;
  694. return nwritten;
  695. }
  696. InodeMetadata Plan9FSInode::metadata() const
  697. {
  698. InodeMetadata metadata;
  699. metadata.inode = identifier();
  700. // 9P2000.L; TODO: 9P2000 & 9P2000.u
  701. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Tgetattr };
  702. message << fid() << (u64)GetAttrMask::Basic;
  703. auto result = fs().post_message_and_wait_for_a_reply(message);
  704. if (result.is_error()) {
  705. // Just return blank metadata; hopefully that's enough to result in an
  706. // error at some upper layer. Ideally, there would be a way for
  707. // Inode::metadata() to return failure.
  708. return metadata;
  709. }
  710. u64 valid;
  711. Plan9FS::qid qid;
  712. u32 mode;
  713. u32 uid;
  714. u32 gid;
  715. u64 nlink;
  716. u64 rdev;
  717. u64 size;
  718. u64 blksize;
  719. u64 blocks;
  720. message >> valid >> qid >> mode >> uid >> gid >> nlink >> rdev >> size >> blksize >> blocks;
  721. // TODO: times...
  722. if (valid & (u64)GetAttrMask::Mode)
  723. metadata.mode = mode;
  724. if (valid & (u64)GetAttrMask::NLink)
  725. metadata.link_count = nlink;
  726. #if 0
  727. // FIXME: Map UID/GID somehow? Or what do we do?
  728. if (valid & (u64)GetAttrMask::UID)
  729. metadata.uid = uid;
  730. if (valid & (u64)GetAttrMask::GID)
  731. metadata.uid = gid;
  732. // FIXME: What about device nodes?
  733. if (valid & (u64)GetAttrMask::RDev)
  734. metadata.encoded_device = 0; // TODO
  735. #endif
  736. if (valid & (u64)GetAttrMask::Size)
  737. metadata.size = size;
  738. if (valid & (u64)GetAttrMask::Blocks) {
  739. metadata.block_size = blksize;
  740. metadata.block_count = blocks;
  741. }
  742. return metadata;
  743. }
  744. void Plan9FSInode::flush_metadata()
  745. {
  746. // Do nothing.
  747. }
  748. KResultOr<size_t> Plan9FSInode::directory_entry_count() const
  749. {
  750. size_t count = 0;
  751. KResult result = traverse_as_directory([&count](auto&) {
  752. count++;
  753. return true;
  754. });
  755. if (result.is_error())
  756. return result;
  757. return count;
  758. }
  759. KResult Plan9FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntryView&)> callback) const
  760. {
  761. KResult result = KSuccess;
  762. // TODO: Should we synthesize "." and ".." here?
  763. if (fs().m_remote_protocol_version >= Plan9FS::ProtocolVersion::v9P2000L) {
  764. // Start by cloning the fid and opening it.
  765. auto clone_fid = fs().allocate_fid();
  766. {
  767. Plan9FS::Message clone_message { fs(), Plan9FS::Message::Type::Twalk };
  768. clone_message << fid() << clone_fid << (u16)0;
  769. result = fs().post_message_and_wait_for_a_reply(clone_message);
  770. if (result.is_error())
  771. return result;
  772. Plan9FS::Message open_message { fs(), Plan9FS::Message::Type::Tlopen };
  773. open_message << clone_fid << (u32)0;
  774. result = fs().post_message_and_wait_for_a_reply(open_message);
  775. if (result.is_error()) {
  776. Plan9FS::Message close_message { fs(), Plan9FS::Message::Type::Tclunk };
  777. close_message << clone_fid;
  778. // FIXME: Should we observe this error?
  779. [[maybe_unused]] auto rc = fs().post_message_and_explicitly_ignore_reply(close_message);
  780. return result;
  781. }
  782. }
  783. u64 offset = 0;
  784. u32 count = fs().adjust_buffer_size(8 * MiB);
  785. while (true) {
  786. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Treaddir };
  787. message << clone_fid << offset << count;
  788. result = fs().post_message_and_wait_for_a_reply(message);
  789. if (result.is_error())
  790. break;
  791. StringView data = message.read_data();
  792. if (data.is_empty()) {
  793. // We've reached the end.
  794. break;
  795. }
  796. for (Plan9FS::Message::Decoder decoder { data }; decoder.has_more_data();) {
  797. Plan9FS::qid qid;
  798. u8 type;
  799. StringView name;
  800. decoder >> qid >> offset >> type >> name;
  801. callback({ name, { fsid(), fs().allocate_fid() }, 0 });
  802. }
  803. }
  804. Plan9FS::Message close_message { fs(), Plan9FS::Message::Type::Tclunk };
  805. close_message << clone_fid;
  806. // FIXME: Should we observe this error?
  807. [[maybe_unused]] auto rc = fs().post_message_and_explicitly_ignore_reply(close_message);
  808. return result;
  809. } else {
  810. // TODO
  811. return KResult(-ENOTIMPL);
  812. }
  813. }
  814. RefPtr<Inode> Plan9FSInode::lookup(StringView name)
  815. {
  816. u32 newfid = fs().allocate_fid();
  817. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Twalk };
  818. message << fid() << newfid << (u16)1 << name;
  819. auto result = fs().post_message_and_wait_for_a_reply(message);
  820. if (result.is_error())
  821. return nullptr;
  822. return Plan9FSInode::create(fs(), newfid);
  823. }
  824. KResultOr<NonnullRefPtr<Inode>> Plan9FSInode::create_child(const String&, mode_t, dev_t, uid_t, gid_t)
  825. {
  826. // TODO
  827. return KResult(-ENOTIMPL);
  828. }
  829. KResult Plan9FSInode::add_child(Inode&, const StringView&, mode_t)
  830. {
  831. // TODO
  832. return KResult(-ENOTIMPL);
  833. }
  834. KResult Plan9FSInode::remove_child(const StringView&)
  835. {
  836. // TODO
  837. return KResult(-ENOTIMPL);
  838. }
  839. KResult Plan9FSInode::chmod(mode_t)
  840. {
  841. // TODO
  842. return KResult(-ENOTIMPL);
  843. }
  844. KResult Plan9FSInode::chown(uid_t, gid_t)
  845. {
  846. // TODO
  847. return KResult(-ENOTIMPL);
  848. }
  849. KResult Plan9FSInode::truncate(u64 new_size)
  850. {
  851. if (fs().m_remote_protocol_version >= Plan9FS::ProtocolVersion::v9P2000L) {
  852. Plan9FS::Message message { fs(), Plan9FS::Message::Type::Tsetattr };
  853. SetAttrMask valid = SetAttrMask::Size;
  854. u32 mode = 0;
  855. u32 uid = 0;
  856. u32 gid = 0;
  857. u64 atime_sec = 0;
  858. u64 atime_nsec = 0;
  859. u64 mtime_sec = 0;
  860. u64 mtime_nsec = 0;
  861. message << fid() << (u64)valid << mode << uid << gid << new_size << atime_sec << atime_nsec << mtime_sec << mtime_nsec;
  862. return fs().post_message_and_wait_for_a_reply(message);
  863. } else {
  864. // TODO: wstat version
  865. return KSuccess;
  866. }
  867. }
  868. }