1 //===----------- rtl.cpp - Target independent OpenMP target RTL -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Functionality for handling RTL plugins. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "rtl.h" 14 #include "device.h" 15 #include "private.h" 16 17 #include <cassert> 18 #include <cstdlib> 19 #include <cstring> 20 #include <dlfcn.h> 21 #include <mutex> 22 #include <string> 23 24 // List of all plugins that can support offloading. 25 static const char *RTLNames[] = { 26 /* PowerPC target */ "libomptarget.rtl.ppc64.so", 27 /* x86_64 target */ "libomptarget.rtl.x86_64.so", 28 /* CUDA target */ "libomptarget.rtl.cuda.so", 29 /* AArch64 target */ "libomptarget.rtl.aarch64.so", 30 /* SX-Aurora VE target */ "libomptarget.rtl.ve.so", 31 /* AMDGPU target */ "libomptarget.rtl.amdgpu.so", 32 /* Remote target */ "libomptarget.rtl.rpc.so", 33 }; 34 35 PluginManager *PM; 36 37 #if OMPTARGET_PROFILE_ENABLED 38 static char *ProfileTraceFile = nullptr; 39 #endif 40 41 __attribute__((constructor(101))) void init() { 42 DP("Init target library!\n"); 43 44 bool UseEventsForAtomicTransfers = true; 45 if (const char *ForceAtomicMap = getenv("LIBOMPTARGET_MAP_FORCE_ATOMIC")) { 46 std::string ForceAtomicMapStr(ForceAtomicMap); 47 if (ForceAtomicMapStr == "false" || ForceAtomicMapStr == "FALSE") 48 UseEventsForAtomicTransfers = false; 49 else if (ForceAtomicMapStr != "true" && ForceAtomicMapStr != "TRUE") 50 fprintf(stderr, 51 "Warning: 'LIBOMPTARGET_MAP_FORCE_ATOMIC' accepts only " 52 "'true'/'TRUE' or 'false'/'FALSE' as options, '%s' ignored\n", 53 ForceAtomicMap); 54 } 55 56 PM = new PluginManager(UseEventsForAtomicTransfers); 57 58 #ifdef OMPTARGET_PROFILE_ENABLED 59 ProfileTraceFile = getenv("LIBOMPTARGET_PROFILE"); 60 // TODO: add a configuration option for time granularity 61 if (ProfileTraceFile) 62 llvm::timeTraceProfilerInitialize(500 /* us */, "libomptarget"); 63 #endif 64 } 65 66 __attribute__((destructor(101))) void deinit() { 67 DP("Deinit target library!\n"); 68 delete PM; 69 70 #ifdef OMPTARGET_PROFILE_ENABLED 71 if (ProfileTraceFile) { 72 // TODO: add env var for file output 73 if (auto E = llvm::timeTraceProfilerWrite(ProfileTraceFile, "-")) 74 fprintf(stderr, "Error writing out the time trace\n"); 75 76 llvm::timeTraceProfilerCleanup(); 77 } 78 #endif 79 } 80 81 void RTLsTy::LoadRTLs() { 82 // Parse environment variable OMP_TARGET_OFFLOAD (if set) 83 PM->TargetOffloadPolicy = 84 (kmp_target_offload_kind_t)__kmpc_get_target_offload(); 85 if (PM->TargetOffloadPolicy == tgt_disabled) { 86 return; 87 } 88 89 DP("Loading RTLs...\n"); 90 91 // Attempt to open all the plugins and, if they exist, check if the interface 92 // is correct and if they are supporting any devices. 93 for (auto *Name : RTLNames) { 94 DP("Loading library '%s'...\n", Name); 95 void *dynlib_handle = dlopen(Name, RTLD_NOW); 96 97 if (!dynlib_handle) { 98 // Library does not exist or cannot be found. 99 DP("Unable to load library '%s': %s!\n", Name, dlerror()); 100 continue; 101 } 102 103 DP("Successfully loaded library '%s'!\n", Name); 104 105 AllRTLs.emplace_back(); 106 107 // Retrieve the RTL information from the runtime library. 108 RTLInfoTy &R = AllRTLs.back(); 109 110 bool ValidPlugin = true; 111 112 if (!(*((void **)&R.is_valid_binary) = 113 dlsym(dynlib_handle, "__tgt_rtl_is_valid_binary"))) 114 ValidPlugin = false; 115 if (!(*((void **)&R.number_of_devices) = 116 dlsym(dynlib_handle, "__tgt_rtl_number_of_devices"))) 117 ValidPlugin = false; 118 if (!(*((void **)&R.init_device) = 119 dlsym(dynlib_handle, "__tgt_rtl_init_device"))) 120 ValidPlugin = false; 121 if (!(*((void **)&R.load_binary) = 122 dlsym(dynlib_handle, "__tgt_rtl_load_binary"))) 123 ValidPlugin = false; 124 if (!(*((void **)&R.data_alloc) = 125 dlsym(dynlib_handle, "__tgt_rtl_data_alloc"))) 126 ValidPlugin = false; 127 if (!(*((void **)&R.data_submit) = 128 dlsym(dynlib_handle, "__tgt_rtl_data_submit"))) 129 ValidPlugin = false; 130 if (!(*((void **)&R.data_retrieve) = 131 dlsym(dynlib_handle, "__tgt_rtl_data_retrieve"))) 132 ValidPlugin = false; 133 if (!(*((void **)&R.data_delete) = 134 dlsym(dynlib_handle, "__tgt_rtl_data_delete"))) 135 ValidPlugin = false; 136 if (!(*((void **)&R.run_region) = 137 dlsym(dynlib_handle, "__tgt_rtl_run_target_region"))) 138 ValidPlugin = false; 139 if (!(*((void **)&R.run_team_region) = 140 dlsym(dynlib_handle, "__tgt_rtl_run_target_team_region"))) 141 ValidPlugin = false; 142 143 // Invalid plugin 144 if (!ValidPlugin) { 145 DP("Invalid plugin as necessary interface is not found.\n"); 146 AllRTLs.pop_back(); 147 continue; 148 } 149 150 // No devices are supported by this RTL? 151 if (!(R.NumberOfDevices = R.number_of_devices())) { 152 // The RTL is invalid! Will pop the object from the RTLs list. 153 DP("No devices supported in this RTL\n"); 154 AllRTLs.pop_back(); 155 continue; 156 } 157 158 R.LibraryHandler = dynlib_handle; 159 160 #ifdef OMPTARGET_DEBUG 161 R.RTLName = Name; 162 #endif 163 164 DP("Registering RTL %s supporting %d devices!\n", R.RTLName.c_str(), 165 R.NumberOfDevices); 166 167 // Optional functions 168 *((void **)&R.init_requires) = 169 dlsym(dynlib_handle, "__tgt_rtl_init_requires"); 170 *((void **)&R.data_submit_async) = 171 dlsym(dynlib_handle, "__tgt_rtl_data_submit_async"); 172 *((void **)&R.data_retrieve_async) = 173 dlsym(dynlib_handle, "__tgt_rtl_data_retrieve_async"); 174 *((void **)&R.run_region_async) = 175 dlsym(dynlib_handle, "__tgt_rtl_run_target_region_async"); 176 *((void **)&R.run_team_region_async) = 177 dlsym(dynlib_handle, "__tgt_rtl_run_target_team_region_async"); 178 *((void **)&R.synchronize) = dlsym(dynlib_handle, "__tgt_rtl_synchronize"); 179 *((void **)&R.data_exchange) = 180 dlsym(dynlib_handle, "__tgt_rtl_data_exchange"); 181 *((void **)&R.data_exchange_async) = 182 dlsym(dynlib_handle, "__tgt_rtl_data_exchange_async"); 183 *((void **)&R.is_data_exchangable) = 184 dlsym(dynlib_handle, "__tgt_rtl_is_data_exchangable"); 185 *((void **)&R.register_lib) = 186 dlsym(dynlib_handle, "__tgt_rtl_register_lib"); 187 *((void **)&R.unregister_lib) = 188 dlsym(dynlib_handle, "__tgt_rtl_unregister_lib"); 189 *((void **)&R.supports_empty_images) = 190 dlsym(dynlib_handle, "__tgt_rtl_supports_empty_images"); 191 *((void **)&R.set_info_flag) = 192 dlsym(dynlib_handle, "__tgt_rtl_set_info_flag"); 193 *((void **)&R.print_device_info) = 194 dlsym(dynlib_handle, "__tgt_rtl_print_device_info"); 195 *((void **)&R.create_event) = 196 dlsym(dynlib_handle, "__tgt_rtl_create_event"); 197 *((void **)&R.record_event) = 198 dlsym(dynlib_handle, "__tgt_rtl_record_event"); 199 *((void **)&R.wait_event) = dlsym(dynlib_handle, "__tgt_rtl_wait_event"); 200 *((void **)&R.sync_event) = dlsym(dynlib_handle, "__tgt_rtl_sync_event"); 201 *((void **)&R.destroy_event) = 202 dlsym(dynlib_handle, "__tgt_rtl_destroy_event"); 203 } 204 205 DP("RTLs loaded!\n"); 206 207 return; 208 } 209 210 //////////////////////////////////////////////////////////////////////////////// 211 // Functionality for registering libs 212 213 static void RegisterImageIntoTranslationTable(TranslationTable &TT, 214 RTLInfoTy &RTL, 215 __tgt_device_image *image) { 216 217 // same size, as when we increase one, we also increase the other. 218 assert(TT.TargetsTable.size() == TT.TargetsImages.size() && 219 "We should have as many images as we have tables!"); 220 221 // Resize the Targets Table and Images to accommodate the new targets if 222 // required 223 unsigned TargetsTableMinimumSize = RTL.Idx + RTL.NumberOfDevices; 224 225 if (TT.TargetsTable.size() < TargetsTableMinimumSize) { 226 TT.TargetsImages.resize(TargetsTableMinimumSize, 0); 227 TT.TargetsTable.resize(TargetsTableMinimumSize, 0); 228 } 229 230 // Register the image in all devices for this target type. 231 for (int32_t i = 0; i < RTL.NumberOfDevices; ++i) { 232 // If we are changing the image we are also invalidating the target table. 233 if (TT.TargetsImages[RTL.Idx + i] != image) { 234 TT.TargetsImages[RTL.Idx + i] = image; 235 TT.TargetsTable[RTL.Idx + i] = 0; // lazy initialization of target table. 236 } 237 } 238 } 239 240 //////////////////////////////////////////////////////////////////////////////// 241 // Functionality for registering Ctors/Dtors 242 243 static void RegisterGlobalCtorsDtorsForImage(__tgt_bin_desc *desc, 244 __tgt_device_image *img, 245 RTLInfoTy *RTL) { 246 247 for (int32_t i = 0; i < RTL->NumberOfDevices; ++i) { 248 DeviceTy &Device = *PM->Devices[RTL->Idx + i]; 249 Device.PendingGlobalsMtx.lock(); 250 Device.HasPendingGlobals = true; 251 for (__tgt_offload_entry *entry = img->EntriesBegin; 252 entry != img->EntriesEnd; ++entry) { 253 if (entry->flags & OMP_DECLARE_TARGET_CTOR) { 254 DP("Adding ctor " DPxMOD " to the pending list.\n", 255 DPxPTR(entry->addr)); 256 Device.PendingCtorsDtors[desc].PendingCtors.push_back(entry->addr); 257 } else if (entry->flags & OMP_DECLARE_TARGET_DTOR) { 258 // Dtors are pushed in reverse order so they are executed from end 259 // to beginning when unregistering the library! 260 DP("Adding dtor " DPxMOD " to the pending list.\n", 261 DPxPTR(entry->addr)); 262 Device.PendingCtorsDtors[desc].PendingDtors.push_front(entry->addr); 263 } 264 265 if (entry->flags & OMP_DECLARE_TARGET_LINK) { 266 DP("The \"link\" attribute is not yet supported!\n"); 267 } 268 } 269 Device.PendingGlobalsMtx.unlock(); 270 } 271 } 272 273 void RTLsTy::RegisterRequires(int64_t flags) { 274 // TODO: add more elaborate check. 275 // Minimal check: only set requires flags if previous value 276 // is undefined. This ensures that only the first call to this 277 // function will set the requires flags. All subsequent calls 278 // will be checked for compatibility. 279 assert(flags != OMP_REQ_UNDEFINED && 280 "illegal undefined flag for requires directive!"); 281 if (RequiresFlags == OMP_REQ_UNDEFINED) { 282 RequiresFlags = flags; 283 return; 284 } 285 286 // If multiple compilation units are present enforce 287 // consistency across all of them for require clauses: 288 // - reverse_offload 289 // - unified_address 290 // - unified_shared_memory 291 if ((RequiresFlags & OMP_REQ_REVERSE_OFFLOAD) != 292 (flags & OMP_REQ_REVERSE_OFFLOAD)) { 293 FATAL_MESSAGE0( 294 1, "'#pragma omp requires reverse_offload' not used consistently!"); 295 } 296 if ((RequiresFlags & OMP_REQ_UNIFIED_ADDRESS) != 297 (flags & OMP_REQ_UNIFIED_ADDRESS)) { 298 FATAL_MESSAGE0( 299 1, "'#pragma omp requires unified_address' not used consistently!"); 300 } 301 if ((RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) != 302 (flags & OMP_REQ_UNIFIED_SHARED_MEMORY)) { 303 FATAL_MESSAGE0( 304 1, 305 "'#pragma omp requires unified_shared_memory' not used consistently!"); 306 } 307 308 // TODO: insert any other missing checks 309 310 DP("New requires flags %" PRId64 " compatible with existing %" PRId64 "!\n", 311 flags, RequiresFlags); 312 } 313 314 void RTLsTy::initRTLonce(RTLInfoTy &R) { 315 // If this RTL is not already in use, initialize it. 316 if (!R.isUsed && R.NumberOfDevices != 0) { 317 // Initialize the device information for the RTL we are about to use. 318 const size_t Start = PM->Devices.size(); 319 PM->Devices.reserve(Start + R.NumberOfDevices); 320 for (int32_t device_id = 0; device_id < R.NumberOfDevices; device_id++) { 321 PM->Devices.push_back(std::make_unique<DeviceTy>(&R)); 322 // global device ID 323 PM->Devices[Start + device_id]->DeviceID = Start + device_id; 324 // RTL local device ID 325 PM->Devices[Start + device_id]->RTLDeviceID = device_id; 326 } 327 328 // Initialize the index of this RTL and save it in the used RTLs. 329 R.Idx = (UsedRTLs.empty()) 330 ? 0 331 : UsedRTLs.back()->Idx + UsedRTLs.back()->NumberOfDevices; 332 assert((size_t)R.Idx == Start && 333 "RTL index should equal the number of devices used so far."); 334 R.isUsed = true; 335 UsedRTLs.push_back(&R); 336 337 DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx); 338 } 339 } 340 341 void RTLsTy::initAllRTLs() { 342 for (auto &R : AllRTLs) 343 initRTLonce(R); 344 } 345 346 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) { 347 PM->RTLsMtx.lock(); 348 // Register the images with the RTLs that understand them, if any. 349 for (int32_t i = 0; i < desc->NumDeviceImages; ++i) { 350 // Obtain the image. 351 __tgt_device_image *img = &desc->DeviceImages[i]; 352 353 RTLInfoTy *FoundRTL = nullptr; 354 355 // Scan the RTLs that have associated images until we find one that supports 356 // the current image. 357 for (auto &R : AllRTLs) { 358 if (!R.is_valid_binary(img)) { 359 DP("Image " DPxMOD " is NOT compatible with RTL %s!\n", 360 DPxPTR(img->ImageStart), R.RTLName.c_str()); 361 continue; 362 } 363 364 DP("Image " DPxMOD " is compatible with RTL %s!\n", 365 DPxPTR(img->ImageStart), R.RTLName.c_str()); 366 367 initRTLonce(R); 368 369 // Initialize (if necessary) translation table for this library. 370 PM->TrlTblMtx.lock(); 371 if (!PM->HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)) { 372 PM->HostEntriesBeginRegistrationOrder.push_back(desc->HostEntriesBegin); 373 TranslationTable &TransTable = 374 (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin]; 375 TransTable.HostTable.EntriesBegin = desc->HostEntriesBegin; 376 TransTable.HostTable.EntriesEnd = desc->HostEntriesEnd; 377 } 378 379 // Retrieve translation table for this library. 380 TranslationTable &TransTable = 381 (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin]; 382 383 DP("Registering image " DPxMOD " with RTL %s!\n", DPxPTR(img->ImageStart), 384 R.RTLName.c_str()); 385 RegisterImageIntoTranslationTable(TransTable, R, img); 386 PM->TrlTblMtx.unlock(); 387 FoundRTL = &R; 388 389 // Load ctors/dtors for static objects 390 RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL); 391 392 // if an RTL was found we are done - proceed to register the next image 393 break; 394 } 395 396 if (!FoundRTL) { 397 DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart)); 398 } 399 } 400 PM->RTLsMtx.unlock(); 401 402 DP("Done registering entries!\n"); 403 } 404 405 void RTLsTy::UnregisterLib(__tgt_bin_desc *desc) { 406 DP("Unloading target library!\n"); 407 408 PM->RTLsMtx.lock(); 409 // Find which RTL understands each image, if any. 410 for (int32_t i = 0; i < desc->NumDeviceImages; ++i) { 411 // Obtain the image. 412 __tgt_device_image *img = &desc->DeviceImages[i]; 413 414 RTLInfoTy *FoundRTL = NULL; 415 416 // Scan the RTLs that have associated images until we find one that supports 417 // the current image. We only need to scan RTLs that are already being used. 418 for (auto *R : UsedRTLs) { 419 420 assert(R->isUsed && "Expecting used RTLs."); 421 422 if (!R->is_valid_binary(img)) { 423 DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n", 424 DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler)); 425 continue; 426 } 427 428 DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n", 429 DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler)); 430 431 FoundRTL = R; 432 433 // Execute dtors for static objects if the device has been used, i.e. 434 // if its PendingCtors list has been emptied. 435 for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) { 436 DeviceTy &Device = *PM->Devices[FoundRTL->Idx + i]; 437 Device.PendingGlobalsMtx.lock(); 438 if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) { 439 AsyncInfoTy AsyncInfo(Device); 440 for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) { 441 int rc = target(nullptr, Device, dtor, 0, nullptr, nullptr, nullptr, 442 nullptr, nullptr, nullptr, 1, 1, true /*team*/, 443 AsyncInfo); 444 if (rc != OFFLOAD_SUCCESS) { 445 DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor)); 446 } 447 } 448 // Remove this library's entry from PendingCtorsDtors 449 Device.PendingCtorsDtors.erase(desc); 450 // All constructors have been issued, wait for them now. 451 if (AsyncInfo.synchronize() != OFFLOAD_SUCCESS) 452 DP("Failed synchronizing destructors kernels.\n"); 453 } 454 Device.PendingGlobalsMtx.unlock(); 455 } 456 457 DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n", 458 DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler)); 459 460 break; 461 } 462 463 // if no RTL was found proceed to unregister the next image 464 if (!FoundRTL) { 465 DP("No RTLs in use support the image " DPxMOD "!\n", 466 DPxPTR(img->ImageStart)); 467 } 468 } 469 PM->RTLsMtx.unlock(); 470 DP("Done unregistering images!\n"); 471 472 // Remove entries from PM->HostPtrToTableMap 473 PM->TblMapMtx.lock(); 474 for (__tgt_offload_entry *cur = desc->HostEntriesBegin; 475 cur < desc->HostEntriesEnd; ++cur) { 476 PM->HostPtrToTableMap.erase(cur->addr); 477 } 478 479 // Remove translation table for this descriptor. 480 auto TransTable = 481 PM->HostEntriesBeginToTransTable.find(desc->HostEntriesBegin); 482 if (TransTable != PM->HostEntriesBeginToTransTable.end()) { 483 DP("Removing translation table for descriptor " DPxMOD "\n", 484 DPxPTR(desc->HostEntriesBegin)); 485 PM->HostEntriesBeginToTransTable.erase(TransTable); 486 } else { 487 DP("Translation table for descriptor " DPxMOD " cannot be found, probably " 488 "it has been already removed.\n", 489 DPxPTR(desc->HostEntriesBegin)); 490 } 491 492 PM->TblMapMtx.unlock(); 493 494 // TODO: Remove RTL and the devices it manages if it's not used anymore? 495 // TODO: Write some RTL->unload_image(...) function? 496 497 DP("Done unregistering library!\n"); 498 } 499