/***************************************************************************
 * Copyright (C) 2026 Eclipse ThreadX contributors
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which is available at
 * https://opensource.org/licenses/MIT.
 *
 * AI Disclosure: This file was largely AI-generated by Codex (gpt 5.4).
 * The AI-generated portions may be considered public domain (CC0-1.0)
 * and not subject to the project's licence. The human contributor has
 * reviewed and verified that the code is correct.
 *
 * SPDX-License-Identifier: MIT and CC0-1.0
 **************************************************************************/

// Some portions generated by Codex (gpt 5.4).

#define TX_SOURCE_CODE
#define TX_THREAD_SMP_SOURCE_CODE

#include "tx_api.h"
#include "tx_thread.h"
#include "tx_timer.h"

void  _tx_thread_smp_unprotect(UINT new_interrupt_posture)
{
UINT    core;
DWORD   current_thread_id;
UINT    critical_section_owned;

    current_thread_id =  GetCurrentThreadId();
    critical_section_owned =  (UINT) (_tx_win32_critical_section.tx_win32_critical_section_owner == current_thread_id);

    if (critical_section_owned == TX_FALSE)
    {
        _tx_win32_critical_section_obtain(&_tx_win32_critical_section);
    }

    core =  _tx_thread_smp_core_get();

    if (_tx_thread_smp_protection.tx_thread_smp_protect_core == core)
    {
        _tx_thread_smp_protection.tx_thread_smp_protect_count--;

        if (_tx_thread_smp_protection.tx_thread_smp_protect_count == 0U)
        {
            _tx_win32_global_int_disabled_flag =  new_interrupt_posture;

            if (_tx_thread_preempt_disable == 0U)
            {
                _tx_thread_smp_protection.tx_thread_smp_protect_in_force =   TX_FALSE;
                _tx_thread_smp_protection.tx_thread_smp_protect_thread =     TX_NULL;
                _tx_thread_smp_protection.tx_thread_smp_protect_core =       0xFFFFFFFFUL;
                _tx_thread_smp_protection.tx_thread_smp_protect_thread_id =  0U;
                _tx_win32_debug_entry_insert("UNPROTECT-keep", __FILE__, __LINE__);
            }
            else
            {
                _tx_win32_debug_entry_insert("UNPROTECT-released", __FILE__, __LINE__);
            }
        }
        else
        {
            _tx_win32_debug_entry_insert("UNPROTECT-nested", __FILE__, __LINE__);
        }

        _tx_win32_critical_section_release(&_tx_win32_critical_section);
    }
    else
    {
        _tx_win32_critical_section_release(&_tx_win32_critical_section);
    }
}
