From 3ea2afdca523cb90f0799c501f5875a11bfcef5f Mon Sep 17 00:00:00 2001
From: Robert Schmidt <robert.schmidt@openairinterface.org>
Date: Wed, 3 May 2023 16:12:45 +0200
Subject: [PATCH] Fix NSA: lock scheduler before removing UE

---
 openair2/RRC/NR/rrc_gNB_nsa.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/openair2/RRC/NR/rrc_gNB_nsa.c b/openair2/RRC/NR/rrc_gNB_nsa.c
index bf69aa703b..250402a2cf 100644
--- a/openair2/RRC/NR/rrc_gNB_nsa.c
+++ b/openair2/RRC/NR/rrc_gNB_nsa.c
@@ -401,8 +401,11 @@ void rrc_remove_nsa_user(gNB_RRC_INST *rrc, int rnti) {
 
   rrc_rlc_remove_ue(&ctxt);
 
-  // WHAT A RACE CONDITION
+  // lock the scheduler before removing the UE. Note: mac_remove_nr_ue() checks
+  // that the scheduler is actually locked!
+  NR_SCHED_LOCK(&RC.nrmac[rrc->module_id]->sched_lock);
   mac_remove_nr_ue(RC.nrmac[rrc->module_id], rnti);
+  NR_SCHED_UNLOCK(&RC.nrmac[rrc->module_id]->sched_lock);
   gtpv1u_enb_delete_tunnel_req_t tmp={0};
   tmp.rnti=rnti;
   tmp.from_gnb=1;
-- 
2.26.2