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::RegisterRequires(int64_t flags) {
190   // TODO: add more elaborate check.
191   // Minimal check: only set requires flags if previous value
192   // is undefined. This ensures that only the first call to this
193   // function will set the requires flags. All subsequent calls
194   // will be checked for compatibility.
195   assert(flags != OMP_REQ_UNDEFINED &&
196          "illegal undefined flag for requires directive!");
197   if (RequiresFlags == OMP_REQ_UNDEFINED) {
198     RequiresFlags = flags;
199     return;
200   }
201 
202   // If multiple compilation units are present enforce
203   // consistency across all of them for require clauses:
204   //  - reverse_offload
205   //  - unified_address
206   //  - unified_shared_memory
207   if ((RequiresFlags & OMP_REQ_REVERSE_OFFLOAD) !=
208       (flags & OMP_REQ_REVERSE_OFFLOAD)) {
209     FATAL_MESSAGE0(1,
210         "'#pragma omp requires reverse_offload' not used consistently!");
211   }
212   if ((RequiresFlags & OMP_REQ_UNIFIED_ADDRESS) !=
213           (flags & OMP_REQ_UNIFIED_ADDRESS)) {
214     FATAL_MESSAGE0(1,
215         "'#pragma omp requires unified_address' not used consistently!");
216   }
217   if ((RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) !=
218           (flags & OMP_REQ_UNIFIED_SHARED_MEMORY)) {
219     FATAL_MESSAGE0(1,
220         "'#pragma omp requires unified_shared_memory' not used consistently!");
221   }
222 
223   // TODO: insert any other missing checks
224 
225   DP("New requires flags %ld compatible with existing %ld!\n",
226      flags, RequiresFlags);
227 }
228 
229 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
230   // Attempt to load all plugins available in the system.
231   std::call_once(initFlag, &RTLsTy::LoadRTLs, this);
232 
233   RTLsMtx.lock();
234   // Register the images with the RTLs that understand them, if any.
235   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
236     // Obtain the image.
237     __tgt_device_image *img = &desc->DeviceImages[i];
238 
239     RTLInfoTy *FoundRTL = NULL;
240 
241     // Scan the RTLs that have associated images until we find one that supports
242     // the current image.
243     for (auto &R : RTLs.AllRTLs) {
244       if (!R.is_valid_binary(img)) {
245         DP("Image " DPxMOD " is NOT compatible with RTL %s!\n",
246             DPxPTR(img->ImageStart), R.RTLName.c_str());
247         continue;
248       }
249 
250       DP("Image " DPxMOD " is compatible with RTL %s!\n",
251           DPxPTR(img->ImageStart), R.RTLName.c_str());
252 
253       // If this RTL is not already in use, initialize it.
254       if (!R.isUsed) {
255         // Initialize the device information for the RTL we are about to use.
256         DeviceTy device(&R);
257         size_t start = Devices.size();
258         Devices.resize(start + R.NumberOfDevices, device);
259         for (int32_t device_id = 0; device_id < R.NumberOfDevices;
260             device_id++) {
261           // global device ID
262           Devices[start + device_id].DeviceID = start + device_id;
263           // RTL local device ID
264           Devices[start + device_id].RTLDeviceID = device_id;
265           // RTL requires flags
266           Devices[start + device_id].RTLRequiresFlags = RequiresFlags;
267         }
268 
269         // Initialize the index of this RTL and save it in the used RTLs.
270         R.Idx = (RTLs.UsedRTLs.empty())
271                     ? 0
272                     : RTLs.UsedRTLs.back()->Idx +
273                           RTLs.UsedRTLs.back()->NumberOfDevices;
274         assert((size_t) R.Idx == start &&
275             "RTL index should equal the number of devices used so far.");
276         R.isUsed = true;
277         RTLs.UsedRTLs.push_back(&R);
278 
279         DP("RTL " DPxMOD " has index %d!\n", DPxPTR(R.LibraryHandler), R.Idx);
280       }
281 
282       // Initialize (if necessary) translation table for this library.
283       TrlTblMtx.lock();
284       if(!HostEntriesBeginToTransTable.count(desc->HostEntriesBegin)){
285         TranslationTable &tt =
286             HostEntriesBeginToTransTable[desc->HostEntriesBegin];
287         tt.HostTable.EntriesBegin = desc->HostEntriesBegin;
288         tt.HostTable.EntriesEnd = desc->HostEntriesEnd;
289       }
290 
291       // Retrieve translation table for this library.
292       TranslationTable &TransTable =
293           HostEntriesBeginToTransTable[desc->HostEntriesBegin];
294 
295       DP("Registering image " DPxMOD " with RTL %s!\n",
296           DPxPTR(img->ImageStart), R.RTLName.c_str());
297       RegisterImageIntoTranslationTable(TransTable, R, img);
298       TrlTblMtx.unlock();
299       FoundRTL = &R;
300 
301       // Load ctors/dtors for static objects
302       RegisterGlobalCtorsDtorsForImage(desc, img, FoundRTL);
303 
304       // if an RTL was found we are done - proceed to register the next image
305       break;
306     }
307 
308     if (!FoundRTL) {
309       DP("No RTL found for image " DPxMOD "!\n", DPxPTR(img->ImageStart));
310     }
311   }
312   RTLsMtx.unlock();
313 
314 
315   DP("Done registering entries!\n");
316 }
317 
318 void RTLsTy::UnregisterLib(__tgt_bin_desc *desc) {
319   DP("Unloading target library!\n");
320 
321   RTLsMtx.lock();
322   // Find which RTL understands each image, if any.
323   for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
324     // Obtain the image.
325     __tgt_device_image *img = &desc->DeviceImages[i];
326 
327     RTLInfoTy *FoundRTL = NULL;
328 
329     // Scan the RTLs that have associated images until we find one that supports
330     // the current image. We only need to scan RTLs that are already being used.
331     for (auto *R : RTLs.UsedRTLs) {
332 
333       assert(R->isUsed && "Expecting used RTLs.");
334 
335       if (!R->is_valid_binary(img)) {
336         DP("Image " DPxMOD " is NOT compatible with RTL " DPxMOD "!\n",
337             DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
338         continue;
339       }
340 
341       DP("Image " DPxMOD " is compatible with RTL " DPxMOD "!\n",
342           DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
343 
344       FoundRTL = R;
345 
346       // Execute dtors for static objects if the device has been used, i.e.
347       // if its PendingCtors list has been emptied.
348       for (int32_t i = 0; i < FoundRTL->NumberOfDevices; ++i) {
349         DeviceTy &Device = Devices[FoundRTL->Idx + i];
350         Device.PendingGlobalsMtx.lock();
351         if (Device.PendingCtorsDtors[desc].PendingCtors.empty()) {
352           for (auto &dtor : Device.PendingCtorsDtors[desc].PendingDtors) {
353             int rc = target(Device.DeviceID, dtor, 0, NULL, NULL, NULL, NULL, 1,
354                 1, true /*team*/);
355             if (rc != OFFLOAD_SUCCESS) {
356               DP("Running destructor " DPxMOD " failed.\n", DPxPTR(dtor));
357             }
358           }
359           // Remove this library's entry from PendingCtorsDtors
360           Device.PendingCtorsDtors.erase(desc);
361         }
362         Device.PendingGlobalsMtx.unlock();
363       }
364 
365       DP("Unregistered image " DPxMOD " from RTL " DPxMOD "!\n",
366           DPxPTR(img->ImageStart), DPxPTR(R->LibraryHandler));
367 
368       break;
369     }
370 
371     // if no RTL was found proceed to unregister the next image
372     if (!FoundRTL){
373       DP("No RTLs in use support the image " DPxMOD "!\n",
374           DPxPTR(img->ImageStart));
375     }
376   }
377   RTLsMtx.unlock();
378   DP("Done unregistering images!\n");
379 
380   // Remove entries from HostPtrToTableMap
381   TblMapMtx.lock();
382   for (__tgt_offload_entry *cur = desc->HostEntriesBegin;
383       cur < desc->HostEntriesEnd; ++cur) {
384     HostPtrToTableMap.erase(cur->addr);
385   }
386 
387   // Remove translation table for this descriptor.
388   auto tt = HostEntriesBeginToTransTable.find(desc->HostEntriesBegin);
389   if (tt != HostEntriesBeginToTransTable.end()) {
390     DP("Removing translation table for descriptor " DPxMOD "\n",
391         DPxPTR(desc->HostEntriesBegin));
392     HostEntriesBeginToTransTable.erase(tt);
393   } else {
394     DP("Translation table for descriptor " DPxMOD " cannot be found, probably "
395         "it has been already removed.\n", DPxPTR(desc->HostEntriesBegin));
396   }
397 
398   TblMapMtx.unlock();
399 
400   // TODO: Remove RTL and the devices it manages if it's not used anymore?
401   // TODO: Write some RTL->unload_image(...) function?
402 
403   DP("Done unregistering library!\n");
404 }
405