Skip to content

Commit ae99966

Browse files
[OpenMP] Enable automatic unified shared memory on MI300A. (#77512)
This patch enables applications that did not request OpenMP unified_shared_memory to run with the same zero-copy behavior, where mapped memory does not result in extra memory allocations and memory copies, but CPU-allocated memory is accessed from the device. The name for this behavior is "automatic zero-copy" and it relies on detecting: that the runtime is running on a MI300A, that the user did not select unified_shared_memory in their program, and that XNACK (unified memory support) is enabled in the current GPU configuration. If all these conditions are met, then automatic zero-copy is triggered. This patch also introduces an environment variable OMPX_APU_MAPS that, if set, triggers automatic zero-copy also on non APU GPUs (e.g., on discrete GPUs). This patch is still missing support for global variables, which will be provided in a subsequent patch. Co-authored-by: Thorsten Blass <[email protected]>
1 parent 4897b98 commit ae99966

File tree

12 files changed

+219
-28
lines changed

12 files changed

+219
-28
lines changed

openmp/libomptarget/include/Shared/PluginAPI.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,9 @@ int32_t __tgt_rtl_initialize_record_replay(int32_t DeviceId, int64_t MemorySize,
219219
void *VAddr, bool isRecord,
220220
bool SaveOutput,
221221
uint64_t &ReqPtrArgOffset);
222+
223+
// Returns true if the device \p DeviceId suggests to use auto zero-copy.
224+
int32_t __tgt_rtl_use_auto_zero_copy(int32_t DeviceId);
222225
}
223226

224227
#endif // OMPTARGET_SHARED_PLUGIN_API_H

openmp/libomptarget/include/Shared/PluginAPI.inc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,4 @@ PLUGIN_API_HANDLE(data_notify_mapped, false);
4747
PLUGIN_API_HANDLE(data_notify_unmapped, false);
4848
PLUGIN_API_HANDLE(set_device_offset, false);
4949
PLUGIN_API_HANDLE(initialize_record_replay, false);
50+
PLUGIN_API_HANDLE(use_auto_zero_copy, false);

openmp/libomptarget/include/Shared/Requirements.h

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,12 @@ enum OpenMPOffloadingRequiresDirFlags : int64_t {
3333
/// unified_shared_memory clause.
3434
OMP_REQ_UNIFIED_SHARED_MEMORY = 0x008,
3535
/// dynamic_allocators clause.
36-
OMP_REQ_DYNAMIC_ALLOCATORS = 0x010
36+
OMP_REQ_DYNAMIC_ALLOCATORS = 0x010,
37+
/// Auto zero-copy extension:
38+
/// when running on an APU, the GPU plugin may decide to
39+
/// run in zero-copy even though the user did not program
40+
/// their application with unified_shared_memory requirement.
41+
OMPX_REQ_AUTO_ZERO_COPY = 0x020
3742
};
3843

3944
class RequirementCollection {
@@ -65,6 +70,14 @@ class RequirementCollection {
6570
return;
6671
}
6772

73+
// Auto zero-copy is only valid when no other requirement has been set
74+
// and it is computed at device initialization time, after the requirement
75+
// flag has already been set to OMP_REQ_NONE.
76+
if (SetFlags == OMP_REQ_NONE && NewFlags == OMPX_REQ_AUTO_ZERO_COPY) {
77+
SetFlags = NewFlags;
78+
return;
79+
}
80+
6881
// If multiple compilation units are present enforce
6982
// consistency across all of them for require clauses:
7083
// - reverse_offload

openmp/libomptarget/include/device.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,9 @@ struct DeviceTy {
164164
/// Print all offload entries to stderr.
165165
void dumpOffloadEntries();
166166

167+
/// Ask the device whether the runtime should use auto zero-copy.
168+
bool useAutoZeroCopy();
169+
167170
private:
168171
/// Deinitialize the device (and plugin).
169172
void deinit();

openmp/libomptarget/plugins-nextgen/amdgpu/dynamic_hsa/hsa_ext_amd.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ typedef enum {
6363
} hsa_amd_memory_pool_access_t;
6464

6565
typedef enum hsa_amd_agent_info_s {
66+
HSA_AMD_AGENT_INFO_CHIP_ID = 0xA000,
6667
HSA_AMD_AGENT_INFO_CACHELINE_SIZE = 0xA001,
6768
HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT = 0xA002,
6869
HSA_AMD_AGENT_INFO_MAX_CLOCK_FREQUENCY = 0xA003,

openmp/libomptarget/plugins-nextgen/amdgpu/src/rtl.cpp

Lines changed: 98 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,29 @@ Error asyncMemCopy(bool UseMultipleSdmaEngines, void *Dst, hsa_agent_t DstAgent,
184184
#endif
185185
}
186186

187+
Expected<std::string> getTargetTripleAndFeatures(hsa_agent_t Agent) {
188+
std::string Target;
189+
auto Err = utils::iterateAgentISAs(Agent, [&](hsa_isa_t ISA) {
190+
uint32_t Length;
191+
hsa_status_t Status;
192+
Status = hsa_isa_get_info_alt(ISA, HSA_ISA_INFO_NAME_LENGTH, &Length);
193+
if (Status != HSA_STATUS_SUCCESS)
194+
return Status;
195+
196+
llvm::SmallVector<char> ISAName(Length);
197+
Status = hsa_isa_get_info_alt(ISA, HSA_ISA_INFO_NAME, ISAName.begin());
198+
if (Status != HSA_STATUS_SUCCESS)
199+
return Status;
200+
201+
llvm::StringRef TripleTarget(ISAName.begin(), Length);
202+
if (TripleTarget.consume_front("amdgcn-amd-amdhsa"))
203+
Target = TripleTarget.ltrim('-').rtrim('\0').str();
204+
return HSA_STATUS_SUCCESS;
205+
});
206+
if (Err)
207+
return Err;
208+
return Target;
209+
}
187210
} // namespace utils
188211

189212
/// Utility class representing generic resource references to AMDGPU resources.
@@ -1849,8 +1872,9 @@ struct AMDGPUDeviceTy : public GenericDeviceTy, AMDGenericDeviceTy {
18491872
OMPX_StreamBusyWait("LIBOMPTARGET_AMDGPU_STREAM_BUSYWAIT", 2000000),
18501873
OMPX_UseMultipleSdmaEngines(
18511874
"LIBOMPTARGET_AMDGPU_USE_MULTIPLE_SDMA_ENGINES", false),
1852-
AMDGPUStreamManager(*this, Agent), AMDGPUEventManager(*this),
1853-
AMDGPUSignalManager(*this), Agent(Agent), HostDevice(HostDevice) {}
1875+
OMPX_ApuMaps("OMPX_APU_MAPS", false), AMDGPUStreamManager(*this, Agent),
1876+
AMDGPUEventManager(*this), AMDGPUSignalManager(*this), Agent(Agent),
1877+
HostDevice(HostDevice) {}
18541878

18551879
~AMDGPUDeviceTy() {}
18561880

@@ -1941,6 +1965,19 @@ struct AMDGPUDeviceTy : public GenericDeviceTy, AMDGenericDeviceTy {
19411965
if (auto Err = AMDGPUSignalManager.init(OMPX_InitialNumSignals))
19421966
return Err;
19431967

1968+
// Detect if XNACK is enabled
1969+
auto TargeTripleAndFeaturesOrError =
1970+
utils::getTargetTripleAndFeatures(Agent);
1971+
if (!TargeTripleAndFeaturesOrError)
1972+
return TargeTripleAndFeaturesOrError.takeError();
1973+
if (static_cast<StringRef>(*TargeTripleAndFeaturesOrError)
1974+
.contains("xnack+"))
1975+
IsXnackEnabled = true;
1976+
1977+
// detect if device is an APU.
1978+
if (auto Err = checkIfAPU())
1979+
return Err;
1980+
19441981
return Plugin::success();
19451982
}
19461983

@@ -2650,6 +2687,21 @@ struct AMDGPUDeviceTy : public GenericDeviceTy, AMDGenericDeviceTy {
26502687
return Plugin::success();
26512688
}
26522689

2690+
/// Returns true if auto zero-copy the best configuration for the current
2691+
/// arch.
2692+
/// On AMDGPUs, automatic zero-copy is turned on
2693+
/// when running on an APU with XNACK (unified memory) support
2694+
/// enabled. On discrete GPUs, automatic zero-copy is triggered
2695+
/// if the user sets the environment variable OMPX_APU_MAPS=1
2696+
/// and if XNACK is enabled. The rationale is that zero-copy
2697+
/// is the best configuration (performance, memory footprint) on APUs,
2698+
/// while it is often not the best on discrete GPUs.
2699+
/// XNACK can be enabled with a kernel boot parameter or with
2700+
/// the HSA_XNACK environment variable.
2701+
bool useAutoZeroCopyImpl() override {
2702+
return ((IsAPU || OMPX_ApuMaps) && IsXnackEnabled);
2703+
}
2704+
26532705
/// Getters and setters for stack and heap sizes.
26542706
Error getDeviceStackSize(uint64_t &Value) override {
26552707
Value = StackSize;
@@ -2749,6 +2801,34 @@ struct AMDGPUDeviceTy : public GenericDeviceTy, AMDGenericDeviceTy {
27492801
return Err;
27502802
}
27512803

2804+
/// Detect if current architecture is an APU.
2805+
Error checkIfAPU() {
2806+
// TODO: replace with ROCr API once it becomes available.
2807+
llvm::StringRef StrGfxName(ComputeUnitKind);
2808+
IsAPU = llvm::StringSwitch<bool>(StrGfxName)
2809+
.Case("gfx940", true)
2810+
.Default(false);
2811+
if (IsAPU)
2812+
return Plugin::success();
2813+
2814+
bool MayBeAPU = llvm::StringSwitch<bool>(StrGfxName)
2815+
.Case("gfx942", true)
2816+
.Default(false);
2817+
if (!MayBeAPU)
2818+
return Plugin::success();
2819+
2820+
// can be MI300A or MI300X
2821+
uint32_t ChipID = 0;
2822+
if (auto Err = getDeviceAttr(HSA_AMD_AGENT_INFO_CHIP_ID, ChipID))
2823+
return Err;
2824+
2825+
if (!(ChipID & 0x1)) {
2826+
IsAPU = true;
2827+
return Plugin::success();
2828+
}
2829+
return Plugin::success();
2830+
}
2831+
27522832
/// Envar for controlling the number of HSA queues per device. High number of
27532833
/// queues may degrade performance.
27542834
UInt32Envar OMPX_NumQueues;
@@ -2785,6 +2865,10 @@ struct AMDGPUDeviceTy : public GenericDeviceTy, AMDGenericDeviceTy {
27852865
/// Use ROCm 5.7 interface for multiple SDMA engines
27862866
BoolEnvar OMPX_UseMultipleSdmaEngines;
27872867

2868+
/// Value of OMPX_APU_MAPS env var used to force
2869+
/// automatic zero-copy behavior on non-APU GPUs.
2870+
BoolEnvar OMPX_ApuMaps;
2871+
27882872
/// Stream manager for AMDGPU streams.
27892873
AMDGPUStreamManagerTy AMDGPUStreamManager;
27902874

@@ -2815,6 +2899,13 @@ struct AMDGPUDeviceTy : public GenericDeviceTy, AMDGenericDeviceTy {
28152899
/// The current size of the stack that will be used in cases where it could
28162900
/// not be statically determined.
28172901
uint64_t StackSize = 16 * 1024 /* 16 KB */;
2902+
2903+
/// Is the plugin associated with an APU?
2904+
bool IsAPU = false;
2905+
2906+
/// True is the system is configured with XNACK-Enabled.
2907+
/// False otherwise.
2908+
bool IsXnackEnabled = false;
28182909
};
28192910

28202911
Error AMDGPUDeviceImageTy::loadExecutable(const AMDGPUDeviceTy &Device) {
@@ -3059,30 +3150,13 @@ struct AMDGPUPluginTy final : public GenericPluginTy {
30593150
std::optional<StringRef> Processor = ElfOrErr->tryGetCPUName();
30603151

30613152
for (hsa_agent_t Agent : KernelAgents) {
3062-
std::string Target;
3063-
auto Err = utils::iterateAgentISAs(Agent, [&](hsa_isa_t ISA) {
3064-
uint32_t Length;
3065-
hsa_status_t Status;
3066-
Status = hsa_isa_get_info_alt(ISA, HSA_ISA_INFO_NAME_LENGTH, &Length);
3067-
if (Status != HSA_STATUS_SUCCESS)
3068-
return Status;
3069-
3070-
llvm::SmallVector<char> ISAName(Length);
3071-
Status = hsa_isa_get_info_alt(ISA, HSA_ISA_INFO_NAME, ISAName.begin());
3072-
if (Status != HSA_STATUS_SUCCESS)
3073-
return Status;
3074-
3075-
llvm::StringRef TripleTarget(ISAName.begin(), Length);
3076-
if (TripleTarget.consume_front("amdgcn-amd-amdhsa"))
3077-
Target = TripleTarget.ltrim('-').rtrim('\0').str();
3078-
return HSA_STATUS_SUCCESS;
3079-
});
3080-
if (Err)
3081-
return std::move(Err);
3082-
3153+
auto TargeTripleAndFeaturesOrError =
3154+
utils::getTargetTripleAndFeatures(Agent);
3155+
if (!TargeTripleAndFeaturesOrError)
3156+
return TargeTripleAndFeaturesOrError.takeError();
30833157
if (!utils::isImageCompatibleWithEnv(Processor ? *Processor : "",
30843158
ElfOrErr->getPlatformFlags(),
3085-
Target))
3159+
*TargeTripleAndFeaturesOrError))
30863160
return false;
30873161
}
30883162
return true;

openmp/libomptarget/plugins-nextgen/common/include/PluginInterface.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -883,6 +883,11 @@ struct GenericDeviceTy : public DeviceAllocatorTy {
883883

884884
virtual Error getDeviceStackSize(uint64_t &V) = 0;
885885

886+
/// Returns true if current plugin architecture is an APU
887+
/// and unified_shared_memory was not requested by the program.
888+
bool useAutoZeroCopy();
889+
virtual bool useAutoZeroCopyImpl() { return false; }
890+
886891
private:
887892
/// Register offload entry for global variable.
888893
Error registerGlobalOffloadEntry(DeviceImageTy &DeviceImage,

openmp/libomptarget/plugins-nextgen/common/src/PluginInterface.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1555,6 +1555,8 @@ Error GenericDeviceTy::syncEvent(void *EventPtr) {
15551555
return syncEventImpl(EventPtr);
15561556
}
15571557

1558+
bool GenericDeviceTy::useAutoZeroCopy() { return useAutoZeroCopyImpl(); }
1559+
15581560
Error GenericPluginTy::init() {
15591561
auto NumDevicesOrErr = initImpl();
15601562
if (!NumDevicesOrErr)
@@ -2067,6 +2069,14 @@ int32_t __tgt_rtl_set_device_offset(int32_t DeviceIdOffset) {
20672069
return OFFLOAD_SUCCESS;
20682070
}
20692071

2072+
int32_t __tgt_rtl_use_auto_zero_copy(int32_t DeviceId) {
2073+
// Automatic zero-copy only applies to programs that did
2074+
// not request unified_shared_memory and are deployed on an
2075+
// APU with XNACK enabled.
2076+
if (Plugin::get().getRequiresFlags() & OMP_REQ_UNIFIED_SHARED_MEMORY)
2077+
return false;
2078+
return Plugin::get().getDevice(DeviceId).useAutoZeroCopy();
2079+
}
20702080
#ifdef __cplusplus
20712081
}
20722082
#endif

openmp/libomptarget/src/OpenMP/Mapping.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,15 +252,21 @@ TargetPointerResultTy MappingInfoTy::getTargetPointer(
252252
MESSAGE("device mapping required by 'present' map type modifier does not "
253253
"exist for host address " DPxMOD " (%" PRId64 " bytes)",
254254
DPxPTR(HstPtrBegin), Size);
255-
} else if (PM->getRequirements() & OMP_REQ_UNIFIED_SHARED_MEMORY &&
256-
!HasCloseModifier) {
255+
} else if ((PM->getRequirements() & OMP_REQ_UNIFIED_SHARED_MEMORY &&
256+
!HasCloseModifier) ||
257+
(PM->getRequirements() & OMPX_REQ_AUTO_ZERO_COPY)) {
258+
257259
// If unified shared memory is active, implicitly mapped variables that are
258260
// not privatized use host address. Any explicitly mapped variables also use
259261
// host address where correctness is not impeded. In all other cases maps
260262
// are respected.
261263
// In addition to the mapping rules above, the close map modifier forces the
262264
// mapping of the variable to the device.
263265
if (Size) {
266+
INFO(OMP_INFOTYPE_MAPPING_CHANGED, Device.DeviceID,
267+
"Return HstPtrBegin " DPxMOD " Size=%" PRId64 " for unified shared "
268+
"memory\n",
269+
DPxPTR((uintptr_t)HstPtrBegin), Size);
264270
DP("Return HstPtrBegin " DPxMOD " Size=%" PRId64 " for unified shared "
265271
"memory\n",
266272
DPxPTR((uintptr_t)HstPtrBegin), Size);
@@ -415,7 +421,8 @@ TargetPointerResultTy MappingInfoTy::getTgtPtrBegin(
415421
LR.TPR.getEntry()->dynRefCountToStr().c_str(), DynRefCountAction,
416422
LR.TPR.getEntry()->holdRefCountToStr().c_str(), HoldRefCountAction);
417423
LR.TPR.TargetPointer = (void *)TP;
418-
} else if (PM->getRequirements() & OMP_REQ_UNIFIED_SHARED_MEMORY) {
424+
} else if (PM->getRequirements() & OMP_REQ_UNIFIED_SHARED_MEMORY ||
425+
PM->getRequirements() & OMPX_REQ_AUTO_ZERO_COPY) {
419426
// If the value isn't found in the mapping and unified shared memory
420427
// is on then it means we have stumbled upon a value which we need to
421428
// use directly from the host.

openmp/libomptarget/src/PluginManager.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,19 +144,30 @@ void PluginAdaptorTy::initDevices(PluginManager &PM) {
144144

145145
int32_t NumPD = getNumberOfPluginDevices();
146146
ExclusiveDevicesAccessor->reserve(DeviceOffset + NumPD);
147+
// Auto zero-copy is a per-device property. We need to ensure
148+
// that all devices are suggesting to use it.
149+
bool UseAutoZeroCopy = !(NumPD == 0);
147150
for (int32_t PDevI = 0, UserDevId = DeviceOffset; PDevI < NumPD; PDevI++) {
148151
auto Device = std::make_unique<DeviceTy>(this, UserDevId, PDevI);
149152
if (auto Err = Device->init()) {
150153
DP("Skip plugin known device %d: %s\n", PDevI,
151154
toString(std::move(Err)).c_str());
152155
continue;
153156
}
157+
UseAutoZeroCopy = UseAutoZeroCopy && Device->useAutoZeroCopy();
154158

155159
ExclusiveDevicesAccessor->push_back(std::move(Device));
156160
++NumberOfUserDevices;
157161
++UserDevId;
158162
}
159163

164+
// Auto Zero-Copy can only be currently triggered when the system is an
165+
// homogeneous APU architecture without attached discrete GPUs.
166+
// If all devices suggest to use it, change requirment flags to trigger
167+
// zero-copy behavior when mapping memory.
168+
if (UseAutoZeroCopy)
169+
PM.addRequirements(OMPX_REQ_AUTO_ZERO_COPY);
170+
160171
DP("Plugin adaptor " DPxMOD " has index %d, exposes %d out of %d devices!\n",
161172
DPxPTR(LibraryHandler.get()), DeviceOffset, NumberOfUserDevices,
162173
NumberOfPluginDevices);

openmp/libomptarget/src/device.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,3 +339,9 @@ void DeviceTy::dumpOffloadEntries() {
339339
fprintf(stderr, " %11s: %s\n", Kind, It.second.getNameAsCStr());
340340
}
341341
}
342+
343+
bool DeviceTy::useAutoZeroCopy() {
344+
if (RTL->use_auto_zero_copy)
345+
return RTL->use_auto_zero_copy(RTLDeviceID);
346+
return false;
347+
}

0 commit comments

Comments
 (0)