Skip to content

Commit

Permalink
Don't reinstate old context
Browse files Browse the repository at this point in the history
  • Loading branch information
hdelan committed Oct 23, 2023
1 parent 614e6d0 commit 8a453f8
Showing 1 changed file with 7 additions and 27 deletions.
34 changes: 7 additions & 27 deletions source/adapters/hip/context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,45 +165,25 @@ struct ur_context_handle_t_ {
};

namespace {
/// RAII type to guarantee recovering original HIP context
/// Scoped context is used across all UR HIP plugin implementation
/// to activate the UR Context on the current thread, matching the
/// HIP driver semantics where the context used for the HIP Driver
/// API is the one active on the thread.
/// The implementation tries to avoid replacing the hipCtx_t if it cans
/// Scoped context is used across all UR HIP plugin implementation to activate
/// the native Context on the current thread. The ScopedContext does not
/// reinstate the previous context as all operations in the hip adapter that
/// require and active context, set the active context and don't rely on context
/// reinstation
class ScopedContext {
hipCtx_t Original;
bool NeedToRecover;

public:
ScopedContext(ur_device_handle_t hDevice) : NeedToRecover{false} {
ScopedContext(ur_device_handle_t hDevice) {
hipCtx_t Original{};

if (!hDevice) {
throw UR_RESULT_ERROR_INVALID_DEVICE;
}

// FIXME when multi device context are supported in HIP adapter
hipCtx_t Desired = hDevice->getNativeContext();
UR_CHECK_ERROR(hipCtxGetCurrent(&Original));
if (Original != Desired) {
// Sets the desired context as the active one for the thread
UR_CHECK_ERROR(hipCtxSetCurrent(Desired));
if (Original == nullptr) {
// No context is installed on the current thread
// This is the most common case. We can activate the context in the
// thread and leave it there until all the UR context referring to the
// same underlying HIP context are destroyed. This emulates
// the behaviour of the HIP runtime api, and avoids costly context
// switches. No action is required on this side of the if.
} else {
NeedToRecover = true;
}
}
}

~ScopedContext() {
if (NeedToRecover) {
UR_CHECK_ERROR(hipCtxSetCurrent(Original));
}
}
};
Expand Down

0 comments on commit 8a453f8

Please sign in to comment.