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