From 9847089b65beac2a9c360bb652fa2f0770b7c9d5 Mon Sep 17 00:00:00 2001
From: francescomani <email@francescomani.it>
Date: Mon, 18 Dec 2023 14:48:34 +0100
Subject: [PATCH] handle rlf with re-establishment or going to idle

---
 openair2/RRC/NR_UE/rrc_UE.c                   | 21 +++++++++++++++++++
 openair2/RRC/NR_UE/rrc_proto.h                |  1 +
 openair2/RRC/NR_UE/rrc_timers_and_constants.c |  3 +--
 3 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/openair2/RRC/NR_UE/rrc_UE.c b/openair2/RRC/NR_UE/rrc_UE.c
index c8470e0ced..5068fd5683 100644
--- a/openair2/RRC/NR_UE/rrc_UE.c
+++ b/openair2/RRC/NR_UE/rrc_UE.c
@@ -1991,6 +1991,27 @@ static void process_lte_nsa_msg(NR_UE_RRC_INST_t *rrc, nsa_msg_t *msg, int msg_l
     }
 }
 
+void handle_rlf_detection(NR_UE_RRC_INST_t *rrc)
+{
+  // 5.3.10.3 in 38.331
+  rrcPerNB_t *nb = &rrc->perNB[0];
+  bool srb2 = nb->Srb[2] != RB_NOT_PRESENT;
+  bool any_drb = false;
+  for (int i = 0; i < MAX_DRBS_PER_UE; i++) {
+    if (nb->status_DRBs[i] != RB_NOT_PRESENT) {
+      any_drb = true;
+      break;
+    }
+  }
+
+  if (rrc->as_security_activated && srb2 && any_drb) // initiate the connection re-establishment procedure
+    nr_rrc_initiate_rrcReestablishment(rrc, NR_ReestablishmentCause_otherFailure, 0);
+  else {
+    NR_Release_Cause_t cause = rrc->as_security_activated ? RRC_CONNECTION_FAILURE : OTHER;
+    nr_rrc_going_to_IDLE(rrc, cause, NULL);
+  }
+}
+
 void nr_rrc_going_to_IDLE(NR_UE_RRC_INST_t *rrc,
                           NR_Release_Cause_t release_cause,
                           NR_RRCRelease_t *RRCRelease)
diff --git a/openair2/RRC/NR_UE/rrc_proto.h b/openair2/RRC/NR_UE/rrc_proto.h
index 53b3ceec8a..92858391f7 100644
--- a/openair2/RRC/NR_UE/rrc_proto.h
+++ b/openair2/RRC/NR_UE/rrc_proto.h
@@ -97,6 +97,7 @@ void *rrc_nrue_task(void *args_p);
 void *rrc_nrue(void *args_p);
 
 void nr_rrc_handle_timers(NR_UE_RRC_INST_t *rrc);
+void handle_rlf_detection(NR_UE_RRC_INST_t *rrc);
 
 /**\brief RRC NSA UE task.
    \param void *args_p Pointer on arguments to start the task. */
diff --git a/openair2/RRC/NR_UE/rrc_timers_and_constants.c b/openair2/RRC/NR_UE/rrc_timers_and_constants.c
index f21591c96e..91bf81617e 100644
--- a/openair2/RRC/NR_UE/rrc_timers_and_constants.c
+++ b/openair2/RRC/NR_UE/rrc_timers_and_constants.c
@@ -146,10 +146,9 @@ void nr_rrc_handle_timers(NR_UE_RRC_INST_t *rrc)
   bool t310_expired = nr_timer_tick(&timers->T310);
   if(t310_expired) {
     LOG_W(NR_RRC, "Timer T310 expired\n");
-    // TODO
     // handle detection of radio link failure
     // as described in 5.3.10.3 of 38.331
-    AssertFatal(false, "Radio link failure! Not handled yet!\n");
+    handle_rlf_detection(rrc);
   }
 
   bool t311_expired = nr_timer_tick(&timers->T311);
-- 
2.26.2