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