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