1 //===--------- device.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 managing devices that are handled by RTL plugins.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "device.h"
14 #include "private.h"
15 #include "rtl.h"
16 
17 #include <cassert>
18 #include <climits>
19 #include <string>
20 
21 /// Map between Device ID (i.e. openmp device id) and its DeviceTy.
22 DevicesTy Devices;
23 
24 int DeviceTy::associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size) {
25   DataMapMtx.lock();
26 
27   // Check if entry exists
28   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
29   if (search != HostDataToTargetMap.end()) {
30     // Mapping already exists
31     bool isValid = search->HstPtrEnd == (uintptr_t)HstPtrBegin + Size &&
32                    search->TgtPtrBegin == (uintptr_t)TgtPtrBegin;
33     DataMapMtx.unlock();
34     if (isValid) {
35       DP("Attempt to re-associate the same device ptr+offset with the same "
36          "host ptr, nothing to do\n");
37       return OFFLOAD_SUCCESS;
38     } else {
39       DP("Not allowed to re-associate a different device ptr+offset with the "
40          "same host ptr\n");
41       return OFFLOAD_FAIL;
42     }
43   }
44 
45   // Mapping does not exist, allocate it with refCount=INF
46   HostDataToTargetTy newEntry((uintptr_t) HstPtrBegin /*HstPtrBase*/,
47                               (uintptr_t) HstPtrBegin /*HstPtrBegin*/,
48                               (uintptr_t) HstPtrBegin + Size /*HstPtrEnd*/,
49                               (uintptr_t) TgtPtrBegin /*TgtPtrBegin*/,
50                               true /*IsRefCountINF*/);
51 
52   DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", HstEnd="
53       DPxMOD ", TgtBegin=" DPxMOD "\n", DPxPTR(newEntry.HstPtrBase),
54       DPxPTR(newEntry.HstPtrBegin), DPxPTR(newEntry.HstPtrEnd),
55       DPxPTR(newEntry.TgtPtrBegin));
56   HostDataToTargetMap.insert(newEntry);
57 
58   DataMapMtx.unlock();
59 
60   return OFFLOAD_SUCCESS;
61 }
62 
63 int DeviceTy::disassociatePtr(void *HstPtrBegin) {
64   DataMapMtx.lock();
65 
66   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
67   if (search != HostDataToTargetMap.end()) {
68     // Mapping exists
69     if (search->isRefCountInf()) {
70       DP("Association found, removing it\n");
71       HostDataToTargetMap.erase(search);
72       DataMapMtx.unlock();
73       return OFFLOAD_SUCCESS;
74     } else {
75       DP("Trying to disassociate a pointer which was not mapped via "
76          "omp_target_associate_ptr\n");
77     }
78   }
79 
80   // Mapping not found
81   DataMapMtx.unlock();
82   DP("Association not found\n");
83   return OFFLOAD_FAIL;
84 }
85 
86 // Get ref count of map entry containing HstPtrBegin
87 uint64_t DeviceTy::getMapEntryRefCnt(void *HstPtrBegin) {
88   uintptr_t hp = (uintptr_t)HstPtrBegin;
89   uint64_t RefCnt = 0;
90 
91   DataMapMtx.lock();
92   if (!HostDataToTargetMap.empty()) {
93     auto upper = HostDataToTargetMap.upper_bound(hp);
94     if (upper != HostDataToTargetMap.begin()) {
95       upper--;
96       if (hp >= upper->HstPtrBegin && hp < upper->HstPtrEnd) {
97         DP("DeviceTy::getMapEntry: requested entry found\n");
98         RefCnt = upper->getRefCount();
99       }
100     }
101   }
102   DataMapMtx.unlock();
103 
104   if (RefCnt == 0) {
105     DP("DeviceTy::getMapEntry: requested entry not found\n");
106   }
107 
108   return RefCnt;
109 }
110 
111 LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
112   uintptr_t hp = (uintptr_t)HstPtrBegin;
113   LookupResult lr;
114 
115   DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%ld)...\n", DPxPTR(hp),
116       Size);
117 
118   if (HostDataToTargetMap.empty())
119     return lr;
120 
121   auto upper = HostDataToTargetMap.upper_bound(hp);
122   // check the left bin
123   if (upper != HostDataToTargetMap.begin()) {
124     lr.Entry = std::prev(upper);
125     auto &HT = *lr.Entry;
126     // Is it contained?
127     lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
128         (hp+Size) <= HT.HstPtrEnd;
129     // Does it extend beyond the mapped region?
130     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
131   }
132 
133   // check the right bin
134   if (!(lr.Flags.IsContained || lr.Flags.ExtendsAfter) &&
135       upper != HostDataToTargetMap.end()) {
136     lr.Entry = upper;
137     auto &HT = *lr.Entry;
138     // Does it extend into an already mapped region?
139     lr.Flags.ExtendsBefore = hp < HT.HstPtrBegin && (hp+Size) > HT.HstPtrBegin;
140     // Does it extend beyond the mapped region?
141     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp+Size) > HT.HstPtrEnd;
142   }
143 
144   if (lr.Flags.ExtendsBefore) {
145     DP("WARNING: Pointer is not mapped but section extends into already "
146         "mapped data\n");
147   }
148   if (lr.Flags.ExtendsAfter) {
149     DP("WARNING: Pointer is already mapped but section extends beyond mapped "
150         "region\n");
151   }
152 
153   return lr;
154 }
155 
156 // Used by target_data_begin
157 // Return the target pointer begin (where the data will be moved).
158 // Allocate memory if this is the first occurrence of this mapping.
159 // Increment the reference counter.
160 // If NULL is returned, then either data allocation failed or the user tried
161 // to do an illegal mapping.
162 void *DeviceTy::getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase,
163                                  int64_t Size, bool &IsNew, bool &IsHostPtr,
164                                  bool IsImplicit, bool UpdateRefCount,
165                                  bool HasCloseModifier,
166                                  bool HasPresentModifier) {
167   void *rc = NULL;
168   IsHostPtr = false;
169   IsNew = false;
170   DataMapMtx.lock();
171   LookupResult lr = lookupMapping(HstPtrBegin, Size);
172 
173   // Check if the pointer is contained.
174   // If a variable is mapped to the device manually by the user - which would
175   // lead to the IsContained flag to be true - then we must ensure that the
176   // device address is returned even under unified memory conditions.
177   if (lr.Flags.IsContained ||
178       ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && IsImplicit)) {
179     auto &HT = *lr.Entry;
180     IsNew = false;
181 
182     if (UpdateRefCount)
183       HT.incRefCount();
184 
185     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
186     DP("Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
187         "Size=%ld,%s RefCount=%s\n", (IsImplicit ? " (implicit)" : ""),
188         DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
189         (UpdateRefCount ? " updated" : ""),
190         HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str());
191     rc = (void *)tp;
192   } else if ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && !IsImplicit) {
193     // Explicit extension of mapped data - not allowed.
194     DP("Explicit extension of mapping is not allowed.\n");
195   } else if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
196              !HasCloseModifier) {
197     // If unified shared memory is active, implicitly mapped variables that are
198     // not privatized use host address. Any explicitly mapped variables also use
199     // host address where correctness is not impeded. In all other cases maps
200     // are respected.
201     // In addition to the mapping rules above, the close map modifier forces the
202     // mapping of the variable to the device.
203     if (Size) {
204       DP("Return HstPtrBegin " DPxMOD " Size=%ld RefCount=%s\n",
205          DPxPTR((uintptr_t)HstPtrBegin), Size,
206          (UpdateRefCount ? " updated" : ""));
207       IsHostPtr = true;
208       rc = HstPtrBegin;
209     }
210   } else if (HasPresentModifier) {
211     DP("Mapping required by 'present' map type modifier does not exist for "
212        "HstPtrBegin=" DPxMOD ", Size=%ld\n",
213        DPxPTR(HstPtrBegin), Size);
214     MESSAGE("device mapping required by 'present' map type modifier does not "
215             "exist for host address " DPxMOD " (%ld bytes)",
216             DPxPTR(HstPtrBegin), Size);
217   } else if (Size) {
218     // If it is not contained and Size > 0, we should create a new entry for it.
219     IsNew = true;
220     uintptr_t tp = (uintptr_t)RTL->data_alloc(RTLDeviceID, Size, HstPtrBegin);
221     DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", "
222        "HstEnd=" DPxMOD ", TgtBegin=" DPxMOD "\n",
223        DPxPTR(HstPtrBase), DPxPTR(HstPtrBegin),
224        DPxPTR((uintptr_t)HstPtrBegin + Size), DPxPTR(tp));
225     HostDataToTargetMap.emplace(
226         HostDataToTargetTy((uintptr_t)HstPtrBase, (uintptr_t)HstPtrBegin,
227                            (uintptr_t)HstPtrBegin + Size, tp));
228     rc = (void *)tp;
229   }
230 
231   DataMapMtx.unlock();
232   return rc;
233 }
234 
235 // Used by target_data_begin, target_data_end, target_data_update and target.
236 // Return the target pointer begin (where the data will be moved).
237 // Decrement the reference counter if called from target_data_end.
238 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
239     bool UpdateRefCount, bool &IsHostPtr) {
240   void *rc = NULL;
241   IsHostPtr = false;
242   IsLast = false;
243   DataMapMtx.lock();
244   LookupResult lr = lookupMapping(HstPtrBegin, Size);
245 
246   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
247     auto &HT = *lr.Entry;
248     IsLast = HT.getRefCount() == 1;
249 
250     if (!IsLast && UpdateRefCount)
251       HT.decRefCount();
252 
253     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
254     DP("Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
255         "Size=%ld,%s RefCount=%s\n", DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
256         (UpdateRefCount ? " updated" : ""),
257         HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str());
258     rc = (void *)tp;
259   } else if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
260     // If the value isn't found in the mapping and unified shared memory
261     // is on then it means we have stumbled upon a value which we need to
262     // use directly from the host.
263     DP("Get HstPtrBegin " DPxMOD " Size=%ld RefCount=%s\n",
264        DPxPTR((uintptr_t)HstPtrBegin), Size, (UpdateRefCount ? " updated" : ""));
265     IsHostPtr = true;
266     rc = HstPtrBegin;
267   }
268 
269   DataMapMtx.unlock();
270   return rc;
271 }
272 
273 // Return the target pointer begin (where the data will be moved).
274 // Lock-free version called when loading global symbols from the fat binary.
275 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
276   uintptr_t hp = (uintptr_t)HstPtrBegin;
277   LookupResult lr = lookupMapping(HstPtrBegin, Size);
278   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
279     auto &HT = *lr.Entry;
280     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
281     return (void *)tp;
282   }
283 
284   return NULL;
285 }
286 
287 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size, bool ForceDelete,
288                             bool HasCloseModifier) {
289   if (RTLs->RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && !HasCloseModifier)
290     return OFFLOAD_SUCCESS;
291   // Check if the pointer is contained in any sub-nodes.
292   int rc;
293   DataMapMtx.lock();
294   LookupResult lr = lookupMapping(HstPtrBegin, Size);
295   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
296     auto &HT = *lr.Entry;
297     if (ForceDelete)
298       HT.resetRefCount();
299     if (HT.decRefCount() == 0) {
300       DP("Deleting tgt data " DPxMOD " of size %ld\n",
301           DPxPTR(HT.TgtPtrBegin), Size);
302       RTL->data_delete(RTLDeviceID, (void *)HT.TgtPtrBegin);
303       DP("Removing%s mapping with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
304           ", Size=%ld\n", (ForceDelete ? " (forced)" : ""),
305           DPxPTR(HT.HstPtrBegin), DPxPTR(HT.TgtPtrBegin), Size);
306       HostDataToTargetMap.erase(lr.Entry);
307     }
308     rc = OFFLOAD_SUCCESS;
309   } else {
310     DP("Section to delete (hst addr " DPxMOD ") does not exist in the allocated"
311        " memory\n", DPxPTR(HstPtrBegin));
312     rc = OFFLOAD_FAIL;
313   }
314 
315   DataMapMtx.unlock();
316   return rc;
317 }
318 
319 /// Init device, should not be called directly.
320 void DeviceTy::init() {
321   // Make call to init_requires if it exists for this plugin.
322   if (RTL->init_requires)
323     RTL->init_requires(RTLs->RequiresFlags);
324   int32_t rc = RTL->init_device(RTLDeviceID);
325   if (rc == OFFLOAD_SUCCESS) {
326     IsInit = true;
327   }
328 }
329 
330 /// Thread-safe method to initialize the device only once.
331 int32_t DeviceTy::initOnce() {
332   std::call_once(InitFlag, &DeviceTy::init, this);
333 
334   // At this point, if IsInit is true, then either this thread or some other
335   // thread in the past successfully initialized the device, so we can return
336   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
337   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
338   // that some other thread already attempted to execute init() and if IsInit
339   // is still false, return OFFLOAD_FAIL.
340   if (IsInit)
341     return OFFLOAD_SUCCESS;
342   else
343     return OFFLOAD_FAIL;
344 }
345 
346 // Load binary to device.
347 __tgt_target_table *DeviceTy::load_binary(void *Img) {
348   RTL->Mtx.lock();
349   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
350   RTL->Mtx.unlock();
351   return rc;
352 }
353 
354 // Submit data to device
355 int32_t DeviceTy::data_submit(void *TgtPtrBegin, void *HstPtrBegin,
356                               int64_t Size, __tgt_async_info *AsyncInfoPtr) {
357   if (!AsyncInfoPtr || !RTL->data_submit_async || !RTL->synchronize)
358     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
359   else
360     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
361                                   AsyncInfoPtr);
362 }
363 
364 // Retrieve data from device
365 int32_t DeviceTy::data_retrieve(void *HstPtrBegin, void *TgtPtrBegin,
366                                 int64_t Size, __tgt_async_info *AsyncInfoPtr) {
367   if (!AsyncInfoPtr || !RTL->data_retrieve_async || !RTL->synchronize)
368     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
369   else
370     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
371                                     AsyncInfoPtr);
372 }
373 
374 // Copy data from current device to destination device directly
375 int32_t DeviceTy::data_exchange(void *SrcPtr, DeviceTy DstDev, void *DstPtr,
376                                 int64_t Size, __tgt_async_info *AsyncInfoPtr) {
377   if (!AsyncInfoPtr || !RTL->data_exchange_async || !RTL->synchronize) {
378     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
379     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
380                               Size);
381   } else
382     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
383                                     DstPtr, Size, AsyncInfoPtr);
384 }
385 
386 // Run region on device
387 int32_t DeviceTy::run_region(void *TgtEntryPtr, void **TgtVarsPtr,
388                              ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
389                              __tgt_async_info *AsyncInfoPtr) {
390   if (!AsyncInfoPtr || !RTL->run_region || !RTL->synchronize)
391     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
392                            TgtVarsSize);
393   else
394     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
395                                  TgtOffsets, TgtVarsSize, AsyncInfoPtr);
396 }
397 
398 // Run team region on device.
399 int32_t DeviceTy::run_team_region(void *TgtEntryPtr, void **TgtVarsPtr,
400                                   ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
401                                   int32_t NumTeams, int32_t ThreadLimit,
402                                   uint64_t LoopTripCount,
403                                   __tgt_async_info *AsyncInfoPtr) {
404   if (!AsyncInfoPtr || !RTL->run_team_region_async || !RTL->synchronize)
405     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
406                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
407                                 LoopTripCount);
408   else
409     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
410                                       TgtOffsets, TgtVarsSize, NumTeams,
411                                       ThreadLimit, LoopTripCount, AsyncInfoPtr);
412 }
413 
414 // Whether data can be copied to DstDevice directly
415 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
416   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
417     return false;
418 
419   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
420     return (RTL->data_exchange != nullptr) ||
421            (RTL->data_exchange_async != nullptr);
422 
423   return false;
424 }
425 
426 /// Check whether a device has an associated RTL and initialize it if it's not
427 /// already initialized.
428 bool device_is_ready(int device_num) {
429   DP("Checking whether device %d is ready.\n", device_num);
430   // Devices.size() can only change while registering a new
431   // library, so try to acquire the lock of RTLs' mutex.
432   RTLsMtx->lock();
433   size_t Devices_size = Devices.size();
434   RTLsMtx->unlock();
435   if (Devices_size <= (size_t)device_num) {
436     DP("Device ID  %d does not have a matching RTL\n", device_num);
437     return false;
438   }
439 
440   // Get device info
441   DeviceTy &Device = Devices[device_num];
442 
443   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
444        Device.RTLDeviceID, Device.IsInit);
445 
446   // Init the device if not done before
447   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
448     DP("Failed to init device %d\n", device_num);
449     return false;
450   }
451 
452   DP("Device %d is ready to use.\n", device_num);
453 
454   return true;
455 }
456