s32 _sys_lwcond_queue_wait(PPUThread& ppu, u32 lwcond_id, u32 lwmutex_id, u64 timeout) { sys_lwcond.Log("_sys_lwcond_queue_wait(lwcond_id=0x%x, lwmutex_id=0x%x, timeout=0x%llx)", lwcond_id, lwmutex_id, timeout); const u64 start_time = get_system_time(); LV2_LOCK; const auto cond = idm::get<lv2_lwcond_t>(lwcond_id); const auto mutex = idm::get<lv2_lwmutex_t>(lwmutex_id); if (!cond || !mutex) { return CELL_ESRCH; } // finalize unlocking the mutex mutex->unlock(lv2_lock); // add waiter; protocol is ignored in current implementation sleep_queue_entry_t waiter(ppu, cond->sq); // potential mutex waiter (not added immediately) sleep_queue_entry_t mutex_waiter(ppu, cond->sq, defer_sleep); while (!ppu.unsignal()) { CHECK_EMU_STATUS; if (timeout && waiter) { const u64 passed = get_system_time() - start_time; if (passed >= timeout) { // try to reown the mutex if timed out if (mutex->signaled) { mutex->signaled--; return CELL_EDEADLK; } else { return CELL_ETIMEDOUT; } } ppu.cv.wait_for(lv2_lock, std::chrono::microseconds(timeout - passed)); } else { ppu.cv.wait(lv2_lock); } } // return cause return ppu.GPR[3] ? CELL_EBUSY : CELL_OK; }
s32 sys_cond_wait(PPUThread& ppu, u32 cond_id, u64 timeout) { sys_cond.Log("sys_cond_wait(cond_id=0x%x, timeout=%lld)", cond_id, timeout); const u64 start_time = get_system_time(); LV2_LOCK; const auto cond = Emu.GetIdManager().get<lv2_cond_t>(cond_id); if (!cond) { return CELL_ESRCH; } // check current ownership if (cond->mutex->owner.get() != &ppu) { return CELL_EPERM; } // save the recursive value const u32 recursive_value = cond->mutex->recursive_count.exchange(0); // unlock the mutex cond->mutex->unlock(lv2_lock); // add waiter; protocol is ignored in current implementation sleep_queue_entry_t waiter(ppu, cond->sq); // potential mutex waiter (not added immediately) sleep_queue_entry_t mutex_waiter(ppu, cond->mutex->sq, defer_sleep); while (!ppu.unsignal()) { CHECK_EMU_STATUS; // timeout is ignored if waiting on the cond var is already dropped if (timeout && waiter) { const u64 passed = get_system_time() - start_time; if (passed >= timeout) { // try to reown mutex and exit if timed out if (!cond->mutex->owner) { cond->mutex->owner = ppu.shared_from_this(); break; } // drop condition variable and start waiting on the mutex queue mutex_waiter.enter(); waiter.leave(); continue; } ppu.cv.wait_for(lv2_lock, std::chrono::microseconds(timeout - passed)); } else { ppu.cv.wait(lv2_lock); } } // mutex owner is restored after notification or unlocking if (cond->mutex->owner.get() != &ppu) { throw EXCEPTION("Unexpected mutex owner"); } // restore the recursive value cond->mutex->recursive_count = recursive_value; // check timeout (unclear) if (timeout && get_system_time() - start_time > timeout) { return CELL_ETIMEDOUT; } return CELL_OK; }