1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 14:17:36 +00:00

AK: Make RefPtr, NonnullRefPtr, WeakPtr thread safe

This makes most operations thread safe, especially so that they
can safely be used in the Kernel. This includes obtaining a strong
reference from a weak reference, which now requires an explicit
call to WeakPtr::strong_ref(). Another major change is that
Weakable::make_weak_ref() may require the explicit target type.
Previously we used reinterpret_cast in WeakPtr, assuming that it
can be properly converted. But WeakPtr does not necessarily have
the knowledge to be able to do this. Instead, we now ask the class
itself to deliver a WeakPtr to the type that we want.

Also, WeakLink is no longer specific to a target type. The reason
for this is that we want to be able to safely convert e.g. WeakPtr<T>
to WeakPtr<U>, and before this we just reinterpret_cast the internal
WeakLink<T> to WeakLink<U>, which is a bold assumption that it would
actually produce the correct code. Instead, WeakLink now operates
on just a raw pointer and we only make those constructors/operators
available if we can verify that it can be safely cast.

In order to guarantee thread safety, we now use the least significant
bit in the pointer for locking purposes. This also means that only
properly aligned pointers can be used.
This commit is contained in:
Tom 2020-09-29 16:26:13 -06:00 committed by Andreas Kling
parent 3c1ef744f6
commit 75f61fe3d9
50 changed files with 819 additions and 322 deletions

View file

@ -113,7 +113,7 @@ DevPtsFSInode::DevPtsFSInode(DevPtsFS& fs, unsigned index, SlavePTY* pty)
: Inode(fs, index)
{
if (pty)
m_pty = pty->make_weak_ptr();
m_pty = *pty;
}
DevPtsFSInode::~DevPtsFSInode()
@ -132,9 +132,9 @@ ssize_t DevPtsFSInode::write_bytes(off_t, ssize_t, const UserOrKernelBuffer&, Fi
InodeMetadata DevPtsFSInode::metadata() const
{
if (m_pty) {
if (auto pty = m_pty.strong_ref()) {
auto metadata = m_metadata;
metadata.mtime = m_pty->time_of_last_write();
metadata.mtime = pty->time_of_last_write();
return metadata;
}
return m_metadata;

View file

@ -129,14 +129,14 @@ void Inode::will_be_destroyed()
void Inode::inode_contents_changed(off_t offset, ssize_t size, const UserOrKernelBuffer& data)
{
if (m_shared_vmobject)
m_shared_vmobject->inode_contents_changed({}, offset, size, data);
if (auto shared_vmobject = this->shared_vmobject())
shared_vmobject->inode_contents_changed({}, offset, size, data);
}
void Inode::inode_size_changed(size_t old_size, size_t new_size)
{
if (m_shared_vmobject)
m_shared_vmobject->inode_size_changed({}, old_size, new_size);
if (auto shared_vmobject = this->shared_vmobject())
shared_vmobject->inode_size_changed({}, old_size, new_size);
}
int Inode::set_atime(time_t)
@ -166,7 +166,7 @@ KResult Inode::decrement_link_count()
void Inode::set_shared_vmobject(SharedInodeVMObject& vmobject)
{
m_shared_vmobject = vmobject.make_weak_ptr();
m_shared_vmobject = vmobject;
}
bool Inode::bind_socket(LocalSocket& socket)
@ -260,4 +260,19 @@ KResult Inode::prepare_to_write_data()
return KSuccess;
}
RefPtr<SharedInodeVMObject> Inode::shared_vmobject()
{
return m_shared_vmobject.strong_ref();
}
RefPtr<SharedInodeVMObject> Inode::shared_vmobject() const
{
return m_shared_vmobject.strong_ref();
}
bool Inode::is_shared_vmobject(const SharedInodeVMObject& other) const
{
return m_shared_vmobject.unsafe_ptr() == &other;
}
}

View file

@ -102,8 +102,9 @@ public:
void will_be_destroyed();
void set_shared_vmobject(SharedInodeVMObject&);
SharedInodeVMObject* shared_vmobject() { return m_shared_vmobject.ptr(); }
const SharedInodeVMObject* shared_vmobject() const { return m_shared_vmobject.ptr(); }
RefPtr<SharedInodeVMObject> shared_vmobject();
RefPtr<SharedInodeVMObject> shared_vmobject() const;
bool is_shared_vmobject(const SharedInodeVMObject&) const;
static InlineLinkedList<Inode>& all_with_lock();
static void sync();

View file

@ -36,15 +36,15 @@ NonnullRefPtr<InodeWatcher> InodeWatcher::create(Inode& inode)
}
InodeWatcher::InodeWatcher(Inode& inode)
: m_inode(inode.make_weak_ptr())
: m_inode(inode)
{
inode.register_watcher({}, *this);
}
InodeWatcher::~InodeWatcher()
{
if (RefPtr<Inode> safe_inode = m_inode.ptr())
safe_inode->unregister_watcher({}, *this);
if (auto inode = m_inode.strong_ref())
inode->unregister_watcher({}, *this);
}
bool InodeWatcher::can_read(const FileDescription&, size_t) const
@ -88,9 +88,9 @@ KResultOr<size_t> InodeWatcher::write(FileDescription&, size_t, const UserOrKern
String InodeWatcher::absolute_path(const FileDescription&) const
{
if (!m_inode)
return "InodeWatcher:(gone)";
return String::format("InodeWatcher:%s", m_inode->identifier().to_string().characters());
if (auto inode = m_inode.strong_ref())
return String::format("InodeWatcher:%s", inode->identifier().to_string().characters());
return "InodeWatcher:(gone)";
}
void InodeWatcher::notify_inode_event(Badge<Inode>, Event::Type event_type)

View file

@ -130,7 +130,7 @@ RefPtr<TCPSocket> TCPSocket::create_client(const IPv4Address& new_local_address,
void TCPSocket::release_to_originator()
{
ASSERT(!!m_originator);
m_originator->release_for_accept(this);
m_originator.strong_ref()->release_for_accept(this);
}
void TCPSocket::release_for_accept(RefPtr<TCPSocket> socket)

View file

@ -159,7 +159,7 @@ public:
static Lockable<HashMap<IPv4SocketTuple, RefPtr<TCPSocket>>>& closing_sockets();
RefPtr<TCPSocket> create_client(const IPv4Address& local_address, u16 local_port, const IPv4Address& peer_address, u16 peer_port);
void set_originator(TCPSocket& originator) { m_originator = originator.make_weak_ptr(); }
void set_originator(TCPSocket& originator) { m_originator = originator; }
bool has_originator() { return !!m_originator; }
void release_to_originator();
void release_for_accept(RefPtr<TCPSocket>);

View file

@ -194,7 +194,7 @@ bool Process::deallocate_region(Region& region)
OwnPtr<Region> region_protector;
ScopedSpinLock lock(m_lock);
if (m_region_lookup_cache.region == &region)
if (m_region_lookup_cache.region.unsafe_ptr() == &region)
m_region_lookup_cache.region = nullptr;
for (size_t i = 0; i < m_regions.size(); ++i) {
if (&m_regions[i] == &region) {
@ -209,13 +209,13 @@ Region* Process::find_region_from_range(const Range& range)
{
ScopedSpinLock lock(m_lock);
if (m_region_lookup_cache.range == range && m_region_lookup_cache.region)
return m_region_lookup_cache.region;
return m_region_lookup_cache.region.unsafe_ptr();
size_t size = PAGE_ROUND_UP(range.size());
for (auto& region : m_regions) {
if (region.vaddr() == range.base() && region.size() == size) {
m_region_lookup_cache.range = range;
m_region_lookup_cache.region = region.make_weak_ptr();
m_region_lookup_cache.region = region;
return &region;
}
}

View file

@ -485,6 +485,7 @@ bool Scheduler::pick_next()
Thread* thread_to_schedule = nullptr;
auto pending_beneficiary = scheduler_data.m_pending_beneficiary.strong_ref();
Vector<Thread*, 128> sorted_runnables;
for_each_runnable([&](auto& thread) {
if ((thread.affinity() & (1u << Processor::current().id())) == 0)
@ -492,7 +493,7 @@ bool Scheduler::pick_next()
if (thread.state() == Thread::Running && &thread != current_thread)
return IterationDecision::Continue;
sorted_runnables.append(&thread);
if (&thread == scheduler_data.m_pending_beneficiary) {
if (&thread == pending_beneficiary) {
thread_to_schedule = &thread;
return IterationDecision::Break;
}
@ -628,7 +629,7 @@ bool Scheduler::donate_to(RefPtr<Thread>& beneficiary, const char* reason)
ASSERT(!proc.in_irq());
if (proc.in_critical() > 1) {
scheduler_data.m_pending_beneficiary = beneficiary->make_weak_ptr(); // Save the beneficiary
scheduler_data.m_pending_beneficiary = *beneficiary; // Save the beneficiary
scheduler_data.m_pending_donate_reason = reason;
proc.invoke_scheduler_async();
return false;

View file

@ -92,13 +92,13 @@ void* SharedBuffer::ref_for_process_and_get_address(Process& process)
auto* region = process.allocate_region_with_vmobject(VirtualAddress(), size(), m_vmobject, 0, "SharedBuffer", PROT_READ | (m_writable ? PROT_WRITE : 0));
if (!region)
return (void*)-ENOMEM;
ref.region = region->make_weak_ptr();
ref.region->set_shared(true);
ref.region = region;
region->set_shared(true);
}
ref.count++;
m_total_refs++;
sanity_check("ref_for_process_and_get_address");
return ref.region->vaddr().as_ptr();
return ref.region.unsafe_ptr()->vaddr().as_ptr(); // TODO: Region needs to be RefCounted!
}
}
ASSERT_NOT_REACHED();
@ -133,7 +133,7 @@ void SharedBuffer::deref_for_process(Process& process)
#ifdef SHARED_BUFFER_DEBUG
dbg() << "Releasing shared buffer reference on " << m_shbuf_id << " of size " << size() << " by PID " << process.pid().value();
#endif
process.deallocate_region(*ref.region);
process.deallocate_region(*ref.region.unsafe_ptr()); // TODO: Region needs to be RefCounted!
#ifdef SHARED_BUFFER_DEBUG
dbg() << "Released shared buffer reference on " << m_shbuf_id << " of size " << size() << " by PID " << process.pid().value();
#endif
@ -187,9 +187,10 @@ void SharedBuffer::seal()
LOCKER(shared_buffers().lock());
m_writable = false;
for (auto& ref : m_refs) {
if (ref.region) {
ref.region->set_writable(false);
ref.region->remap();
// TODO: Region needs to be RefCounted!
if (auto* region = ref.region.unsafe_ptr()) {
region->set_writable(false);
region->remap();
}
}
}

View file

@ -88,8 +88,8 @@ pid_t Process::sys$fork(RegisterState& regs)
auto& child_region = child->add_region(region.clone());
child_region.map(child->page_directory());
if (&region == m_master_tls_region)
child->m_master_tls_region = child_region.make_weak_ptr();
if (&region == m_master_tls_region.unsafe_ptr())
child->m_master_tls_region = child_region;
}
ScopedSpinLock processes_lock(g_processes_lock);

View file

@ -166,8 +166,8 @@ void TTY::emit(u8 ch)
if (ch == m_termios.c_cc[VSUSP]) {
dbg() << tty_name() << ": VSUSP pressed!";
generate_signal(SIGTSTP);
if (m_original_process_parent)
(void)m_original_process_parent->send_signal(SIGCHLD, nullptr);
if (auto original_process_parent = m_original_process_parent.strong_ref())
(void)original_process_parent->send_signal(SIGCHLD, nullptr);
// TODO: Else send it to the session leader maybe?
return;
}
@ -330,11 +330,11 @@ int TTY::ioctl(FileDescription&, unsigned request, FlatPtr arg)
return -EPERM;
if (process && pgid != process->pgid())
return -EPERM;
m_pg = process_group->make_weak_ptr();
m_pg = *process_group;
if (process) {
if (auto parent = Process::from_pid(process->ppid())) {
m_original_process_parent = parent->make_weak_ptr();
m_original_process_parent = *parent;
return 0;
}
}

View file

@ -51,7 +51,12 @@ public:
unsigned short rows() const { return m_rows; }
unsigned short columns() const { return m_columns; }
ProcessGroupID pgid() const { return m_pg ? m_pg->pgid() : 0; }
ProcessGroupID pgid() const
{
if (auto pg = m_pg.strong_ref())
return pg->pgid();
return 0;
}
void set_termios(const termios&);
bool should_generate_signals() const { return m_termios.c_lflag & ISIG; }

View file

@ -978,7 +978,7 @@ KResult Thread::make_thread_specific_region(Badge<Process>)
m_thread_specific_data = VirtualAddress(thread_specific_data);
thread_specific_data->self = thread_specific_data;
if (process().m_master_tls_size)
memcpy(thread_local_storage, process().m_master_tls_region->vaddr().as_ptr(), process().m_master_tls_size);
memcpy(thread_local_storage, process().m_master_tls_region.unsafe_ptr()->vaddr().as_ptr(), process().m_master_tls_size);
return KSuccess;
}

View file

@ -58,7 +58,7 @@ SharedInodeVMObject::SharedInodeVMObject(const SharedInodeVMObject& other)
SharedInodeVMObject::~SharedInodeVMObject()
{
ASSERT(inode().shared_vmobject() == this);
ASSERT(inode().is_shared_vmobject(*this));
}
}