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