| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | #pragma once |
| 4 | |
| 5 | #include "mos/io/io.hpp" |
| 6 | #include "mos/tasks/wait.hpp" |
| 7 | |
| 8 | #include <mos/allocator.hpp> |
| 9 | #include <mos/lib/structures/ring_buffer.hpp> |
| 10 | |
| 11 | struct pipe_t : mos::NamedType<"Pipe" > |
| 12 | { |
| 13 | u32 magic; |
| 14 | waitlist_t waitlist; ///< for both reader and writer, only one party can wait on the pipe at a time |
| 15 | spinlock_t lock; ///< protects the buffer_pos (and thus the buffer) |
| 16 | bool other_closed; ///< true if the other end of the pipe has been closed |
| 17 | void *buffers; |
| 18 | ring_buffer_pos_t buffer_pos; |
| 19 | }; |
| 20 | |
| 21 | PtrResult<pipe_t> pipe_create(size_t bufsize); |
| 22 | size_t pipe_read(pipe_t *pipe, void *buf, size_t size); |
| 23 | size_t pipe_write(pipe_t *pipe, const void *buf, size_t size); |
| 24 | |
| 25 | /** |
| 26 | * @brief Close one end of the pipe, so that the other end will get EOF. |
| 27 | * @note The other end should also call this function to get the pipe correctly freed. |
| 28 | * |
| 29 | * @param pipe The pipe to close one end of. |
| 30 | * @return true if the pipe was fully closed, false if the other end is still open. |
| 31 | */ |
| 32 | __nodiscard bool pipe_close_one_end(pipe_t *pipe); |
| 33 | |
| 34 | struct PipeIOImpl : IO |
| 35 | { |
| 36 | explicit PipeIOImpl(IOFlags flags) : IO(flags, IO_PIPE) {}; |
| 37 | |
| 38 | size_t on_read(void *buf, size_t size) override; |
| 39 | size_t on_write(const void *buf, size_t size) override; |
| 40 | void on_closed() override; |
| 41 | }; |
| 42 | |
| 43 | struct pipeio_t : mos::NamedType<"PipeIO" > |
| 44 | { |
| 45 | explicit pipeio_t(pipe_t *pipe) : pipe(pipe), io_r(IO_READABLE), io_w(IO_WRITABLE) {}; |
| 46 | |
| 47 | pipe_t *const pipe; |
| 48 | PipeIOImpl io_r, io_w; |
| 49 | }; |
| 50 | |
| 51 | pipeio_t *pipeio_create(pipe_t *pipe); |
| 52 | |