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     *((void **)&R.release_async_info) =
204         dlsym(dynlib_handle, "__tgt_rtl_release_async_info");
205     *((void **)&R.init_async_info) =
206         dlsym(dynlib_handle, "__tgt_rtl_init_async_info");
207     *((void **)&R.init_device_info) =
208         dlsym(dynlib_handle, "__tgt_rtl_init_device_info");
209   }
210 
211   DP("RTLs loaded!\n");
212 
213   return;
214 }
215 
216 ////////////////////////////////////////////////////////////////////////////////
217 // Functionality for registering libs
218 
219 static void RegisterImageIntoTranslationTable(TranslationTable &TT,
220                                               RTLInfoTy &RTL,
221                                               __tgt_device_image *image) {
222 
223   // same size, as when we increase one, we also increase the other.
224   assert(TT.TargetsTable.size() == TT.TargetsImages.size() &&
225          "We should have as many images as we have tables!");
226 
227   // Resize the Targets Table and Images to accommodate the new targets if
228   // required
229   unsigned TargetsTableMinimumSize = RTL.Idx + RTL.NumberOfDevices;
230 
231   if (TT.TargetsTable.size() < TargetsTableMinimumSize) {
232     TT.TargetsImages.resize(TargetsTableMinimumSize, 0);
233     TT.TargetsTable.resize(TargetsTableMinimumSize, 0);
234   }
235 
236   // Register the image in all devices for this target type.
237   for (int32_t i = 0; i < RTL.NumberOfDevices; ++i) {
238     // If we are changing the image we are also invalidating the target table.
239     if (TT.TargetsImages[RTL.Idx + i] != image) {
240       TT.TargetsImages[RTL.Idx + i] = image;
241       TT.TargetsTable[RTL.Idx + i] = 0; // lazy initialization of target table.
242     }
243   }
244 }
245 
246 ////////////////////////////////////////////////////////////////////////////////
247 // Functionality for registering Ctors/Dtors
248 
249 static void RegisterGlobalCtorsDtorsForImage(__tgt_bin_desc *desc,
250                                              __tgt_device_image *img,
251                                              RTLInfoTy *RTL) {
252 
253   for (int32_t i = 0; i < RTL->NumberOfDevices; ++i) {
254     DeviceTy &Device = *PM->Devices[RTL->Idx + i];
255     Device.PendingGlobalsMtx.lock();
256     Device.HasPendingGlobals = true;
257     for (__tgt_offload_entry *entry = img->EntriesBegin;
258          entry != img->EntriesEnd; ++entry) {
259       if (entry->flags & OMP_DECLARE_TARGET_CTOR) {
260         DP("Adding ctor " DPxMOD " to the pending list.\n",
261            DPxPTR(entry->addr));
262         Device.PendingCtorsDtors[desc].PendingCtors.push_back(entry->addr);
263       } else if (entry->flags & OMP_DECLARE_TARGET_DTOR) {
264         // Dtors are pushed in reverse order so they are executed from end
265         // to beginning when unregistering the library!
266         DP("Adding dtor " DPxMOD " to the pending list.\n",
267            DPxPTR(entry->addr));
268         Device.PendingCtorsDtors[desc].PendingDtors.push_front(entry->addr);
269       }
270 
271       if (entry->flags & OMP_DECLARE_TARGET_LINK) {
272         DP("The \"link\" attribute is not yet supported!\n");
273       }
274     }
275     Device.PendingGlobalsMtx.unlock();
276   }
277 }
278 
279 void RTLsTy::RegisterRequires(int64_t flags) {
280   // TODO: add more elaborate check.
281   // Minimal check: only set requires flags if previous value
282   // is undefined. This ensures that only the first call to this
283   // function will set the requires flags. All subsequent calls
284   // will be checked for compatibility.
285   assert(flags != OMP_REQ_UNDEFINED &&
286          "illegal undefined flag for requires directive!");
287   if (RequiresFlags == OMP_REQ_UNDEFINED) {
288     RequiresFlags = flags;
289     return;
290   }
291 
292   // If multiple compilation units are present enforce
293   // consistency across all of them for require clauses:
294   //  - reverse_offload
295   //  - unified_address
296   //  - unified_shared_memory
297   if ((RequiresFlags & OMP_REQ_REVERSE_OFFLOAD) !=
298       (flags & OMP_REQ_REVERSE_OFFLOAD)) {
299     FATAL_MESSAGE0(
300         1, "'#pragma omp requires reverse_offload' not used consistently!");
301   }
302   if ((RequiresFlags & OMP_REQ_UNIFIED_ADDRESS) !=
303       (flags & OMP_REQ_UNIFIED_ADDRESS)) {
304     FATAL_MESSAGE0(
305         1, "'#pragma omp requires unified_address' not used consistently!");
306   }
307   if ((RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) !=
308       (flags & OMP_REQ_UNIFIED_SHARED_MEMORY)) {
309     FATAL_MESSAGE0(
310         1,
311         "'#pragma omp requires unified_shared_memory' not used consistently!");
312   }
313 
314   // TODO: insert any other missing checks
315 
316   DP("New requires flags %" PRId64 " compatible with existing %" PRId64 "!\n",
317      flags, RequiresFlags);
318 }
319 
320 void RTLsTy::initRTLonce(RTLInfoTy &R) {
321   // If this RTL is not already in use, initialize it.
322   if (!R.isUsed && R.NumberOfDevices != 0) {
323     // Initialize the device information for the RTL we are about to use.
324     const size_t Start = PM->Devices.size();
325     PM->Devices.reserve(Start + R.NumberOfDevices);
326     for (int32_t device_id = 0; device_id < R.NumberOfDevices; device_id++) {
327       PM->Devices.push_back(std::make_unique<DeviceTy>(&R));
328       // global device ID
329       PM->Devices[Start + device_id]->DeviceID = Start + device_id;
330       // RTL local device ID
331       PM->Devices[Start + device_id]->RTLDeviceID = device_id;
332     }
333 
334     // Initialize the index of this RTL and save it in the used RTLs.
335     R.Idx = (UsedRTLs.empty())
336                 ? 0
337                 : UsedRTLs.back()->Idx + UsedRTLs.back()->NumberOfDevices;
338     assert((size_t)R.Idx == Start &&
339            "RTL index should equal the number of devices used so far.");
340     R.isUsed = true;
341     UsedRTLs.push_back(&R);
342 
343     DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx);
344   }
345 }
346 
347 void RTLsTy::initAllRTLs() {
348   for (auto &R : AllRTLs)
349     initRTLonce(R);
350 }
351 
352 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
353   PM->RTLsMtx.lock();
354   // Register the images with the RTLs that understand them, if any.
355   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
356     // Obtain the image.
357     __tgt_device_image *img = &desc->DeviceImages[i];
358 
359     RTLInfoTy *FoundRTL = nullptr;
360 
361     // Scan the RTLs that have associated images until we find one that supports
362     // the current image.
363     for (auto &R : AllRTLs) {
364       if (!R.is_valid_binary(img)) {
365         DP("Image " DPxMOD " is NOT compatible with RTL %s!\n",
366            DPxPTR(img->ImageStart), R.RTLName.c_str());
367         continue;
368       }
369 
370       DP("Image " DPxMOD " is compatible with RTL %s!\n",
371          DPxPTR(img->ImageStart), R.RTLName.c_str());
372 
373       initRTLonce(R);
374 
375       // Initialize (if necessary) translation table for this library.
376       PM->TrlTblMtx.lock();
377       if (!PM->HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)) {
378         PM->HostEntriesBeginRegistrationOrder.push_back(desc->HostEntriesBegin);
379         TranslationTable &TransTable =
380             (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
381         TransTable.HostTable.EntriesBegin = desc->HostEntriesBegin;
382         TransTable.HostTable.EntriesEnd = desc->HostEntriesEnd;
383       }
384 
385       // Retrieve translation table for this library.
386       TranslationTable &TransTable =
387           (PM->HostEntriesBeginToTransTable)[desc->HostEntriesBegin];
388 
389       DP("Registering image " DPxMOD " with RTL %s!\n", DPxPTR(img->ImageStart),
390          R.RTLName.c_str());
391       RegisterImageIntoTranslationTable(TransTable, R, img);
392       PM->TrlTblMtx.unlock();
393       FoundRTL = &R;
394 
395       // Load ctors/dtors for static objects
396       RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL);
397 
398       // if an RTL was found we are done - proceed to register the next image
399       break;
400     }
401 
402     if (!FoundRTL) {
403       DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart));
404     }
405   }
406   PM->RTLsMtx.unlock();
407 
408   DP("Done registering entries!\n");
409 }
410 
411 void RTLsTy::UnregisterLib(__tgt_bin_desc *desc) {
412   DP("Unloading target library!\n");
413 
414   PM->RTLsMtx.lock();
415   // Find which RTL understands each image, if any.
416   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
417     // Obtain the image.
418     __tgt_device_image *img = &desc->DeviceImages[i];
419 
420     RTLInfoTy *FoundRTL = NULL;
421 
422     // Scan the RTLs that have associated images until we find one that supports
423     // the current image. We only need to scan RTLs that are already being used.
424     for (auto *R : UsedRTLs) {
425 
426       assert(R->isUsed && "Expecting used RTLs.");
427 
428       if (!R->is_valid_binary(img)) {
429         DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n",
430            DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
431         continue;
432       }
433 
434       DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n",
435          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
436 
437       FoundRTL = R;
438 
439       // Execute dtors for static objects if the device has been used, i.e.
440       // if its PendingCtors list has been emptied.
441       for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) {
442         DeviceTy &Device = *PM->Devices[FoundRTL->Idx + i];
443         Device.PendingGlobalsMtx.lock();
444         if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) {
445           AsyncInfoTy AsyncInfo(Device);
446           for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) {
447             int rc = target(nullptr, Device, dtor, 0, nullptr, nullptr, nullptr,
448                             nullptr, nullptr, nullptr, 1, 1, true /*team*/,
449                             AsyncInfo);
450             if (rc != OFFLOAD_SUCCESS) {
451               DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor));
452             }
453           }
454           // Remove this library's entry from PendingCtorsDtors
455           Device.PendingCtorsDtors.erase(desc);
456           // All constructors have been issued, wait for them now.
457           if (AsyncInfo.synchronize() != OFFLOAD_SUCCESS)
458             DP("Failed synchronizing destructors kernels.\n");
459         }
460         Device.PendingGlobalsMtx.unlock();
461       }
462 
463       DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n",
464          DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
465 
466       break;
467     }
468 
469     // if no RTL was found proceed to unregister the next image
470     if (!FoundRTL) {
471       DP("No RTLs in use support the image " DPxMOD "!\n",
472          DPxPTR(img->ImageStart));
473     }
474   }
475   PM->RTLsMtx.unlock();
476   DP("Done unregistering images!\n");
477 
478   // Remove entries from PM->HostPtrToTableMap
479   PM->TblMapMtx.lock();
480   for (__tgt_offload_entry *cur = desc->HostEntriesBegin;
481        cur < desc->HostEntriesEnd; ++cur) {
482     PM->HostPtrToTableMap.erase(cur->addr);
483   }
484 
485   // Remove translation table for this descriptor.
486   auto TransTable =
487       PM->HostEntriesBeginToTransTable.find(desc->HostEntriesBegin);
488   if (TransTable != PM->HostEntriesBeginToTransTable.end()) {
489     DP("Removing translation table for descriptor " DPxMOD "\n",
490        DPxPTR(desc->HostEntriesBegin));
491     PM->HostEntriesBeginToTransTable.erase(TransTable);
492   } else {
493     DP("Translation table for descriptor " DPxMOD " cannot be found, probably "
494        "it has been already removed.\n",
495        DPxPTR(desc->HostEntriesBegin));
496   }
497 
498   PM->TblMapMtx.unlock();
499 
500   // TODO: Remove RTL and the devices it manages if it's not used anymore?
501   // TODO: Write some RTL->unload_image(...) function?
502 
503   DP("Done unregistering library!\n");
504 }
505