File: ze_lib.cpp

package info (click to toggle)
level-zero 1.26.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,468 kB
  • sloc: cpp: 130,327; ansic: 16,197; python: 9,824; makefile: 4
file content (692 lines) | stat: -rw-r--r-- 29,779 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
 *
 * Copyright (C) 2019-2025 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 * @file ze_lib.cpp
 *
 */
#include "ze_lib.h"
#include "../loader/ze_loader_api.h"
#include "../loader/ze_loader_internal.h"
#include <thread>
#include <future>
#include <stdexcept>

namespace ze_lib
{
    ///////////////////////////////////////////////////////////////////////////////
    context_t *context = nullptr;
    #ifdef L0_STATIC_LOADER_BUILD
    void context_at_exit_destructor()
    {
        if (ze_lib::context) {
            delete ze_lib::context;
            ze_lib::context = nullptr;
        }
    }
    bool delayContextDestruction = false;
    bool loaderTeardownCallbackReceived = false;
    bool loaderTeardownRegistrationEnabled = false;

    /// @brief Callback function to handle loader teardown events.
    ///
    /// This function sets the `loaderTeardownCallbackReceived` flag to true,
    /// indicating that a loader teardown callback has been received.
    /// It is intended to be used as a static callback during the loader's
    /// teardown process.
    void staticLoaderTeardownCallback() {
        loaderTeardownCallbackReceived = true;
    }
    #endif
    /**
     * @brief Removes a teardown callback from the context's callback registry.
     *
     * This function checks if a teardown callback with the specified index exists
     * in the context's teardownCallbacks map. If it exists, the callback is removed.
     *
     * @param index The unique identifier of the teardown callback to remove.
     */
    void applicationTeardownCallback(uint32_t index) {
        std::lock_guard<std::mutex> lock(ze_lib::context->teardownCallbacksMutex);
        if (ze_lib::context->teardownCallbacks.find(index) != ze_lib::context->teardownCallbacks.end()) {
            if (ze_lib::context->debugTraceEnabled) {
                std::string message = "applicationTeardownCallback received for index: " + std::to_string(index);
                ze_lib::context->debug_trace_message(message, "");
            }
            ze_lib::context->teardownCallbacks.erase(index);
        }
    }
    bool destruction = false;

    ///////////////////////////////////////////////////////////////////////////////
    __zedlllocal context_t::context_t()
    {
        debugTraceEnabled = getenv_tobool( "ZE_ENABLE_LOADER_DEBUG_TRACE" );
        memset(&initialzeDdiTable, 0, sizeof(ze_dditable_t));
        memset(&initialzetDdiTable, 0, sizeof(zet_dditable_t));
        memset(&initialzesDdiTable, 0, sizeof(zes_dditable_t));
        memset(&initialzerDdiTable, 0, sizeof(zer_dditable_t));
    };

    ///////////////////////////////////////////////////////////////////////////////
    __zedlllocal context_t::~context_t()
    {
#ifdef L0_STATIC_LOADER_BUILD
        if (loaderTeardownRegistrationEnabled && !loaderTeardownCallbackReceived) {
            loaderTeardownCallback(loaderTeardownCallbackIndex);
        }
        if (loader) {
            FREE_DRIVER_LIBRARY( loader );
        }
#else
        // Given the loader teardown, notify the registered callbacks that the loader is being torn down.
        for (auto &callback : teardownCallbacks) {
            callback.second();
        }
        // Clear the teardown callbacks map once the callbacks have been executed.
        teardownCallbacks.clear();
#endif
        ze_lib::destruction = true;
    };

    //////////////////////////////////////////////////////////////////////////
    __zedlllocal ze_result_t context_t::Init(ze_init_flags_t flags, bool sysmanOnly, ze_init_driver_type_desc_t* desc)
    {
        ze_result_t result;
        ze_api_version_t version = ZE_API_VERSION_CURRENT;
#ifdef L0_STATIC_LOADER_BUILD
        std::string loaderLibraryPath;
        auto loaderLibraryPathEnv = getenv_string("ZEL_LIBRARY_PATH");
        if (!loaderLibraryPathEnv.empty()) {
            loaderLibraryPath = loaderLibraryPathEnv;
        }
#ifdef _WIN32
        else {
            loaderLibraryPath = readLevelZeroLoaderLibraryPath();
        }
#endif
        if (debugTraceEnabled)
            debug_trace_message("Static Loader Using Loader Library Path: ", loaderLibraryPath);
        std::string loaderFullLibraryPath = create_library_path(MAKE_LIBRARY_NAME( "ze_loader", L0_LOADER_VERSION), loaderLibraryPath.c_str());
        loader = LOAD_DRIVER_LIBRARY(loaderFullLibraryPath.c_str());

        if( NULL == loader ) {
            std::string message = "ze_lib Context Init() Loader Library Load Failed with ";
            debug_trace_message(message, to_string(ZE_RESULT_ERROR_UNINITIALIZED));
            return ZE_RESULT_ERROR_UNINITIALIZED;
        }

        typedef ze_result_t (ZE_APICALL *loaderInit_t)();
        auto loaderInit = reinterpret_cast<loaderInit_t>(
                GET_FUNCTION_PTR(loader, "zeLoaderInit") );
        result = loaderInit();
        if( ZE_RESULT_SUCCESS != result ) {
            std::string message = "ze_lib Context Init() Loader Init Failed with ";
            debug_trace_message(message, to_string(result));
            return result;
        }

        size_t size = 0;
        result = zelLoaderGetVersions(&size, nullptr);
        if (ZE_RESULT_SUCCESS != result) {
            std::string message = "ze_lib Context Init() zelLoaderGetVersions Failed with";
            debug_trace_message(message, to_string(result));
            return result;
        }

        std::vector<zel_component_version_t> versions(size);
        result = zelLoaderGetVersions(&size, versions.data());
        if (ZE_RESULT_SUCCESS != result) {
            std::string message = "ze_lib Context Init() zelLoaderGetVersions Failed to read component versions with ";
            debug_trace_message(message, to_string(result));
            return result;
        }

        ze_api_version_t current_api_version = version;
        const std::string loader_name = "loader";
        for (auto &component : versions) {
            if (loader_name == component.component_name) {
                version = component.spec_version;
                std::string message = "ze_lib Context Init() Static Loader Found Loader Version v" + std::to_string(component.component_lib_version.major) + "." + std::to_string(component.component_lib_version.minor) + "." + std::to_string(component.component_lib_version.patch);
                debug_trace_message(message, "");
                if(component.component_lib_version.major == 1) {
                    if (component.component_lib_version.minor < 18) {
                        std::string message = "ze_lib Context Init() Version Does not support zeInitDrivers";
                        debug_trace_message(message, "");
                    }
                } else {
                    std::string message = "ze_lib Context Init() Loader version is too new, returning ";
                    debug_trace_message(message, to_string(ZE_RESULT_ERROR_UNSUPPORTED_VERSION));
                    return ZE_RESULT_ERROR_UNSUPPORTED_VERSION;
                }
            }
        }

        if (version > current_api_version) {
            version = current_api_version;
            std::string message = "ze_lib Context Init() Static Loader Requesting Loader API Version v" + std::to_string(ZE_MAJOR_VERSION(version)) + "." + std::to_string(ZE_MINOR_VERSION(version));
            debug_trace_message(message, "");
        }

        typedef HMODULE (ZE_APICALL *getTracing_t)();
        auto getTracing = reinterpret_cast<getTracing_t>(
            GET_FUNCTION_PTR(loader, "zeLoaderGetTracingHandle") );
        if (getTracing == nullptr) {
            std::string message = "ze_lib Context Init() zeLoaderGetTracingHandle missing, returning ";
            debug_trace_message(message, to_string(ZE_RESULT_ERROR_UNINITIALIZED));
            return ZE_RESULT_ERROR_UNINITIALIZED;
        }
        tracing_lib = getTracing();
        typedef ze_result_t (ZE_APICALL *zelLoaderZeTracingLayerInit_t)(std::atomic<ze_dditable_t *> &zeDdiTable);
        auto loaderZeTracingLayerInit = reinterpret_cast<zelLoaderZeTracingLayerInit_t>(
                GET_FUNCTION_PTR(loader, "zelLoaderTracingLayerInit") );
        if (loaderZeTracingLayerInit == nullptr) {
            std::string message = "ze_lib Context Init() zelLoaderTracingLayerInit missing, disabling dynamic tracer support ";
            debug_trace_message(message, "");
            this->dynamicTracingSupported = false;
        }
        typedef ze_result_t (ZE_APICALL *zelLoaderZerTracingLayerInit_t)(std::atomic<zer_dditable_t *> &zerDdiTable);
        auto loaderZerTracingLayerInit = reinterpret_cast<zelLoaderZerTracingLayerInit_t>(
                GET_FUNCTION_PTR(loader, "zelLoaderZerTracingLayerInit") );
        if (loaderZerTracingLayerInit == nullptr) {
            std::string message = "ze_lib Context Init() zelLoaderZerTracingLayerInit missing, dynamic tracing support for Zer API's will be unavailable ";
            debug_trace_message(message, "");
        }
        typedef loader::context_t * (ZE_APICALL *zelLoaderGetContext_t)();
        auto loaderGetContext = reinterpret_cast<zelLoaderGetContext_t>(
                GET_FUNCTION_PTR(loader, "zelLoaderGetContext") );
        if (loaderGetContext == nullptr) {
            std::string message = "ze_lib Context Init() zelLoaderGetContext missing";
            debug_trace_message(message, "");
        }

        std::string version_message = "Loader API Version to be requested is v" + std::to_string(ZE_MAJOR_VERSION(version)) + "." + std::to_string(ZE_MINOR_VERSION(version));
        debug_trace_message(version_message, "");
        loaderDriverGet = reinterpret_cast<ze_pfnDriverGet_t>(GET_FUNCTION_PTR(loader, "zeDriverGet"));
#else
        result = zeLoaderInit();
        if( ZE_RESULT_SUCCESS == result ) {
            tracing_lib = zeLoaderGetTracingHandle();
        }

#endif

        if ( ZE_RESULT_SUCCESS == result )
        {
            ze_lib::context->zeDdiTable.exchange(&ze_lib::context->initialzeDdiTable);
            ze_lib::context->zetDdiTable.exchange(&ze_lib::context->initialzetDdiTable);
            ze_lib::context->zesDdiTable.exchange(&ze_lib::context->initialzesDdiTable);
            ze_lib::context->zerDdiTable.exchange(&ze_lib::context->initialzerDdiTable);
        }

        // Given zesInit, then zesDrivers needs to be used as the sysmanInstanceDrivers;
        bool loaderContextAccessAllowed = true;
#ifdef L0_STATIC_LOADER_BUILD
        loaderContextAccessAllowed = false;
        loader::context_t *loaderContext = nullptr;
#else
        loader::context_t *loaderContext = loader::context;
#endif
        if (sysmanOnly && loaderContextAccessAllowed && loaderContext != nullptr) {
            loaderContext->sysmanInstanceDrivers = &loaderContext->zesDrivers;
        }

        // Always call the inits for all the ddi tables before checking which drivers are usable to enable Instrumentation correctly.

        // Init the ZE DDI Tables
        if( ZE_RESULT_SUCCESS == result )
        {
            result = zeDdiTableInit(version);
            if (result != ZE_RESULT_SUCCESS) {
                std::string message = "ze_lib Context Init() zeDdiTableInit failed with ";
                debug_trace_message(message, to_string(result));
            }
        }
        // Init the ZET DDI Tables
        if( ZE_RESULT_SUCCESS == result )
        {
            result = zetDdiTableInit(version);
            if( ZE_RESULT_SUCCESS != result ) {
                std::string message = "ze_lib Context Init() zetDdiTableInit failed with ";
                debug_trace_message(message, to_string(result));
            }
        }
        // Init the ZES DDI Tables
        if( ZE_RESULT_SUCCESS == result )
        {
            result = zesDdiTableInit(version);
            if (result != ZE_RESULT_SUCCESS) {
                std::string message = "ze_lib Context Init() zesDdiTableInit failed with ";
                debug_trace_message(message, to_string(result));
            }
        }
        // Init the ZER DDI Tables
        if (ZE_RESULT_SUCCESS == result)
        {
            result = zerDdiTableInit(version);
            if (result != ZE_RESULT_SUCCESS)
            {
                std::string message = "ze_lib Context Init() zerDdiTableInit failed with ";
                debug_trace_message(message, to_string(result));
            }
        }
        // Init the Tracing API DDI Tables
        if( ZE_RESULT_SUCCESS == result )
        {
            result = zelTracingDdiTableInit(version);
            if (result != ZE_RESULT_SUCCESS) {
                std::string message = "ze_lib Context Init() zelTracingDdiTableInit failed with ";
                debug_trace_message(message, to_string(result));
            }
        }
        // Init the stored ddi tables for the tracing layer
        if( ZE_RESULT_SUCCESS == result )
        {
            #ifdef L0_STATIC_LOADER_BUILD
            if (loaderZeTracingLayerInit) {
                result = loaderZeTracingLayerInit(this->pTracingZeDdiTable);
                if (result == ZE_RESULT_SUCCESS && loaderZerTracingLayerInit) {
                    result = loaderZerTracingLayerInit(this->pTracingZerDdiTable);
                }
            }
            #else
            result = zelLoaderTracingLayerInit(this->pTracingZeDdiTable);
            if (result == ZE_RESULT_SUCCESS) {
                result = zelLoaderZerTracingLayerInit(this->pTracingZerDdiTable);
            }
            #endif
        }
        // End DDI Table Inits

        if( ZE_RESULT_SUCCESS == result )
        {
#ifdef L0_STATIC_LOADER_BUILD
            // Init Dynamic Loader's Lib Context:
            auto initDriversLoader = reinterpret_cast<ze_pfnInitDrivers_t>(
                GET_FUNCTION_PTR(loader, "zeInitDrivers") );
            auto initLoader = reinterpret_cast<ze_pfnInit_t>(
                GET_FUNCTION_PTR(loader, "zeInit") );
            if (initDriversLoader == nullptr && initLoader == nullptr) {
                std::string message = "ze_lib Context Init() zeInitDrivers and zeInit missing, returning ";
                debug_trace_message(message, to_string(ZE_RESULT_ERROR_UNINITIALIZED));
                return ZE_RESULT_ERROR_UNINITIALIZED;
            }
            if (!desc) {
                result = initLoader(flags);
            } else if (initDriversLoader != nullptr) {
                uint32_t pInitDriversCount = 0;
                result = initDriversLoader(&pInitDriversCount, nullptr, desc);
            } else {
                ze_init_flags_t init_flags = flags;
                if (desc) {
                    if(desc->flags & ZE_INIT_DRIVER_TYPE_FLAG_GPU) {
                        init_flags = ZE_INIT_FLAG_GPU_ONLY;
                    } else if(desc->flags & ZE_INIT_DRIVER_TYPE_FLAG_NPU) {
                        init_flags = ZE_INIT_FLAG_VPU_ONLY;
                    } else {
                        init_flags = 0;
                    }
                }
                result = initLoader(init_flags);
            }
            if (result != ZE_RESULT_SUCCESS) {
                std::string message = "ze_lib Context Init() zeInitDrivers or zeInit failed with ";
                debug_trace_message(message, to_string(result));
                return result;
            }
#endif
            isInitialized = true;
        }
        #ifdef L0_STATIC_LOADER_BUILD
        std::call_once(ze_lib::context->initTeardownCallbacksOnce, [this]() {
            if (!delayContextDestruction) {
                std::atexit(context_at_exit_destructor);
            }
            // Get the function pointer for zelRegisterTeardownCallback from the dynamic loader
            typedef ze_result_t (ZE_APICALL *zelRegisterTeardownCallback_t)(
                zel_loader_teardown_callback_t,
                zel_application_teardown_callback_t*,
                uint32_t*);
            auto pfnZelRegisterTeardownCallback = reinterpret_cast<zelRegisterTeardownCallback_t>(
                GET_FUNCTION_PTR(loader, "zelRegisterTeardownCallback"));
            if (pfnZelRegisterTeardownCallback != nullptr) {
                auto register_teardown_result = pfnZelRegisterTeardownCallback(staticLoaderTeardownCallback, &loaderTeardownCallback, &loaderTeardownCallbackIndex);
                if (register_teardown_result != ZE_RESULT_SUCCESS) {
                    std::string message = "ze_lib Context Init() zelRegisterTeardownCallback failed with ";
                    debug_trace_message(message, to_string(register_teardown_result));
                } else {
                    loaderTeardownRegistrationEnabled = true;
                    std::string message = "ze_lib Context Init() zelRegisterTeardownCallback completed for the static loader with ";
                    debug_trace_message(message, to_string(register_teardown_result));
                }
            }
        });
        #endif
        return result;
    }

} // namespace ze_lib

extern "C" {


ze_result_t ZE_APICALL
zelLoaderGetVersions(
   size_t *num_elems,                     //Pointer to num versions to get.
   zel_component_version_t *versions)     //Pointer to array of versions. If set to NULL, num_elems is returned
{
#ifdef L0_STATIC_LOADER_BUILD
    if(nullptr == ze_lib::context->loader)
        return ZE_RESULT_ERROR_UNINITIALIZED;
    typedef ze_result_t (ZE_APICALL *zelLoaderGetVersions_t)(size_t *num_elems, zel_component_version_t *versions);
    auto getVersions = reinterpret_cast<zelLoaderGetVersions_t>(
            GET_FUNCTION_PTR(ze_lib::context->loader, "zelLoaderGetVersionsInternal") );
    return getVersions(num_elems, versions);
#else
    return zelLoaderGetVersionsInternal(num_elems, versions);
#endif
}

ze_result_t ZE_APICALL
zelGetLoaderVersion(
   zel_component_version_t *version)     //Pointer to version structure to be filled with loader version information
{
#ifdef L0_STATIC_LOADER_BUILD
    // zelLoaderGetVersion doesn't require initialization, so we can load the library temporarily if needed
    HMODULE loaderHandle = nullptr;
    bool temporaryLoad = false;

    if(ze_lib::context && ze_lib::context->loader) {
        // Use existing loader
        loaderHandle = ze_lib::context->loader;
    } else {
        // Temporarily load the loader library to get version info
        std::string loaderLibraryPath;
        auto loaderLibraryPathEnv = getenv_string("ZEL_LIBRARY_PATH");
        if (!loaderLibraryPathEnv.empty()) {
            loaderLibraryPath = loaderLibraryPathEnv;
        }
#ifdef _WIN32
        else {
            loaderLibraryPath = readLevelZeroLoaderLibraryPath();
        }
#endif
        std::string loaderFullLibraryPath = create_library_path(MAKE_LIBRARY_NAME( "ze_loader", L0_LOADER_VERSION), loaderLibraryPath.c_str());
        loaderHandle = LOAD_DRIVER_LIBRARY(loaderFullLibraryPath.c_str());
        if (nullptr == loaderHandle) {
            return ZE_RESULT_ERROR_UNINITIALIZED;
        }
        temporaryLoad = true;
    }

    typedef ze_result_t (ZE_APICALL *zelLoaderGetVersion_t)(zel_component_version_t *version);
    auto getVersion = reinterpret_cast<zelLoaderGetVersion_t>(
            GET_FUNCTION_PTR(loaderHandle, "zelLoaderGetVersion") );
    ze_result_t result = getVersion(version);

    // Clean up temporary load
    if (temporaryLoad && loaderHandle) {
        FREE_DRIVER_LIBRARY(loaderHandle);
    }

    return result;
#else
    return zelLoaderGetVersion(version);
#endif
}


ze_result_t ZE_APICALL
zelLoaderTranslateHandle(
   zel_handle_type_t handleType,
   void *handleIn,
   void **handleOut)

{
#ifdef L0_STATIC_LOADER_BUILD
    if(nullptr == ze_lib::context->loader)
        return ZE_RESULT_ERROR_UNINITIALIZED;
    typedef ze_result_t (ZE_APICALL *zelLoaderTranslateHandleInternal_t)(zel_handle_type_t handleType, void *handleIn, void **handleOut);
    auto translateHandle = reinterpret_cast<zelLoaderTranslateHandleInternal_t>(
            GET_FUNCTION_PTR(ze_lib::context->loader, "zelLoaderTranslateHandleInternal") );
    return translateHandle(handleType, handleIn, handleOut);
#else
    return zelLoaderTranslateHandleInternal(handleType, handleIn, handleOut);
#endif
}

ze_result_t ZE_APICALL
zelSetDriverTeardown()
{
    ze_result_t result = ZE_RESULT_SUCCESS;
    if (!ze_lib::destruction) {
        if (ze_lib::context) {
            // Given the driver teardown, notify the registered callbacks that the loader is being torn down.
            for (auto &callback : ze_lib::context->teardownCallbacks) {
                callback.second();
            }
            // Clear the registered callbacks now that they have been called.
            ze_lib::context->teardownCallbacks.clear();
        }

        ze_lib::destruction = true;
    }
    return result;
}

void ZE_APICALL
zelSetDelayLoaderContextTeardown()
{
    #ifdef L0_STATIC_LOADER_BUILD
    if (!ze_lib::delayContextDestruction) {
        ze_lib::delayContextDestruction = true;
    }
    #endif
}

/// @brief Registers a teardown callback function to be invoked during loader teardown.
///
/// This function allows an application to register a callback that will be called when the loader is being torn down.
/// The loader provides a callback function pointer to the application, which the application should call to notify
/// the loader that it is tearing down. The loader will then remove the application's callback from its list of registered callbacks.
///
/// @param[in] application_callback
///     The application's callback function to be called during loader teardown. Must not be nullptr.
/// @param[out] loader_callback
///     Pointer to the loader's callback function. The application should call this function to notify the loader of teardown.
/// @param[out] index
///     Pointer to a uint32_t that will receive the index assigned to the registered callback.
///
/// @return
///     - ZE_RESULT_SUCCESS: The callback was successfully registered.
///     - ZE_RESULT_ERROR_INVALID_ARGUMENT: The application_callback parameter is nullptr.
///     - ZE_RESULT_ERROR_UNINITIALIZED: The loader context is not initialized.
ze_result_t ZE_APICALL
zelRegisterTeardownCallback(
   zel_loader_teardown_callback_t application_callback, // [in] Application's callback function to be called during loader teardown
   zel_application_teardown_callback_t *loader_callback, // [out] Pointer to the loader's callback function
   uint32_t *index // [out] Index assigned to the registered callback
) {
    ze_result_t result = ZE_RESULT_SUCCESS;
    if (nullptr == application_callback) {
        return ZE_RESULT_ERROR_INVALID_ARGUMENT;
    }
    if (!ze_lib::context) {
        return ZE_RESULT_ERROR_UNINITIALIZED;
    }
    {
        std::lock_guard<std::mutex> lock(ze_lib::context->teardownCallbacksMutex);
        // Assign the loader's callback function to the application callback such that the application can notify the loader
        // that it is tearing down. The loader will then remove the application's callback from the list of callbacks.
        *loader_callback = ze_lib::applicationTeardownCallback;
        // Increment the teardown callback count and assign the index to the application callback.
        ze_lib::context->teardownCallbacksCount.fetch_add(1);
        *index = ze_lib::context->teardownCallbacksCount.load();
        ze_lib::context->teardownCallbacks.insert(std::pair<uint32_t, zel_loader_teardown_callback_t>(*index, application_callback));
        if (ze_lib::context->debugTraceEnabled) {
            std::string message = "Registered teardown callback with index: " + std::to_string(*index);
            ze_lib::context->debug_trace_message(message, "");
        }
    }
    return result;
}

/// @brief Checks if the Level Zero loader is currently in the teardown state.
///
/// This function determines whether the loader is in the process of being destroyed or is otherwise
/// unavailable for further API calls. It performs several checks, including:
/// - Whether the loader's destruction flag is set or the context is null.
/// - On Windows with dynamic loading, it checks for loader teardown notifications,
///   registration status, and the stability of the loader by attempting to call `loaderDriverGet`.
/// - If any of these checks indicate the loader is in teardown or unstable, the function returns true.
///
/// @return true if the loader is in teardown or unstable; false otherwise.
bool ZE_APICALL
zelCheckIsLoaderInTearDown() {
    if (ze_lib::destruction || ze_lib::context == nullptr) {
        return true;
    }
    #if defined(L0_STATIC_LOADER_BUILD) && defined(_WIN32)
    static bool loaderIsStable = true;
    if (!loaderIsStable) {
        if (ze_lib::context->debugTraceEnabled) {
            std::string message = "Loader Teardown check failed before, exiting.";
            ze_lib::context->debug_trace_message(message, "");
        }
        return true;
    }
    if (ze_lib::loaderTeardownCallbackReceived) {
        if (ze_lib::context->debugTraceEnabled) {
            std::string message = "Loader Teardown Notification Received, loader in teardown state.";
            ze_lib::context->debug_trace_message(message, "");
        }
        loaderIsStable = false;
        return true;
    }
    if (!ze_lib::loaderTeardownRegistrationEnabled) {
        try {
            if (!ze_lib::context->loaderDriverGet) {
                if (ze_lib::context->debugTraceEnabled) {
                    std::string message = "LoaderDriverGet is a bad pointer. Exiting stability checker.";
                    ze_lib::context->debug_trace_message(message, "");
                }
                loaderIsStable = false;
                return true;
            }

            uint32_t driverCount = 0;
            ze_result_t result = ZE_RESULT_ERROR_UNINITIALIZED;
            result = ze_lib::context->loaderDriverGet(&driverCount, nullptr);
            if (result != ZE_RESULT_SUCCESS || driverCount == 0) {
                if (ze_lib::context->debugTraceEnabled) {
                    std::string message = "Loader stability check failed. Exiting stability checker.";
                    ze_lib::context->debug_trace_message(message, "");
                }
                loaderIsStable = false;
                return true;
            }
        } catch (...) {
            if (ze_lib::context->debugTraceEnabled) {
                std::string message = "Loader stability check failed. Exception occurred.";
                ze_lib::context->debug_trace_message(message, "");
            }
            loaderIsStable = false;
            return true;
        }
    }
    #endif
    return false;
}

void ZE_APICALL
zelLoaderContextTeardown()
{
    #ifdef L0_STATIC_LOADER_BUILD
    if (ze_lib::delayContextDestruction && ze_lib::context) {
        delete ze_lib::context;
        ze_lib::context = nullptr;
    }
    #endif
}

ze_result_t ZE_APICALL
zelEnableTracingLayer()
{
    #ifdef L0_STATIC_LOADER_BUILD
    if(nullptr == ze_lib::context->loader)
        return ZE_RESULT_ERROR_UNINITIALIZED;
    typedef ze_result_t (ZE_APICALL *zelEnableTracingLayerInternal_t)();
    auto enableDynamicTracing = reinterpret_cast<zelEnableTracingLayerInternal_t>(
            GET_FUNCTION_PTR(ze_lib::context->loader, "zelEnableTracingLayer") );
    return enableDynamicTracing();
    #else
    if (ze_lib::context->dynamicTracingSupported == false) {
        return ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;
    }
    if (ze_lib::context->tracingLayerEnableCounter.fetch_add(1) == 0) {
        ze_lib::context->zeDdiTable.exchange(ze_lib::context->pTracingZeDdiTable);
        if (ze_lib::context->pTracingZerDdiTable != nullptr) {
            ze_lib::context->zerDdiTable.exchange(ze_lib::context->pTracingZerDdiTable);
        }
    }
    #endif
    return ZE_RESULT_SUCCESS;
}

ze_result_t ZE_APICALL
zelGetTracingLayerState
(
    bool* enabled // Pointer to bool to receive tracing layer state
)
{
    if (enabled == nullptr) {
        return ZE_RESULT_ERROR_INVALID_NULL_POINTER;
    }
    #ifdef L0_STATIC_LOADER_BUILD
    if(nullptr == ze_lib::context->loader)
        return ZE_RESULT_ERROR_UNINITIALIZED;
    typedef ze_result_t (ZE_APICALL *zelGetTracingLayerStateInternal_t)(bool* enabled);
    auto getDynamicTracingState = reinterpret_cast<zelGetTracingLayerStateInternal_t>(
            GET_FUNCTION_PTR(ze_lib::context->loader, "zelGetTracingLayerState") );
    return getDynamicTracingState(enabled);
    #else
    if (ze_lib::context->dynamicTracingSupported == false) {
        return ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;
    }
    if (loader::context) {
        *enabled = loader::context->tracingLayerEnabled;
    }
    if (!*enabled) {
        *enabled = (ze_lib::context->tracingLayerEnableCounter.load() > 0);
    }
    #endif
    return ZE_RESULT_SUCCESS;
}

ze_result_t ZE_APICALL
zelDisableTracingLayer()
{
    #ifdef L0_STATIC_LOADER_BUILD
    if(nullptr == ze_lib::context->loader)
        return ZE_RESULT_ERROR_UNINITIALIZED;
    typedef ze_result_t (ZE_APICALL *zelDisableTracingLayerInternal_t)();
    auto disableDynamicTracing = reinterpret_cast<zelDisableTracingLayerInternal_t>(
            GET_FUNCTION_PTR(ze_lib::context->loader, "zelDisableTracingLayer") );
    return disableDynamicTracing();
    #else
    if (ze_lib::context->dynamicTracingSupported == false) {
        return ZE_RESULT_ERROR_UNSUPPORTED_FEATURE;
    }
    if (ze_lib::context->tracingLayerEnableCounter.fetch_sub(1) <= 1) {
        ze_lib::context->zeDdiTable.exchange(&ze_lib::context->initialzeDdiTable);
        if (ze_lib::context->pTracingZerDdiTable != nullptr) {
            ze_lib::context->zerDdiTable.exchange(&ze_lib::context->initialzerDdiTable);
        }
    }
    #endif
    return ZE_RESULT_SUCCESS;
}

} //extern "c"