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