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