1 #include "petscdevice_interface_internal.hpp" /*I <petscdevice.h> I*/ 2 3 #include <petsc/private/cpp/object_pool.hpp> 4 #include <petsc/private/cpp/utility.hpp> 5 #include <petsc/private/cpp/unordered_map.hpp> 6 7 #include <algorithm> // std::remove_if(), std::find_if() 8 #include <vector> 9 #include <string> 10 #include <sstream> // std::ostringstream 11 12 #if defined(__clang__) 13 #pragma clang diagnostic push 14 #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" 15 #endif 16 17 // ========================================================================================== 18 // PetscEvent 19 // ========================================================================================== 20 21 class PetscEventConstructor : public Petsc::ConstructorInterface<_n_PetscEvent, PetscEventConstructor> { 22 public: 23 PetscErrorCode construct_(PetscEvent event) const noexcept 24 { 25 PetscFunctionBegin; 26 PetscCall(PetscArrayzero(event, 1)); 27 PetscCall(underlying().reset(event)); 28 PetscFunctionReturn(PETSC_SUCCESS); 29 } 30 31 PetscErrorCode destroy_(PetscEvent event) const noexcept 32 { 33 PetscFunctionBegin; 34 PetscCall(underlying().reset(event)); 35 PetscFunctionReturn(PETSC_SUCCESS); 36 } 37 38 static PetscErrorCode reset_(PetscEvent event) noexcept 39 { 40 PetscFunctionBegin; 41 if (auto &destroy = event->destroy) { 42 PetscCall((*destroy)(event)); 43 destroy = nullptr; 44 } 45 PetscAssert(!event->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Event failed to destroy its data member: %p", event->data); 46 event->dctx_id = 0; 47 event->dctx_state = 0; 48 event->dtype = PETSC_DEVICE_DEFAULT(); 49 PetscFunctionReturn(PETSC_SUCCESS); 50 } 51 52 static PetscErrorCode invalidate_(PetscEvent) noexcept { return PETSC_SUCCESS; } 53 }; 54 55 static Petsc::ObjectPool<_n_PetscEvent, PetscEventConstructor> event_pool; 56 57 static PetscErrorCode PetscDeviceContextCreateEvent_Private(PetscDeviceContext dctx, PetscEvent *event) 58 { 59 PetscFunctionBegin; 60 PetscValidDeviceContext(dctx, 1); 61 PetscValidPointer(event, 2); 62 PetscCall(event_pool.allocate(event)); 63 PetscCall(PetscDeviceContextGetDeviceType(dctx, &(*event)->dtype)); 64 PetscTryTypeMethod(dctx, createevent, *event); 65 PetscFunctionReturn(PETSC_SUCCESS); 66 } 67 68 static PetscErrorCode PetscEventDestroy_Private(PetscEvent *event) 69 { 70 PetscFunctionBegin; 71 PetscValidPointer(event, 1); 72 if (*event) PetscCall(event_pool.deallocate(event)); 73 PetscFunctionReturn(PETSC_SUCCESS); 74 } 75 76 static PetscErrorCode PetscDeviceContextRecordEvent_Private(PetscDeviceContext dctx, PetscEvent event) 77 { 78 PetscObjectId id; 79 PetscObjectState state; 80 81 PetscFunctionBegin; 82 PetscValidDeviceContext(dctx, 1); 83 PetscValidPointer(event, 2); 84 id = PetscObjectCast(dctx)->id; 85 state = PetscObjectCast(dctx)->state; 86 // technically state can never be less than event->dctx_state (only equal) but we include 87 // it in the check just in case 88 if ((id == event->dctx_id) && (state <= event->dctx_state)) PetscFunctionReturn(PETSC_SUCCESS); 89 if (dctx->ops->recordevent) { 90 // REVIEW ME: 91 // TODO maybe move this to impls, as they can determine whether they can interoperate with 92 // other device types more readily 93 if (PetscDefined(USE_DEBUG) && (event->dtype != PETSC_DEVICE_HOST)) { 94 PetscDeviceType dtype; 95 96 PetscCall(PetscDeviceContextGetDeviceType(dctx, &dtype)); 97 PetscCheck(event->dtype == dtype, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Event type %s does not match device context type %s", PetscDeviceTypes[event->dtype], PetscDeviceTypes[dtype]); 98 } 99 PetscUseTypeMethod(dctx, recordevent, event); 100 } 101 event->dctx_id = id; 102 event->dctx_state = state; 103 PetscFunctionReturn(PETSC_SUCCESS); 104 } 105 106 static PetscErrorCode PetscDeviceContextWaitForEvent_Private(PetscDeviceContext dctx, PetscEvent event) 107 { 108 PetscFunctionBegin; 109 PetscValidDeviceContext(dctx, 1); 110 PetscValidPointer(event, 2); 111 // empty data implies you cannot wait on this event 112 if (!event->data) PetscFunctionReturn(PETSC_SUCCESS); 113 if (PetscDefined(USE_DEBUG)) { 114 const auto etype = event->dtype; 115 PetscDeviceType dtype; 116 117 PetscCall(PetscDeviceContextGetDeviceType(dctx, &dtype)); 118 PetscCheck(etype == dtype, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Event type %s does not match device context type %s", PetscDeviceTypes[etype], PetscDeviceTypes[dtype]); 119 } 120 if (PetscObjectCast(dctx)->id == event->dctx_id) PetscFunctionReturn(PETSC_SUCCESS); 121 PetscTryTypeMethod(dctx, waitforevent, event); 122 PetscFunctionReturn(PETSC_SUCCESS); 123 } 124 125 // ========================================================================================== 126 // PetscStackFrame 127 // 128 // A helper class that (when debugging is enabled) contains the stack frame from which 129 // PetscDeviceContextMakrIntentFromID(). It is intended to be derived from, since this enables 130 // empty-base-class optimization to kick in when debugging is disabled. 131 // ========================================================================================== 132 133 template <bool use_debug> 134 struct PetscStackFrame; 135 136 template <> 137 struct PetscStackFrame</* use_debug = */ true> { 138 std::string file{}; 139 std::string function{}; 140 int line{}; 141 142 PetscStackFrame() = default; 143 144 PetscStackFrame(const char *file_, const char *func_, int line_) noexcept : file(split_on_petsc_path_(file_)), function(func_), line(line_) { } 145 146 bool operator==(const PetscStackFrame &other) const noexcept { return line == other.line && file == other.file && function == other.function; } 147 148 PETSC_NODISCARD std::string to_string() const noexcept 149 { 150 std::string ret; 151 152 ret = '(' + function + "() at " + file + ':' + std::to_string(line) + ')'; 153 return ret; 154 } 155 156 private: 157 static std::string split_on_petsc_path_(std::string &&in) noexcept 158 { 159 auto pos = in.find("petsc/src"); 160 161 if (pos == std::string::npos) pos = in.find("petsc/include"); 162 if (pos == std::string::npos) pos = 0; 163 return in.substr(pos); 164 } 165 166 friend std::ostream &operator<<(std::ostream &os, const PetscStackFrame &frame) 167 { 168 os << frame.to_string(); 169 return os; 170 } 171 172 friend void swap(PetscStackFrame &lhs, PetscStackFrame &rhs) noexcept 173 { 174 using std::swap; 175 176 swap(lhs.file, rhs.file); 177 swap(lhs.function, rhs.function); 178 swap(lhs.line, rhs.line); 179 } 180 }; 181 182 template <> 183 struct PetscStackFrame</* use_debug = */ false> { 184 template <typename... T> 185 constexpr PetscStackFrame(T &&...) noexcept 186 { 187 } 188 189 constexpr bool operator==(const PetscStackFrame &) const noexcept { return true; } 190 191 PETSC_NODISCARD static std::string to_string() noexcept { return "(unknown)"; } 192 193 friend std::ostream &operator<<(std::ostream &os, const PetscStackFrame &) noexcept 194 { 195 os << "(unknown)"; 196 return os; 197 } 198 }; 199 200 // ========================================================================================== 201 // MarkedObjectMap 202 // 203 // A mapping from a PetscObjectId to a PetscEvent and (if debugging is enabled) a 204 // PetscStackFrame containing the location where PetscDeviceContextMarkIntentFromID was called 205 // ========================================================================================== 206 207 class MarkedObjectMap : public Petsc::RegisterFinalizeable<MarkedObjectMap> { 208 public: 209 // Note we derive from PetscStackFrame so that the empty base class optimization can kick 210 // in. If it were just a member it would still take up storage in optimized builds 211 class snapshot_type : private PetscStackFrame<PetscDefined(USE_DEBUG) && !PetscDefined(HAVE_THREADSAFETY)> { 212 public: 213 using frame_type = PetscStackFrame<PetscDefined(USE_DEBUG) && !PetscDefined(HAVE_THREADSAFETY)>; 214 215 snapshot_type() = default; 216 snapshot_type(PetscDeviceContext, frame_type) noexcept; 217 218 ~snapshot_type() noexcept; 219 220 // movable 221 snapshot_type(snapshot_type &&) noexcept; 222 snapshot_type &operator=(snapshot_type &&) noexcept; 223 224 // not copyable 225 snapshot_type(const snapshot_type &) noexcept = delete; 226 snapshot_type &operator=(const snapshot_type &) noexcept = delete; 227 228 PETSC_NODISCARD PetscEvent event() const noexcept { return event_; } 229 PETSC_NODISCARD const frame_type &frame() const noexcept { return *this; } 230 PETSC_NODISCARD frame_type &frame() noexcept { return *this; } 231 232 PETSC_NODISCARD PetscObjectId dctx_id() const noexcept 233 { 234 PetscFunctionBegin; 235 PetscAssertAbort(event(), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Snapshot %s does not contain an event!", frame().to_string().c_str()); 236 PetscFunctionReturn(event()->dctx_id); 237 } 238 239 PetscErrorCode ensure_event(PetscDeviceContext) noexcept; 240 241 friend void swap(snapshot_type &, snapshot_type &) noexcept; 242 243 private: 244 PetscEvent event_{}; // the state of device context when this snapshot was recorded 245 246 PETSC_NODISCARD static PetscEvent init_event_(PetscDeviceContext) noexcept; 247 }; 248 249 // the "value" each key maps to 250 struct mapped_type { 251 using dependency_type = std::vector<snapshot_type>; 252 253 mapped_type() noexcept = default; 254 255 PetscMemoryAccessMode mode{PETSC_MEMORY_ACCESS_READ}; 256 snapshot_type last_write{}; 257 dependency_type dependencies{}; 258 }; 259 260 using map_type = Petsc::UnorderedMap<PetscObjectId, mapped_type>; 261 262 map_type map; 263 264 private: 265 friend RegisterFinalizeable; 266 267 PetscErrorCode finalize_() noexcept; 268 }; 269 270 // ========================================================================================== 271 // MarkedObjectMap Private API 272 // ========================================================================================== 273 274 inline PetscErrorCode MarkedObjectMap::finalize_() noexcept 275 { 276 PetscFunctionBegin; 277 PetscCall(PetscInfo(nullptr, "Finalizing marked object map\n")); 278 PetscCall(map.clear()); 279 PetscFunctionReturn(PETSC_SUCCESS); 280 } 281 282 // ========================================================================================== 283 // MarkedObjectMap::snapshot_type Private API 284 // ========================================================================================== 285 286 inline PetscEvent MarkedObjectMap::snapshot_type::init_event_(PetscDeviceContext dctx) noexcept 287 { 288 PetscEvent event = nullptr; 289 290 PetscFunctionBegin; 291 PetscCallAbort(PETSC_COMM_SELF, PetscDeviceContextCreateEvent_Private(dctx, &event)); 292 PetscCallAbort(PETSC_COMM_SELF, PetscDeviceContextRecordEvent_Private(dctx, event)); 293 PetscFunctionReturn(event); 294 } 295 296 // ========================================================================================== 297 // MarkedObjectMap::snapshot_type Public API 298 // ========================================================================================== 299 300 MarkedObjectMap::snapshot_type::snapshot_type(PetscDeviceContext dctx, frame_type frame) noexcept : frame_type(std::move(frame)), event_(init_event_(dctx)) { } 301 302 MarkedObjectMap::snapshot_type::~snapshot_type() noexcept 303 { 304 PetscFunctionBegin; 305 PetscCallAbort(PETSC_COMM_SELF, PetscEventDestroy_Private(&event_)); 306 PetscFunctionReturnVoid(); 307 } 308 309 // movable 310 MarkedObjectMap::snapshot_type::snapshot_type(snapshot_type &&other) noexcept : frame_type(std::move(other)), event_(Petsc::util::exchange(other.event_, nullptr)) { } 311 312 MarkedObjectMap::snapshot_type &MarkedObjectMap::snapshot_type::operator=(snapshot_type &&other) noexcept 313 { 314 PetscFunctionBegin; 315 if (this != &other) { 316 frame_type::operator=(std::move(other)); 317 PetscCallAbort(PETSC_COMM_SELF, PetscEventDestroy_Private(&event_)); 318 event_ = Petsc::util::exchange(other.event_, nullptr); 319 } 320 PetscFunctionReturn(*this); 321 } 322 323 PetscErrorCode MarkedObjectMap::snapshot_type::ensure_event(PetscDeviceContext dctx) noexcept 324 { 325 PetscFunctionBegin; 326 if (PetscUnlikely(!event_)) PetscCall(PetscDeviceContextCreateEvent_Private(dctx, &event_)); 327 PetscFunctionReturn(PETSC_SUCCESS); 328 } 329 330 void swap(MarkedObjectMap::snapshot_type &lhs, MarkedObjectMap::snapshot_type &rhs) noexcept 331 { 332 using std::swap; 333 334 swap(lhs.frame(), rhs.frame()); 335 swap(lhs.event_, rhs.event_); 336 } 337 338 // A mapping between PetscObjectId (i.e. some PetscObject) to the list of PetscEvent's encoding 339 // the last time the PetscObject was accessed 340 static MarkedObjectMap marked_object_map; 341 342 // ========================================================================================== 343 // Utility Functions 344 // ========================================================================================== 345 346 PetscErrorCode PetscGetMarkedObjectMap_Internal(std::size_t *nkeys, PetscObjectId **keys, PetscMemoryAccessMode **modes, std::size_t **ndeps, PetscEvent ***dependencies) 347 { 348 std::size_t i = 0; 349 const auto &map = marked_object_map.map; 350 const auto size = *nkeys = map.size(); 351 352 PetscFunctionBegin; 353 PetscCall(PetscMalloc4(size, keys, size, modes, size, ndeps, size, dependencies)); 354 for (auto it_ = map.begin(); it_ != map.end(); ++it_) { 355 auto &it = *it_; 356 std::size_t j = 0; 357 358 (*keys)[i] = it.first; 359 (*modes)[i] = it.second.mode; 360 (*ndeps)[i] = it.second.dependencies.size(); 361 (*dependencies)[i] = nullptr; 362 PetscCall(PetscMalloc1((*ndeps)[i], (*dependencies) + i)); 363 for (auto &&dep : it.second.dependencies) (*dependencies)[i][j++] = dep.event(); 364 ++i; 365 } 366 PetscFunctionReturn(PETSC_SUCCESS); 367 } 368 369 PetscErrorCode PetscRestoreMarkedObjectMap_Internal(std::size_t nkeys, PetscObjectId **keys, PetscMemoryAccessMode **modes, std::size_t **ndeps, PetscEvent ***dependencies) 370 { 371 PetscFunctionBegin; 372 for (std::size_t i = 0; i < nkeys; ++i) PetscCall(PetscFree((*dependencies)[i])); 373 PetscCall(PetscFree4(*keys, *modes, *ndeps, *dependencies)); 374 PetscFunctionReturn(PETSC_SUCCESS); 375 } 376 377 template <typename T> 378 static PetscErrorCode PetscDeviceContextMapIterVisitor(PetscDeviceContext dctx, T &&callback) noexcept 379 { 380 const auto dctx_id = PetscObjectCast(dctx)->id; 381 auto &dctx_deps = CxxDataCast(dctx)->deps; 382 auto &object_map = marked_object_map.map; 383 384 PetscFunctionBegin; 385 for (auto &&dep : dctx_deps) { 386 const auto mapit = object_map.find(dep); 387 388 // Need this check since the final PetscDeviceContext may run through this *after* the map 389 // has been finalized (and cleared), and hence might fail to find its dependencies. This is 390 // perfectly valid since the user no longer cares about dangling dependencies after PETSc 391 // is finalized 392 if (PetscLikely(mapit != object_map.end())) { 393 auto &deps = mapit->second.dependencies; 394 const auto end = deps.end(); 395 const auto it = std::remove_if(deps.begin(), end, [&](const MarkedObjectMap::snapshot_type &obj) { return obj.dctx_id() == dctx_id; }); 396 397 PetscCall(callback(mapit, deps.cbegin(), static_cast<decltype(deps.cend())>(it))); 398 // remove ourselves 399 PetscCallCXX(deps.erase(it, end)); 400 // continue to next object, but erase this one if it has no more dependencies 401 if (deps.empty()) PetscCallCXX(object_map.erase(mapit)); 402 } 403 } 404 PetscCallCXX(dctx_deps.clear()); 405 PetscFunctionReturn(PETSC_SUCCESS); 406 } 407 408 PetscErrorCode PetscDeviceContextSyncClearMap_Internal(PetscDeviceContext dctx) 409 { 410 using map_iterator = MarkedObjectMap::map_type::const_iterator; 411 using dep_iterator = MarkedObjectMap::mapped_type::dependency_type::const_iterator; 412 413 PetscFunctionBegin; 414 PetscCall(PetscDeviceContextMapIterVisitor(dctx, [&](map_iterator mapit, dep_iterator it, dep_iterator end) { 415 PetscFunctionBegin; 416 if (PetscDefined(USE_DEBUG_AND_INFO)) { 417 std::ostringstream oss; 418 const auto mode = PetscMemoryAccessModeToString(mapit->second.mode); 419 420 oss << "synced dctx " << PetscObjectCast(dctx)->id << ", remaining leaves for obj " << mapit->first << ": {"; 421 while (it != end) { 422 oss << "[dctx " << it->dctx_id() << ", " << mode << ' ' << it->frame() << ']'; 423 if (++it != end) oss << ", "; 424 } 425 oss << '}'; 426 PetscCall(PetscInfo(nullptr, "%s\n", oss.str().c_str())); 427 } 428 PetscFunctionReturn(PETSC_SUCCESS); 429 })); 430 { 431 // the recursive sync clear map call is unbounded in case of a dependenct loop so we make a 432 // copy 433 // clang-format off 434 const std::vector<CxxData::upstream_type::value_type> upstream_copy( 435 std::make_move_iterator(CxxDataCast(dctx)->upstream.begin()), 436 std::make_move_iterator(CxxDataCast(dctx)->upstream.end()) 437 ); 438 // clang-format on 439 440 // aftermath, clear our set of parents (to avoid infinite recursion) and mark ourselves as no 441 // longer contained (while the empty graph technically *is* always contained, it is not what 442 // we mean by it) 443 PetscCall(CxxDataCast(dctx)->clear()); 444 //dctx->contained = PETSC_FALSE; 445 for (auto &&upstrm : upstream_copy) { 446 // check that this parent still points to what we originally thought it was 447 PetscCheck(upstrm.second.id == PetscObjectCast(upstrm.first)->id, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Upstream dctx %" PetscInt64_FMT " no longer exists, now has id %" PetscInt64_FMT, upstrm.second.id, PetscObjectCast(upstrm.first)->id); 448 PetscCall(PetscDeviceContextSyncClearMap_Internal(upstrm.first)); 449 } 450 } 451 PetscFunctionReturn(PETSC_SUCCESS); 452 } 453 454 PetscErrorCode PetscDeviceContextCheckNotOrphaned_Internal(PetscDeviceContext dctx) 455 { 456 std::ostringstream oss; 457 //const auto allow = dctx->options.allow_orphans, contained = dctx->contained; 458 const auto allow = true, contained = true; 459 auto wrote_to_oss = false; 460 using map_iterator = MarkedObjectMap::map_type::const_iterator; 461 using dep_iterator = MarkedObjectMap::mapped_type::dependency_type::const_iterator; 462 463 PetscFunctionBegin; 464 PetscCall(PetscDeviceContextMapIterVisitor(dctx, [&](map_iterator mapit, dep_iterator it, dep_iterator end) { 465 PetscFunctionBegin; 466 if (allow || contained) PetscFunctionReturn(PETSC_SUCCESS); 467 wrote_to_oss = true; 468 oss << "- PetscObject (id " << mapit->first << "), intent " << PetscMemoryAccessModeToString(mapit->second.mode) << ' ' << it->frame(); 469 if (std::distance(it, end) == 0) oss << " (orphaned)"; // we were the only dependency 470 oss << '\n'; 471 PetscFunctionReturn(PETSC_SUCCESS); 472 })); 473 PetscCheck(!wrote_to_oss, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Destroying PetscDeviceContext ('%s', id %" PetscInt64_FMT ") would leave the following dangling (possibly orphaned) dependants:\n%s\nMust synchronize before destroying it, or allow it to be destroyed with orphans", 474 PetscObjectCast(dctx)->name ? PetscObjectCast(dctx)->name : "unnamed", PetscObjectCast(dctx)->id, oss.str().c_str()); 475 PetscCall(CxxDataCast(dctx)->clear()); 476 PetscFunctionReturn(PETSC_SUCCESS); 477 } 478 479 #define DEBUG_INFO(mess, ...) PetscDebugInfo(dctx, "dctx %" PetscInt64_FMT " (%s) - obj %" PetscInt64_FMT " (%s): " mess, PetscObjectCast(dctx)->id, PetscObjectCast(dctx)->name ? PetscObjectCast(dctx)->name : "unnamed", id, name, ##__VA_ARGS__) 480 481 // The current mode is compatible with the previous mode (i.e. read-read) so we need only 482 // update the existing version and possibly appeand ourselves to the dependency list 483 484 template <bool use_debug> 485 static PetscErrorCode MarkFromID_CompatibleModes(MarkedObjectMap::mapped_type &marked, PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> &frame, const char *PETSC_UNUSED name, bool *update_object_dependencies) 486 { 487 const auto dctx_id = PetscObjectCast(dctx)->id; 488 auto &object_dependencies = marked.dependencies; 489 const auto end = object_dependencies.end(); 490 const auto it = std::find_if(object_dependencies.begin(), end, [&](const MarkedObjectMap::snapshot_type &obj) { return obj.dctx_id() == dctx_id; }); 491 492 PetscFunctionBegin; 493 PetscCall(DEBUG_INFO("new mode (%s) COMPATIBLE with %s mode (%s), no need to serialize\n", PetscMemoryAccessModeToString(mode), object_dependencies.empty() ? "default" : "old", PetscMemoryAccessModeToString(marked.mode))); 494 (void)mode; 495 if (it != end) { 496 using std::swap; 497 498 // we have been here before, all we must do is update our entry then we can bail 499 PetscCall(DEBUG_INFO("found old self as dependency, updating\n")); 500 PetscAssert(CxxDataCast(dctx)->deps.find(id) != CxxDataCast(dctx)->deps.end(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "PetscDeviceContext %" PetscInt64_FMT " listed as dependency for object %" PetscInt64_FMT " (%s), but does not have the object in private dependency list!", dctx_id, id, name); 501 swap(it->frame(), frame); 502 PetscCall(PetscDeviceContextRecordEvent_Private(dctx, it->event())); 503 *update_object_dependencies = false; 504 PetscFunctionReturn(PETSC_SUCCESS); 505 } 506 507 // we have not been here before, need to serialize with the last write event (if it exists) 508 // and add ourselves to the dependency list 509 if (const auto event = marked.last_write.event()) PetscCall(PetscDeviceContextWaitForEvent_Private(dctx, event)); 510 PetscFunctionReturn(PETSC_SUCCESS); 511 } 512 513 template <bool use_debug> 514 static PetscErrorCode MarkFromID_IncompatibleModes_UpdateLastWrite(MarkedObjectMap::mapped_type &marked, PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> &frame, const char *PETSC_UNUSED name, bool *update_object_dependencies) 515 { 516 const auto dctx_id = PetscObjectCast(dctx)->id; 517 auto &last_write = marked.last_write; 518 auto &last_dep = marked.dependencies.back(); 519 PetscDeviceType dtype; 520 521 PetscFunctionBegin; 522 PetscAssert(marked.dependencies.size() == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Can only have a single writer as dependency, have %zu!", marked.dependencies.size()); 523 PetscCall(PetscDeviceContextGetDeviceType(dctx, &dtype)); 524 if (last_dep.event()->dtype != dtype) { 525 PetscCall(DEBUG_INFO("moving last write dependency (intent %s)\n", PetscMemoryAccessModeToString(marked.mode))); 526 last_write = std::move(last_dep); 527 PetscFunctionReturn(PETSC_SUCCESS); 528 } 529 530 // we match the device type of the dependency, we can reuse its event! 531 auto &dctx_upstream_deps = CxxDataCast(dctx)->deps; 532 const auto last_write_was_also_us = last_write.event() && (last_write.dctx_id() == dctx_id); 533 using std::swap; 534 535 PetscCall(DEBUG_INFO("we matched the previous write dependency's (intent %s) device type (%s), swapping last dependency with last write\n", PetscMemoryAccessModeToString(marked.mode), PetscDeviceTypes[dtype])); 536 if (last_dep.event()->dctx_id != dctx_id) dctx_upstream_deps.emplace(id); 537 PetscAssert(dctx_upstream_deps.find(id) != dctx_upstream_deps.end(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Did not find id %" PetscInt64_FMT "in object dependencies, but we have apparently recorded the last dependency %s!", id, 538 last_write.frame().to_string().c_str()); 539 swap(last_write, last_dep); 540 if (last_write_was_also_us) { 541 PetscCall(DEBUG_INFO("we were also the last write event (intent %s), updating\n", PetscMemoryAccessModeToString(mode))); 542 (void)mode; 543 // we are both the last to write *and* the last to leave a write event. This is the 544 // fast path, we only need to update the frame and update the recorded event 545 swap(last_dep.frame(), frame); 546 // last used to be last_write which is not guaranteed to have an event, so must 547 // create it now 548 PetscCall(last_dep.ensure_event(dctx)); 549 PetscCall(PetscDeviceContextRecordEvent_Private(dctx, last_dep.event())); 550 *update_object_dependencies = false; 551 } 552 PetscFunctionReturn(PETSC_SUCCESS); 553 } 554 555 // The current mode is NOT compatible with the previous mode. We must serialize with all events 556 // in the dependency list, possibly clear it, and update the previous write event 557 558 template <bool use_debug> 559 static PetscErrorCode MarkFromID_IncompatibleModes(MarkedObjectMap::mapped_type &marked, PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> &frame, const char *name, bool *update_object_dependencies) 560 { 561 auto &old_mode = marked.mode; 562 auto &object_dependencies = marked.dependencies; 563 564 PetscFunctionBegin; 565 // we are NOT compatible with the previous mode 566 PetscCall(DEBUG_INFO("new mode (%s) NOT COMPATIBLE with %s mode (%s), serializing then clearing (%zu) %s\n", PetscMemoryAccessModeToString(mode), object_dependencies.empty() ? "default" : "old", PetscMemoryAccessModeToString(old_mode), 567 object_dependencies.size(), object_dependencies.size() == 1 ? "dependency" : "dependencies")); 568 569 for (const auto &dep : object_dependencies) PetscCall(PetscDeviceContextWaitForEvent_Private(dctx, dep.event())); 570 // if the previous mode wrote, update the last write node with it 571 if (PetscMemoryAccessWrite(old_mode)) PetscCall(MarkFromID_IncompatibleModes_UpdateLastWrite(marked, dctx, id, mode, frame, name, update_object_dependencies)); 572 573 old_mode = mode; 574 // clear out the old dependencies if are about to append ourselves 575 if (*update_object_dependencies) object_dependencies.clear(); 576 PetscFunctionReturn(PETSC_SUCCESS); 577 } 578 579 template <bool use_debug> 580 static PetscErrorCode PetscDeviceContextMarkIntentFromID_Private(PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, PetscStackFrame<use_debug> frame, const char *name) 581 { 582 auto &marked = marked_object_map.map[id]; 583 auto &object_dependencies = marked.dependencies; 584 auto update_object_dependencies = true; 585 586 PetscFunctionBegin; 587 if ((marked.mode == PETSC_MEMORY_ACCESS_READ) && (mode == PETSC_MEMORY_ACCESS_READ)) { 588 PetscCall(MarkFromID_CompatibleModes(marked, dctx, id, mode, frame, name, &update_object_dependencies)); 589 } else { 590 PetscCall(MarkFromID_IncompatibleModes(marked, dctx, id, mode, frame, name, &update_object_dependencies)); 591 } 592 if (update_object_dependencies) { 593 // become the new leaf by appending ourselves 594 PetscCall(DEBUG_INFO("%s with intent %s\n", object_dependencies.empty() ? "dependency list is empty, creating new leaf" : "appending to existing leaves", PetscMemoryAccessModeToString(mode))); 595 PetscCallCXX(object_dependencies.emplace_back(dctx, std::move(frame))); 596 PetscCallCXX(CxxDataCast(dctx)->deps.emplace(id)); 597 } 598 PetscFunctionReturn(PETSC_SUCCESS); 599 } 600 601 #undef DEBUG_INFO 602 603 /*@C 604 PetscDeviceContextMarkIntentFromID - Indicate a `PetscDeviceContext`s access intent to the 605 auto-dependency system 606 607 Not Collective 608 609 Input Parameters: 610 + dctx - The `PetscDeviceContext` 611 . id - The `PetscObjectId` to mark 612 . mode - The desired access intent 613 - name - The object name (for debug purposes, ignored in optimized builds) 614 615 Notes: 616 This routine formally informs the dependency system that `dctx` will access the object 617 represented by `id` with `mode` and adds `dctx` to `id`'s list of dependencies (termed 618 "leaves"). 619 620 If the existing set of leaves have an incompatible `PetscMemoryAccessMode` to `mode`, `dctx` 621 will be serialized against them. 622 623 Level: intermediate 624 625 .seealso: `PetscDeviceContextWaitForContext()`, `PetscDeviceContextSynchronize()`, 626 `PetscObjectGetId()`, `PetscMemoryAccessMode` 627 @*/ 628 PetscErrorCode PetscDeviceContextMarkIntentFromID(PetscDeviceContext dctx, PetscObjectId id, PetscMemoryAccessMode mode, const char name[]) 629 { 630 #if PetscDefined(USE_DEBUG) && !PetscDefined(HAVE_THREADSAFETY) 631 const auto index = petscstack.currentsize > 2 ? petscstack.currentsize - 2 : 0; 632 const auto file = petscstack.file[index]; 633 const auto function = petscstack.function[index]; 634 const auto line = petscstack.line[index]; 635 #else 636 constexpr const char *file = nullptr; 637 constexpr const char *function = nullptr; 638 constexpr auto line = 0; 639 #endif 640 641 PetscFunctionBegin; 642 PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx)); 643 if (name) PetscValidCharPointer(name, 4); 644 PetscCall(marked_object_map.register_finalize()); 645 PetscCall(PetscLogEventBegin(DCONTEXT_Mark, dctx, nullptr, nullptr, nullptr)); 646 PetscCall(PetscDeviceContextMarkIntentFromID_Private(dctx, id, mode, MarkedObjectMap::snapshot_type::frame_type{file, function, line}, name ? name : "unknown object")); 647 PetscCall(PetscLogEventEnd(DCONTEXT_Mark, dctx, nullptr, nullptr, nullptr)); 648 PetscFunctionReturn(PETSC_SUCCESS); 649 } 650 651 #if defined(__clang__) 652 #pragma clang diagnostic pop 653 #endif 654