rrc_gNB.c 116 KB
Newer Older
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
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
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this file
 * except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

/*! \file rrc_gNB.c
 * \brief rrc procedures for gNB
 * \author Navid Nikaein and  Raymond Knopp , WEI-TAI CHEN
 * \date 2011 - 2014 , 2018
 * \version 1.0
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
27 28
 * \company Eurecom, NTUST
 * \email: navid.nikaein@eurecom.fr and raymond.knopp@eurecom.fr, kroempa@gmail.com
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
29
 */
30
#define RRC_GNB_C
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
31 32
#define RRC_GNB_C

Laurent THOMAS's avatar
Laurent THOMAS committed
33 34 35 36
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

37
#include "nr_rrc_config.h"
38 39
#include "nr_rrc_defs.h"
#include "nr_rrc_extern.h"
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
40 41
#include "assertions.h"
#include "common/ran_context.h"
42
#include "oai_asn1.h"
43
#include "rrc_gNB_radio_bearers.h"
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
44 45

#include "RRC/L2_INTERFACE/openair_rrc_L2_interface.h"
46
#include "LAYER2/NR_MAC_gNB/mac_proto.h"
Raymond Knopp's avatar
Raymond Knopp committed
47
#include "common/utils/LOG/log.h"
48
#include "RRC/NR/MESSAGES/asn1_msg.h"
49
#include "openair2/E1AP/e1ap_asnc.h"
50 51 52 53

#include "NR_BCCH-BCH-Message.h"
#include "NR_UL-DCCH-Message.h"
#include "NR_DL-DCCH-Message.h"
54 55 56 57 58 59
#include "NR_DL-CCCH-Message.h"
#include "NR_UL-CCCH-Message.h"
#include "NR_RRCReject.h"
#include "NR_RejectWaitTime.h"
#include "NR_RRCSetup.h"

60
#include "NR_CellGroupConfig.h"
61
#include "NR_MeasResults.h"
62 63
#include "NR_UL-CCCH-Message.h"
#include "NR_RRCSetupRequest-IEs.h"
Xue Song's avatar
Xue Song committed
64
#include "NR_RRCSetupComplete-IEs.h"
65
#include "NR_RRCReestablishmentRequest-IEs.h"
66
#include "NR_MIB.h"
67 68
#include "uper_encoder.h"
#include "uper_decoder.h"
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
69

70
#include "common/platform_types.h"
Raymond Knopp's avatar
Raymond Knopp committed
71
#include "common/utils/LOG/vcd_signal_dumper.h"
72

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
73 74 75 76 77
#include "T.h"

#include "RRC/NAS/nas_config.h"
#include "RRC/NAS/rb_config.h"

mir's avatar
mir committed
78
#include "openair3/SECU/secu_defs.h"
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
79

Xue Song's avatar
Xue Song committed
80
#include "rrc_gNB_NGAP.h"
81
#include "rrc_gNB_du.h"
Xue Song's avatar
Xue Song committed
82

83
#include "rrc_gNB_GTPV1U.h"
84

85
#include "nr_pdcp/nr_pdcp_entity.h"
86
#include "nr_pdcp/nr_pdcp_oai_api.h"
87

88
#include "intertask_interface.h"
89
#include "SIMULATION/TOOLS/sim.h" // for taus
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
90

91
#include "executables/softmodem-common.h"
laurent's avatar
laurent committed
92
#include <openair2/RRC/NR/rrc_gNB_UE_context.h>
Laurent's avatar
Laurent committed
93
#include <openair2/X2AP/x2ap_eNB.h>
mir's avatar
mir committed
94
#include <openair3/SECU/key_nas_deriver.h>
95
#include <openair3/ocp-gtpu/gtp_itf.h>
96
#include <openair2/RRC/NR/nr_rrc_proto.h>
97
#include "openair2/F1AP/f1ap_common.h"
98
#include "openair2/F1AP/f1ap_ids.h"
99 100
#include "openair2/SDAP/nr_sdap/nr_sdap_entity.h"
#include "cucp_cuup_if.h"
101

Xue Song's avatar
Xue Song committed
102 103
#include "BIT_STRING.h"
#include "assertions.h"
104

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
105 106 107 108
//#define XER_PRINT

extern RAN_CONTEXT_t RC;

109
static inline uint64_t bitStr_to_uint64(const BIT_STRING_t *asn);
Xue Song's avatar
Xue Song committed
110

111
mui_t rrc_gNB_mui = 0;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
112

Robert Schmidt's avatar
Robert Schmidt committed
113 114 115 116 117 118 119 120 121 122
// the assoc_id might be 0 (if the DU goes offline). Below helper macro to
// print an error and return from the function in that case
#define RETURN_IF_INVALID_ASSOC_ID(ue_data)                                \
  {                                                                        \
    if (ue_data.du_assoc_id == 0) {                                        \
      LOG_E(NR_RRC, "cannot send data: invalid assoc_id 0, DU offline\n"); \
      return;                                                              \
    }                                                                      \
  }

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
123 124
///---------------------------------------------------------------------------------------------------------------///
///---------------------------------------------------------------------------------------------------------------///
luis_pereira87's avatar
luis_pereira87 committed
125

126 127 128 129 130 131
NR_DRB_ToAddModList_t *fill_DRB_configList(gNB_RRC_UE_t *ue)
{
  gNB_RRC_INST *rrc = RC.nrrrc[0];
  if (ue->nb_of_pdusessions == 0)
    return NULL;
  int nb_drb_to_setup = rrc->configuration.drbs;
132
  long drb_priority[MAX_DRBS_PER_UE] = {0};
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
  uint8_t drb_id_to_setup_start = 0;
  NR_DRB_ToAddModList_t *DRB_configList = CALLOC(sizeof(*DRB_configList), 1);
  for (int i = 0; i < ue->nb_of_pdusessions; i++) {
    if (ue->pduSession[i].status >= PDU_SESSION_STATUS_DONE) {
      continue;
    }
    LOG_I(NR_RRC, "adding rnti %x pdusession %d, nb drb %d\n", ue->rnti, ue->pduSession[i].param.pdusession_id, nb_drb_to_setup);
    for (long drb_id_add = 1; drb_id_add <= nb_drb_to_setup; drb_id_add++) {
      uint8_t drb_id;
      // Reference TS23501 Table 5.7.4-1: Standardized 5QI to QoS characteristics mapping
      for (int qos_flow_index = 0; qos_flow_index < ue->pduSession[i].param.nb_qos; qos_flow_index++) {
        switch (ue->pduSession[i].param.qos[qos_flow_index].fiveQI) {
          case 1 ... 4: /* GBR */
            drb_id = next_available_drb(ue, &ue->pduSession[i], GBR_FLOW);
            break;
          case 5 ... 9: /* Non-GBR */
            if (rrc->configuration.drbs > 1) { /* Force the creation from gNB Conf file */
              LOG_W(NR_RRC, "Adding %d DRBs, from gNB config file (not decided by 5GC\n", rrc->configuration.drbs);
              drb_id = next_available_drb(ue, &ue->pduSession[i], GBR_FLOW);
            } else {
              drb_id = next_available_drb(ue, &ue->pduSession[i], NONGBR_FLOW);
            }
            break;

          default:
            LOG_E(NR_RRC, "not supported 5qi %lu\n", ue->pduSession[i].param.qos[qos_flow_index].fiveQI);
            ue->pduSession[i].status = PDU_SESSION_STATUS_FAILED;
            continue;
        }
        drb_priority[drb_id - 1] = ue->pduSession[i].param.qos[qos_flow_index].allocation_retention_priority.priority_level;
        if (drb_priority[drb_id - 1] < 0 || drb_priority[drb_id - 1] > NGAP_PRIORITY_LEVEL_NO_PRIORITY) {
          LOG_E(NR_RRC, "invalid allocation_retention_priority.priority_level %ld set to _NO_PRIORITY\n", drb_priority[drb_id - 1]);
          drb_priority[drb_id - 1] = NGAP_PRIORITY_LEVEL_NO_PRIORITY;
        }

        if (drb_is_active(ue, drb_id)) { /* Non-GBR flow using the same DRB or a GBR flow with no available DRBs*/
          nb_drb_to_setup--;
        } else {
          generateDRB(ue,
                      drb_id,
                      &ue->pduSession[i],
                      rrc->configuration.enable_sdap,
                      rrc->security.do_drb_integrity,
                      rrc->security.do_drb_ciphering);
          NR_DRB_ToAddMod_t *DRB_config = generateDRB_ASN1(&ue->established_drbs[drb_id - 1]);
          if (drb_id_to_setup_start == 0)
            drb_id_to_setup_start = DRB_config->drb_Identity;
          asn1cSeqAdd(&DRB_configList->list, DRB_config);
        }
        LOG_D(RRC, "DRB Priority %ld\n", drb_priority[drb_id]); // To supress warning for now
      }
    }
  }
  if (DRB_configList->list.count == 0) {
    free(DRB_configList);
    return NULL;
  }
  return DRB_configList;
}
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
192

193 194
static void freeDRBlist(NR_DRB_ToAddModList_t *list)
{
laurent's avatar
laurent committed
195
  //ASN_STRUCT_FREE(asn_DEF_NR_DRB_ToAddModList, list);
196 197
  return;
}
198

199 200 201
typedef struct deliver_dl_rrc_message_data_s {
  const gNB_RRC_INST *rrc;
  f1ap_dl_rrc_message_t *dl_rrc;
Robert Schmidt's avatar
Robert Schmidt committed
202
  sctp_assoc_t assoc_id;
203 204 205 206 207 208 209 210
} deliver_dl_rrc_message_data_t;
static void rrc_deliver_dl_rrc_message(void *deliver_pdu_data, ue_id_t ue_id, int srb_id, char *buf, int size, int sdu_id)
{
  DevAssert(deliver_pdu_data != NULL);
  deliver_dl_rrc_message_data_t *data = (deliver_dl_rrc_message_data_t *)deliver_pdu_data;
  data->dl_rrc->rrc_container = (uint8_t *)buf;
  data->dl_rrc->rrc_container_length = size;
  DevAssert(data->dl_rrc->srb_id == srb_id);
Robert Schmidt's avatar
Robert Schmidt committed
211
  data->rrc->mac_rrc.dl_rrc_message_transfer(data->assoc_id, data->dl_rrc);
212 213 214 215 216 217
}


void nr_rrc_transfer_protected_rrc_message(const gNB_RRC_INST *rrc, const gNB_RRC_UE_t *ue_p, uint8_t srb_id, const uint8_t* buffer, int size)
{
  DevAssert(size > 0);
218
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
219
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
220
  f1ap_dl_rrc_message_t dl_rrc = {.gNB_CU_ue_id = ue_p->rrc_ue_id, .gNB_DU_ue_id = ue_data.secondary_ue, .srb_id = srb_id};
Robert Schmidt's avatar
Robert Schmidt committed
221
  deliver_dl_rrc_message_data_t data = {.rrc = rrc, .dl_rrc = &dl_rrc, .assoc_id = ue_data.du_assoc_id };
222
  nr_pdcp_data_req_srb(ue_p->rrc_ue_id, srb_id, rrc_gNB_mui++, size, (unsigned char *const)buffer, rrc_deliver_dl_rrc_message, &data);
223
}
224

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
static int get_dl_band(const f1ap_served_cell_info_t *cell_info)
{
  return cell_info->mode == F1AP_MODE_TDD ? cell_info->tdd.freqinfo.band : cell_info->fdd.dl_freqinfo.band;
}

static int get_ssb_scs(const f1ap_served_cell_info_t *cell_info)
{
  return cell_info->mode == F1AP_MODE_TDD ? cell_info->tdd.tbw.scs : cell_info->fdd.dl_tbw.scs;
}

static int get_dl_arfcn(const f1ap_served_cell_info_t *cell_info)
{
  return cell_info->mode == F1AP_MODE_TDD ? cell_info->tdd.freqinfo.arfcn : cell_info->fdd.dl_freqinfo.arfcn;
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
static int get_dl_bw(const f1ap_served_cell_info_t *cell_info)
{
  return cell_info->mode == F1AP_MODE_TDD ? cell_info->tdd.tbw.nrb : cell_info->fdd.dl_tbw.nrb;
}

static int get_ssb_arfcn(const f1ap_served_cell_info_t *cell_info, const NR_MIB_t *mib, const NR_SIB1_t *sib1)
{
  DevAssert(cell_info != NULL && sib1 != NULL && mib != NULL);
  const NR_FrequencyInfoDL_SIB_t* freq_info = &sib1->servingCellConfigCommon->downlinkConfigCommon.frequencyInfoDL;
  AssertFatal(freq_info->scs_SpecificCarrierList.list.count == 1, "cannot handle more than one carrier, but has %d\n", freq_info->scs_SpecificCarrierList.list.count);
  AssertFatal(freq_info->scs_SpecificCarrierList.list.array[0]->offsetToCarrier == 0, "cannot handle offsetToCarrier != 0, but is %ld\n", freq_info->scs_SpecificCarrierList.list.array[0]->offsetToCarrier);

  long offsetToPointA = freq_info->offsetToPointA;
  long kssb = mib->ssb_SubcarrierOffset;
  uint32_t dl_arfcn = get_dl_arfcn(cell_info);
  int scs = get_ssb_scs(cell_info);
  int band = get_dl_band(cell_info);
luis_pereira87's avatar
luis_pereira87 committed
257 258 259 260 261 262 263 264 265 266
  // FR1 includes frequency bands from 410 MHz (ARFCN 82000) to 7125 MHz (ARFCN 875000)
  // FR2 includes frequency bands from 24.25 GHz (ARFCN 2016667) to 71.0 GHz (ARFCN 2795832)
  uint64_t scaling = 0;
  if (dl_arfcn >= 82000 && dl_arfcn < 875000)
    scaling = 1;
  else if (dl_arfcn >= 2016667 && dl_arfcn < 2795832)
    scaling = 4;
  else
    AssertFatal(false, "Invalid absoluteFrequencyPointA: %d\n", dl_arfcn);

267 268

  uint64_t freqpointa = from_nrarfcn(band, scs, dl_arfcn);
luis_pereira87's avatar
luis_pereira87 committed
269
  // offsetToPointA and kSSB are both on 15kHz SCS for FR1 and 60kHz SCS for FR2 (see 38.211 sections 7.4.3.1 and 4.4.4.2)
270 271 272 273 274 275
  // SSB uses the SCS of the cell and is 20 RBs wide, so use 10
  uint64_t freqssb = freqpointa + scaling * 15000 * (offsetToPointA * 12 + kssb)  + 10ll * 12 * (1 << scs) * 15000;
  int bw_index = get_supported_band_index(scs, band, get_dl_bw(cell_info));
  int band_size_hz = get_supported_bw_mhz(band > 256 ? FR2 : FR1, bw_index) * 1000 * 1000;
  uint32_t ssb_arfcn = to_nrarfcn(band, freqssb, scs, band_size_hz);

Robert Schmidt's avatar
Robert Schmidt committed
276
  LOG_D(RRC, "freqpointa %ld Hz/%d offsetToPointA %ld kssb %ld scs %d band %d band_size_hz %d freqssb %ld Hz/%d\n", freqpointa, dl_arfcn, offsetToPointA, kssb, scs, band, band_size_hz, freqssb, ssb_arfcn);
277 278 279 280 281 282 283 284 285 286

  if (RC.nrmac) {
    // debugging: let's test this is the correct ARFCN
    // in the CU, we have no access to the SSB ARFCN and therefore need to
    // compute it ourselves. If we are running in monolithic, though, we have
    // access to the MAC structures and hence can read and compare to the
    // original SSB ARFCN. If the below creates problems, it can safely be
    // taken out (but the reestablishment will likely not work).
    const NR_ServingCellConfigCommon_t *scc = RC.nrmac[0]->common_channels[0].ServingCellConfigCommon;
    uint32_t scc_ssb_arfcn = *scc->downlinkConfigCommon->frequencyInfoDL->absoluteFrequencySSB;
287
    AssertFatal(ssb_arfcn == scc_ssb_arfcn, "mismatch of SCC SSB ARFCN original %d vs. computed %d! Note: you can remove this Assert, the gNB might run but UE connection instable\n", scc_ssb_arfcn, ssb_arfcn);
288 289 290 291 292
  }

  return ssb_arfcn;
}

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
293 294 295
///---------------------------------------------------------------------------------------------------------------///
///---------------------------------------------------------------------------------------------------------------///

296
static void init_NR_SI(gNB_RRC_INST *rrc)
297
{
298 299 300
  if (!NODE_IS_DU(rrc->node_type)) {
    rrc->carrier.SIB23 = (uint8_t *) malloc16(100);
    AssertFatal(rrc->carrier.SIB23 != NULL, "cannot allocate memory for SIB");
301
    rrc->carrier.sizeof_SIB23 = do_SIB23_NR(&rrc->carrier);
302 303 304
    LOG_I(NR_RRC,"do_SIB23_NR, size %d \n ", rrc->carrier.sizeof_SIB23);
    AssertFatal(rrc->carrier.sizeof_SIB23 != 255,"FATAL, RC.nrrrc[mod].carrier[CC_id].sizeof_SIB23 == 255");
  }
305

306
  if (get_softmodem_params()->phy_test > 0 || get_softmodem_params()->do_ra > 0) {
307
    AssertFatal(NODE_IS_MONOLITHIC(rrc->node_type), "phy_test and do_ra only work in monolithic\n");
308
    rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_allocate_new_ue_context(rrc);
309 310
    gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
    UE->spCellConfig = calloc(1, sizeof(struct NR_SpCellConfig));
311
    UE->spCellConfig->spCellConfigDedicated = RC.nrmac[0]->common_channels[0].pre_ServingCellConfig;
312 313 314
    LOG_I(NR_RRC,"Adding new user (%p)\n",ue_context_p);
    if (!NODE_IS_CU(RC.nrrrc[0]->node_type)) {
      rrc_add_nsa_user(rrc,ue_context_p,NULL);
315
    }
316
  }
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
317
}
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
318

319
static void rrc_gNB_CU_DU_init(gNB_RRC_INST *rrc)
320 321
{
  switch (rrc->node_type) {
322 323 324 325
    case ngran_gNB_CUCP:
      mac_rrc_dl_f1ap_init(&rrc->mac_rrc);
      cucp_cuup_message_transfer_e1ap_init(rrc);
      break;
326 327
    case ngran_gNB_CU:
      mac_rrc_dl_f1ap_init(&rrc->mac_rrc);
328
      cucp_cuup_message_transfer_direct_init(rrc);
329
      break;
330 331 332 333
    case ngran_gNB:
      mac_rrc_dl_direct_init(&rrc->mac_rrc);
      cucp_cuup_message_transfer_direct_init(rrc);
       break;
334 335 336 337 338 339 340 341 342
    case ngran_gNB_DU:
      /* silently drop this, as we currently still need the RRC at the DU. As
       * soon as this is not the case anymore, we can add the AssertFatal() */
      //AssertFatal(1==0,"nothing to do for DU\n");
      break;
    default:
      AssertFatal(0 == 1, "Unknown node type %d\n", rrc->node_type);
      break;
  }
343
  cu_init_f1_ue_data();
344 345
}

346
void openair_rrc_gNB_configuration(gNB_RRC_INST *rrc, gNB_RrcConfigurationReq *configuration)
347
{
348 349 350
  AssertFatal(rrc != NULL, "RC.nrrrc not initialized!");
  AssertFatal(NUMBER_OF_UE_MAX < (module_id_t)0xFFFFFFFFFFFFFFFF, " variable overflow");
  AssertFatal(configuration!=NULL,"configuration input is null\n");
351
  rrc->module_id = 0;
352
  rrc_gNB_CU_DU_init(rrc);
353
  uid_linear_allocator_init(&rrc->uid_allocator);
354
  RB_INIT(&rrc->rrc_ue_head);
355
  RB_INIT(&rrc->cuups);
Robert Schmidt's avatar
Robert Schmidt committed
356
  RB_INIT(&rrc->dus);
357
  rrc->configuration = *configuration;
358
   /// System Information INIT
359
  init_NR_SI(rrc);
360 361
  return;
} // END openair_rrc_gNB_configuration
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
362

363 364
static void rrc_gNB_process_AdditionRequestInformation(const module_id_t gnb_mod_idP, x2ap_ENDC_sgnb_addition_req_t *m)
{
365 366 367 368 369 370 371
  struct NR_CG_ConfigInfo *cg_configinfo = NULL;
  asn_dec_rval_t dec_rval = uper_decode_complete(NULL,
                            &asn_DEF_NR_CG_ConfigInfo,
                            (void **)&cg_configinfo,
                            (uint8_t *)m->rrc_buffer,
                            (int) m->rrc_buffer_size);//m->rrc_buffer_size);
  gNB_RRC_INST         *rrc=RC.nrrrc[gnb_mod_idP];
372

373 374 375 376 377 378
  if ((dec_rval.code != RC_OK) && (dec_rval.consumed == 0)) {
    AssertFatal(1==0,"NR_UL_DCCH_MESSAGE decode error\n");
    // free the memory
    SEQUENCE_free(&asn_DEF_NR_CG_ConfigInfo, cg_configinfo, 1);
    return;
  }
379

380 381 382 383 384
  xer_fprint(stdout,&asn_DEF_NR_CG_ConfigInfo, cg_configinfo);
  // recreate enough of X2 EN-DC Container
  AssertFatal(cg_configinfo->criticalExtensions.choice.c1->present == NR_CG_ConfigInfo__criticalExtensions__c1_PR_cg_ConfigInfo,
              "ueCapabilityInformation not present\n");
  parse_CG_ConfigInfo(rrc,cg_configinfo,m);
385 386
  LOG_A(NR_RRC, "Successfully parsed CG_ConfigInfo of size %zu bits. (%zu bytes)\n",
        dec_rval.consumed, (dec_rval.consumed +7/8));
387 388
}

389
//-----------------------------------------------------------------------------
390
unsigned int rrc_gNB_get_next_transaction_identifier(module_id_t gnb_mod_idP)
391 392
//-----------------------------------------------------------------------------
{
393 394 395 396 397 398
  static unsigned int transaction_id[NUMBER_OF_gNB_MAX] = {0};
  // used also in NGAP thread, so need thread safe operation
  unsigned int tmp = __atomic_add_fetch(&transaction_id[gnb_mod_idP], 1, __ATOMIC_SEQ_CST);
  tmp %= NR_RRC_TRANSACTION_IDENTIFIER_NUMBER;
  LOG_T(NR_RRC, "generated xid is %d\n", tmp);
  return tmp;
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
static NR_SRB_ToAddModList_t *createSRBlist(gNB_RRC_UE_t *ue, bool reestablish)
{
  if (!ue->Srb[1].Active) {
    LOG_E(NR_RRC, "Call SRB list while SRB1 doesn't exist\n");
    return NULL;
  }
  NR_SRB_ToAddModList_t *list = CALLOC(sizeof(*list), 1);
  for (int i = 0; i < maxSRBs; i++)
    if (ue->Srb[i].Active) {
      asn1cSequenceAdd(list->list, NR_SRB_ToAddMod_t, srb);
      srb->srb_Identity = i;
      if (reestablish && i == 2) {
        asn1cCallocOne(srb->reestablishPDCP, NR_SRB_ToAddMod__reestablishPDCP_true);
      }
    }
  return list;
}

static NR_DRB_ToAddModList_t *createDRBlist(gNB_RRC_UE_t *ue, bool reestablish)
{
  NR_DRB_ToAddMod_t *DRB_config = NULL;
  NR_DRB_ToAddModList_t *DRB_configList = CALLOC(sizeof(*DRB_configList), 1);

424
  for (int i = 0; i < MAX_DRBS_PER_UE; i++) {
425 426 427 428 429 430 431 432 433 434 435 436
    if (ue->established_drbs[i].status != DRB_INACTIVE) {
      DRB_config = generateDRB_ASN1(&ue->established_drbs[i]);
      if (reestablish) {
        ue->established_drbs[i].reestablishPDCP = NR_DRB_ToAddMod__reestablishPDCP_true;
        asn1cCallocOne(DRB_config->reestablishPDCP, NR_DRB_ToAddMod__reestablishPDCP_true);
      }
      asn1cSeqAdd(&DRB_configList->list, DRB_config);
    }
  }
  return DRB_configList;
}

laurent's avatar
laurent committed
437 438 439 440 441 442
static void freeSRBlist(NR_SRB_ToAddModList_t *l)
{
  if (l) {
    for (int i = 0; i < l->list.count; i++)
      free(l->list.array[i]);
    free(l);
laurent's avatar
laurent committed
443 444
  } else
    LOG_E(NR_RRC, "Call free SRB list on NULL pointer\n");
laurent's avatar
laurent committed
445 446
}

447
//-----------------------------------------------------------------------------
448 449
static void rrc_gNB_generate_RRCSetup(instance_t instance,
                                      rnti_t rnti,
450 451
                                      rrc_gNB_ue_context_t *const ue_context_pP,
                                      const uint8_t *masterCellGroup,
452
                                      int masterCellGroup_len)
453 454
//-----------------------------------------------------------------------------
{
455
  LOG_I(NR_RRC, "rrc_gNB_generate_RRCSetup for RNTI %04x\n", rnti);
456 457

  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
458
  gNB_RRC_INST *rrc = RC.nrrrc[instance];
459
  unsigned char buf[1024];
460 461
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(instance);
  ue_p->xids[xid] = RRC_SETUP;
462
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, false);
laurent's avatar
laurent committed
463 464

  int size = do_RRCSetup(ue_context_pP, buf, xid, masterCellGroup, masterCellGroup_len, &rrc->configuration, SRBs);
465
  AssertFatal(size > 0, "do_RRCSetup failed\n");
466
  AssertFatal(size <= 1024, "memory corruption\n");
467 468

  LOG_DUMPMSG(NR_RRC, DEBUG_RRC,
469 470
              (char *)buf,
              size,
471
              "[MSG] RRC Setup\n");
472
  nr_pdcp_add_srbs(true, ue_p->rrc_ue_id, SRBs, 0, NULL, NULL);
Eurecom's avatar
Eurecom committed
473

laurent's avatar
laurent committed
474
  freeSRBlist(SRBs);
475
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
476
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
477
  f1ap_dl_rrc_message_t dl_rrc = {
478
    .gNB_CU_ue_id = ue_p->rrc_ue_id,
479
    .gNB_DU_ue_id = ue_data.secondary_ue,
480 481
    .rrc_container = buf,
    .rrc_container_length = size,
482 483
    .srb_id = CCCH
  };
Robert Schmidt's avatar
Robert Schmidt committed
484
  rrc->mac_rrc.dl_rrc_message_transfer(ue_data.du_assoc_id, &dl_rrc);
485 486
}

487
static void rrc_gNB_generate_RRCReject(module_id_t module_id, rrc_gNB_ue_context_t *const ue_context_pP)
488 489
//-----------------------------------------------------------------------------
{
490
  LOG_I(NR_RRC, "rrc_gNB_generate_RRCReject \n");
491
  gNB_RRC_INST *rrc = RC.nrrrc[module_id];
492
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
493

494
  unsigned char buf[1024];
495
  int size = do_RRCReject(buf);
496
  AssertFatal(size > 0, "do_RRCReject failed\n");
497
  AssertFatal(size <= 1024, "memory corruption\n");
498

499
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC,
500 501
              (char *)buf,
              size,
502
              "[MSG] RRCReject \n");
503
  LOG_I(NR_RRC, " [RAPROC] ue %04x Logical Channel DL-CCCH, Generating NR_RRCReject (bytes %d)\n", ue_p->rnti, size);
504

505
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
506
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
507
  f1ap_dl_rrc_message_t dl_rrc = {
508
    .gNB_CU_ue_id = ue_p->rrc_ue_id,
509
    .gNB_DU_ue_id = ue_data.secondary_ue,
510 511 512 513 514 515
    .rrc_container = buf,
    .rrc_container_length = size,
    .srb_id = CCCH,
    .execute_duplication  = 1,
    .RAT_frequency_priority_information.en_dc = 0
  };
Robert Schmidt's avatar
Robert Schmidt committed
516
  rrc->mac_rrc.dl_rrc_message_transfer(ue_data.du_assoc_id, &dl_rrc);
517 518
}

Xue Song's avatar
Xue Song committed
519 520 521 522
//-----------------------------------------------------------------------------
/*
* Process the rrc setup complete message from UE (SRB1 Active)
*/
523
static void rrc_gNB_process_RRCSetupComplete(const protocol_ctxt_t *const ctxt_pP, rrc_gNB_ue_context_t *ue_context_pP, NR_RRCSetupComplete_IEs_t *rrcSetupComplete)
Xue Song's avatar
Xue Song committed
524 525
//-----------------------------------------------------------------------------
{
526
  LOG_A(NR_RRC, PROTOCOL_NR_RRC_CTXT_UE_FMT" [RAPROC] Logical Channel UL-DCCH, " "processing NR_RRCSetupComplete from UE (SRB1 Active)\n",
527
      PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP));
laurent's avatar
tmp  
laurent committed
528 529
  ue_context_pP->ue_context.Srb[1].Active = 1;
  ue_context_pP->ue_context.Srb[2].Active = 0;
530
  ue_context_pP->ue_context.StatusRrc = NR_RRC_CONNECTED;
531
  AssertFatal(ctxt_pP->rntiMaybeUEid == ue_context_pP->ue_context.rrc_ue_id, "logic bug: inconsistent IDs, must use CU UE ID!\n");
Xue Song's avatar
Xue Song committed
532

533
  rrc_gNB_send_NGAP_NAS_FIRST_REQ(ctxt_pP, ue_context_pP, rrcSetupComplete);
Xue Song's avatar
Xue Song committed
534 535
}

Xue Song's avatar
Xue Song committed
536
//-----------------------------------------------------------------------------
537
static void rrc_gNB_generate_defaultRRCReconfiguration(const protocol_ctxt_t *const ctxt_pP, rrc_gNB_ue_context_t *ue_context_pP)
Xue Song's avatar
Xue Song committed
538 539
//-----------------------------------------------------------------------------
{
540
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
541
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
542
  AssertFatal(ue_p->nb_of_pdusessions == 0, "logic bug: PDU sessions present before RRC Connection established\n");
543 544
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
  ue_p->xids[xid] = RRC_DEFAULT_RECONF;
545

546
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList = CALLOC(1, sizeof(*dedicatedNAS_MessageList));
547

548
  /* Add all NAS PDUs to the list */
549 550 551 552
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
    if (ue_p->pduSession[i].param.nas_pdu.buffer != NULL) {
      asn1cSequenceAdd(dedicatedNAS_MessageList->list, NR_DedicatedNAS_Message_t, msg);
      OCTET_STRING_fromBuf(msg, (char *)ue_p->pduSession[i].param.nas_pdu.buffer, ue_p->pduSession[i].param.nas_pdu.length);
553 554
    }

555 556
    ue_p->pduSession[i].status = PDU_SESSION_STATUS_DONE;
    LOG_D(NR_RRC, "setting the status for the default DRB (index %d) to (%d,%s)\n", i, ue_p->pduSession[i].status, "PDU_SESSION_STATUS_DONE");
557 558
  }

559 560 561
  if (ue_p->nas_pdu.length) {
    asn1cSequenceAdd(dedicatedNAS_MessageList->list, NR_DedicatedNAS_Message_t, msg);
    OCTET_STRING_fromBuf(msg, (char *)ue_p->nas_pdu.buffer, ue_p->nas_pdu.length);
562 563 564 565 566 567 568 569
  }

  /* If list is empty free the list and reset the address */
  if (dedicatedNAS_MessageList->list.count == 0) {
    free(dedicatedNAS_MessageList);
    dedicatedNAS_MessageList = NULL;
  }

570 571
  const nr_rrc_du_container_t *du = get_du_for_ue(rrc, ue_p->rrc_ue_id);
  DevAssert(du != NULL);
572 573 574
  f1ap_served_cell_info_t *cell_info = &du->setup_req->cell[0].info;
  int scs = get_ssb_scs(cell_info);
  int band = get_dl_band(cell_info);
575 576 577 578 579 580 581
  NR_MeasConfig_t *measconfig = NULL;
  if (du->mib != NULL && du->sib1 != NULL) {
    /* we cannot calculate the default measurement config without MIB&SIB1, as
     * we don't know the DU's SSB ARFCN */
    uint32_t ssb_arfcn = get_ssb_arfcn(cell_info, du->mib, du->sib1);
    measconfig = get_defaultMeasConfig(ssb_arfcn, band, scs);
  }
582

583
  uint8_t buffer[RRC_BUF_SIZE] = {0};
584
  int size = do_RRCReconfiguration(ue_p,
585
                                   buffer,
586
                                   RRC_BUF_SIZE,
587 588 589 590 591 592 593 594
                                   xid,
                                   NULL, //*SRB_configList2,
                                   NULL, //*DRB_configList,
                                   NULL,
                                   NULL,
                                   measconfig,
                                   dedicatedNAS_MessageList,
                                   ue_p->masterCellGroup);
595
  AssertFatal(size > 0, "cannot encode RRCReconfiguration in %s()\n", __func__);
Robert Schmidt's avatar
Robert Schmidt committed
596
  free_defaultMeasConfig(measconfig);
597

598 599 600
  if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
    xer_fprint(stdout, &asn_DEF_NR_CellGroupConfig, ue_p->masterCellGroup);
  }
601

602
  // suspicious if it is always malloced before ?
603
  free(ue_p->nas_pdu.buffer);
604

605
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC,(char *)buffer, size, "[MSG] RRC Reconfiguration\n");
606 607

  /* Free all NAS PDUs */
608 609 610 611
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
    if (ue_p->pduSession[i].param.nas_pdu.buffer != NULL) {
      free(ue_p->pduSession[i].param.nas_pdu.buffer);
      ue_p->pduSession[i].param.nas_pdu.buffer = NULL;
612 613 614
    }
  }

615 616 617 618 619 620
  LOG_I(NR_RRC, "[gNB %d] Frame %d, Logical Channel DL-DCCH, Generate NR_RRCReconfiguration (bytes %d, UE id %x)\n",
          ctxt_pP->module_id,
          ctxt_pP->frame,
          size,
          ue_context_pP->ue_context.rnti);
  AssertFatal(!NODE_IS_DU(rrc->node_type), "illegal node type DU!\n");
621

622
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
Xue Song's avatar
Xue Song committed
623 624
}

625
//-----------------------------------------------------------------------------
626
void rrc_gNB_generate_dedicatedRRCReconfiguration(const protocol_ctxt_t *const ctxt_pP, rrc_gNB_ue_context_t *ue_context_pP)
627 628 629 630
//-----------------------------------------------------------------------------
{
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];

631
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
632
  int drb_id_to_setup_start = 1;
633
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
634 635 636
  NR_DRB_ToAddModList_t *DRB_configList = fill_DRB_configList(ue_p);
  int nb_drb_to_setup = DRB_configList ? DRB_configList->list.count : 0;
  ue_p->xids[xid] = RRC_PDUSESSION_ESTABLISH;
637 638 639 640 641 642
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList = NULL;
  NR_DedicatedNAS_Message_t *dedicatedNAS_Message = NULL;
  dedicatedNAS_MessageList = CALLOC(1, sizeof(struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList));

  for (int i=0; i < nb_drb_to_setup; i++) {
    NR_DRB_ToAddMod_t *DRB_config = DRB_configList->list.array[i];
laurent's avatar
laurent committed
643 644
    if (drb_id_to_setup_start == 1)
      drb_id_to_setup_start = DRB_config->drb_Identity;
645
    int j = ue_p->nb_of_pdusessions - 1;
laurent's avatar
laurent committed
646
    AssertFatal(j >= 0, "");
647
    if (ue_p->pduSession[j].param.nas_pdu.buffer != NULL) {
648 649
      dedicatedNAS_Message = CALLOC(1, sizeof(NR_DedicatedNAS_Message_t));
      memset(dedicatedNAS_Message, 0, sizeof(OCTET_STRING_t));
650 651 652 653
      OCTET_STRING_fromBuf(dedicatedNAS_Message,
                           (char *)ue_p->pduSession[j].param.nas_pdu.buffer,
                           ue_p->pduSession[j].param.nas_pdu.length);
      ue_p->pduSession[j].status = PDU_SESSION_STATUS_DONE;
654
      asn1cSeqAdd(&dedicatedNAS_MessageList->list, dedicatedNAS_Message);
655

656
      LOG_I(NR_RRC, "add NAS info with size %d (pdusession idx %d)\n", ue_p->pduSession[j].param.nas_pdu.length, j);
657 658
    } else {
      // TODO
laurent's avatar
laurent committed
659
      LOG_E(NR_RRC, "no NAS info (pdusession idx %d)\n", j);
660
    }
661

662
    ue_p->pduSession[j].xid = xid;
663
  }
luis_pereira87's avatar
luis_pereira87 committed
664
  freeDRBlist(DRB_configList);
665 666 667 668 669 670 671

  /* If list is empty free the list and reset the address */
  if (dedicatedNAS_MessageList->list.count == 0) {
    free(dedicatedNAS_MessageList);
    dedicatedNAS_MessageList = NULL;
  }

luis_pereira87's avatar
luis_pereira87 committed
672 673 674 675 676 677 678 679 680
  /* Free all NAS PDUs */
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
    if (ue_p->pduSession[i].param.nas_pdu.buffer != NULL) {
      /* Free the NAS PDU buffer and invalidate it */
      free(ue_p->pduSession[i].param.nas_pdu.buffer);
      ue_p->pduSession[i].param.nas_pdu.buffer = NULL;
    }
  }

681
  NR_CellGroupConfig_t *cellGroupConfig = ue_p->masterCellGroup;
682

683
  uint8_t buffer[RRC_BUF_SIZE] = {0};
684
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, false);
685
  NR_DRB_ToAddModList_t *DRBs = createDRBlist(ue_p, false);
luis_pereira87's avatar
luis_pereira87 committed
686

687
  int size = do_RRCReconfiguration(ue_p,
688 689 690
                                   buffer,
                                   RRC_BUF_SIZE,
                                   xid,
laurent's avatar
laurent committed
691
                                   SRBs,
luis_pereira87's avatar
luis_pereira87 committed
692
                                   DRBs,
693
                                   ue_p->DRB_ReleaseList,
694 695 696 697
                                   NULL,
                                   NULL,
                                   dedicatedNAS_MessageList,
                                   cellGroupConfig);
698
  LOG_DUMPMSG(NR_RRC,DEBUG_RRC,(char *)buffer,size,"[MSG] RRC Reconfiguration\n");
laurent's avatar
laurent committed
699
  freeSRBlist(SRBs);
luis_pereira87's avatar
luis_pereira87 committed
700
  freeDRBlist(DRBs);
701 702 703
  ASN_STRUCT_FREE(asn_DEF_NR_DRB_ToReleaseList, ue_p->DRB_ReleaseList);
  ue_p->DRB_ReleaseList = NULL;

704
  LOG_I(NR_RRC, "[gNB %d] Frame %d, Logical Channel DL-DCCH, Generate RRCReconfiguration (bytes %d, UE RNTI %x)\n", ctxt_pP->module_id, ctxt_pP->frame, size, ue_p->rnti);
705 706
  LOG_D(NR_RRC,
        "[FRAME %05d][RRC_gNB][MOD %u][][--- PDCP_DATA_REQ/%d Bytes (rrcReconfiguration to UE %x MUI %d) --->][PDCP][MOD %u][RB %u]\n",
707 708 709 710 711 712 713
        ctxt_pP->frame,
        ctxt_pP->module_id,
        size,
        ue_p->rnti,
        rrc_gNB_mui,
        ctxt_pP->module_id,
        DCCH);
714

715
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
716 717
}

718
//-----------------------------------------------------------------------------
Masayuki Harada's avatar
Masayuki Harada committed
719
void
720 721 722 723 724
rrc_gNB_modify_dedicatedRRCReconfiguration(
  const protocol_ctxt_t     *const ctxt_pP,
  rrc_gNB_ue_context_t      *ue_context_pP)
//-----------------------------------------------------------------------------
{
725 726
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
  NR_DRB_ToAddModList_t *DRB_configList = fill_DRB_configList(ue_p);
727
  int qos_flow_index = 0;
728
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
729
  ue_p->xids[xid] = RRC_PDUSESSION_MODIFY;
730

731 732 733
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList =
      CALLOC(1, sizeof(*dedicatedNAS_MessageList));
  NR_DRB_ToAddMod_t *DRB_config = NULL;
734

735
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
736
    // bypass the new and already configured pdu sessions
737 738
    if (ue_p->pduSession[i].status >= PDU_SESSION_STATUS_DONE) {
      ue_p->pduSession[i].xid = xid;
739 740 741
      continue;
    }

742
    if (ue_p->pduSession[i].cause != NGAP_CAUSE_NOTHING) {
743
      // set xid of failure pdu session
744 745
      ue_p->pduSession[i].xid = xid;
      ue_p->pduSession[i].status = PDU_SESSION_STATUS_FAILED;
746 747 748 749
      continue;
    }

    // search exist DRB_config
750
    int j;
751
    for (j = 0; i < MAX_DRBS_PER_UE; j++) {
752 753
      if (ue_p->established_drbs[j].status != DRB_INACTIVE
          && ue_p->established_drbs[j].cnAssociation.sdap_config.pdusession_id == ue_p->pduSession[i].param.pdusession_id)
754 755 756
        break;
    }

757
    if (j == MAX_DRBS_PER_UE) {
758 759 760 761
      ue_p->pduSession[i].xid = xid;
      ue_p->pduSession[i].status = PDU_SESSION_STATUS_FAILED;
      ue_p->pduSession[i].cause = NGAP_CAUSE_RADIO_NETWORK;
      ue_p->pduSession[i].cause_value = NGAP_CauseRadioNetwork_unspecified;
762 763 764 765
      continue;
    }

    // Reference TS23501 Table 5.7.4-1: Standardized 5QI to QoS characteristics mapping
766 767
    for (qos_flow_index = 0; qos_flow_index < ue_p->pduSession[i].param.nb_qos; qos_flow_index++) {
      switch (ue_p->pduSession[i].param.qos[qos_flow_index].fiveQI) {
768 769 770 771 772 773 774 775 776 777 778 779 780
        case 1: //100ms
        case 2: //150ms
        case 3: //50ms
        case 4: //300ms
        case 5: //100ms
        case 6: //300ms
        case 7: //100ms
        case 8: //300ms
        case 9: //300ms Video (Buffered Streaming)TCP-based (e.g., www, e-mail, chat, ftp, p2p file sharing, progressive video, etc.)
          // TODO
          break;

        default:
781 782 783 784 785
          LOG_E(NR_RRC, "not supported 5qi %lu\n", ue_p->pduSession[i].param.qos[qos_flow_index].fiveQI);
          ue_p->pduSession[i].status = PDU_SESSION_STATUS_FAILED;
          ue_p->pduSession[i].xid = xid;
          ue_p->pduSession[i].cause = NGAP_CAUSE_RADIO_NETWORK;
          ue_p->pduSession[i].cause_value = NGAP_CauseRadioNetwork_not_supported_5QI_value;
786 787
          continue;
      }
788 789 790 791 792 793
      LOG_I(NR_RRC,
            "PDU SESSION ID %ld, DRB ID %ld (index %d), QOS flow %d, 5QI %ld \n",
            DRB_config->cnAssociation->choice.sdap_Config->pdu_Session,
            DRB_config->drb_Identity,
            i,
            qos_flow_index,
794
            ue_p->pduSession[i].param.qos[qos_flow_index].fiveQI);
795 796
    }

797
    asn1cSeqAdd(&DRB_configList->list, DRB_config);
798

799 800
    ue_p->pduSession[i].status = PDU_SESSION_STATUS_DONE;
    ue_p->pduSession[i].xid = xid;
801

802 803 804 805
    if (ue_p->pduSession[i].param.nas_pdu.buffer != NULL) {
      asn1cSequenceAdd(dedicatedNAS_MessageList->list,NR_DedicatedNAS_Message_t, dedicatedNAS_Message);
      OCTET_STRING_fromBuf(dedicatedNAS_Message, (char *)ue_p->pduSession[i].param.nas_pdu.buffer, ue_p->pduSession[i].param.nas_pdu.length);
      LOG_I(NR_RRC, "add NAS info with size %d (pdusession id %d)\n", ue_p->pduSession[i].param.nas_pdu.length, ue_p->pduSession[i].param.pdusession_id);
806
    } else {
807
      LOG_W(NR_RRC, "no NAS info (pdusession id %d)\n", ue_p->pduSession[i].param.pdusession_id);
808 809 810 811 812 813 814 815 816
    }
  }

  /* If list is empty free the list and reset the address */
  if (dedicatedNAS_MessageList->list.count == 0) {
    free(dedicatedNAS_MessageList);
    dedicatedNAS_MessageList = NULL;
  }

817
  uint8_t buffer[RRC_BUF_SIZE];
818
  int size = do_RRCReconfiguration(ue_p,
819 820 821 822 823 824 825 826 827 828
                                   buffer,
                                   RRC_BUF_SIZE,
                                   xid,
                                   NULL,
                                   DRB_configList,
                                   NULL,
                                   NULL,
                                   NULL,
                                   dedicatedNAS_MessageList,
                                   NULL);
829 830 831
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC, (char *)buffer, size, "[MSG] RRC Reconfiguration\n");

  /* Free all NAS PDUs */
832 833
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
    if (ue_p->pduSession[i].param.nas_pdu.buffer != NULL) {
834
      /* Free the NAS PDU buffer and invalidate it */
835 836
      free(ue_p->pduSession[i].param.nas_pdu.buffer);
      ue_p->pduSession[i].param.nas_pdu.buffer = NULL;
837 838 839
    }
  }

840
  LOG_I(NR_RRC, "[gNB %d] Frame %d, Logical Channel DL-DCCH, Generate RRCReconfiguration (bytes %d, UE RNTI %x)\n", ctxt_pP->module_id, ctxt_pP->frame, size, ue_p->rnti);
841 842
  LOG_D(NR_RRC,
        "[FRAME %05d][RRC_gNB][MOD %u][][--- PDCP_DATA_REQ/%d Bytes (rrcReconfiguration to UE %x MUI %d) --->][PDCP][MOD %u][RB %u]\n",
843 844 845 846 847 848 849
        ctxt_pP->frame,
        ctxt_pP->module_id,
        size,
        ue_p->rnti,
        rrc_gNB_mui,
        ctxt_pP->module_id,
        DCCH);
850

851
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
852
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
853 854
}

855 856 857 858 859 860 861 862 863 864
//-----------------------------------------------------------------------------
void
rrc_gNB_generate_dedicatedRRCReconfiguration_release(
    const protocol_ctxt_t   *const ctxt_pP,
    rrc_gNB_ue_context_t    *const ue_context_pP,
    uint8_t                  xid,
    uint32_t                 nas_length,
    uint8_t                 *nas_buffer)
//-----------------------------------------------------------------------------
{
865
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
866

867
  NR_DRB_ToReleaseList_t *DRB_Release_configList2 = CALLOC(sizeof(*DRB_Release_configList2), 1);
868

869
  for (int i = 0; i < NB_RB_MAX; i++) {
870
    if ((ue_p->pduSession[i].status == PDU_SESSION_STATUS_TORELEASE) && ue_p->pduSession[i].xid == xid) {
871 872
      asn1cSequenceAdd(DRB_Release_configList2->list, NR_DRB_Identity_t, DRB_release);
      *DRB_release = i + 1;
873 874 875 876
    }
  }

  /* If list is empty free the list and reset the address */
877
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList = NULL;
878
  if (nas_length > 0) {
879 880 881
    dedicatedNAS_MessageList = CALLOC(1, sizeof(*dedicatedNAS_MessageList));
    asn1cSequenceAdd(dedicatedNAS_MessageList->list, NR_DedicatedNAS_Message_t, dedicatedNAS_Message);
    OCTET_STRING_fromBuf(dedicatedNAS_Message, (char *)nas_buffer, nas_length);
882 883 884 885 886
    LOG_I(NR_RRC,"add NAS info with size %d\n", nas_length);
  } else {
    LOG_W(NR_RRC,"dedlicated NAS list is empty\n");
  }

887
  uint8_t buffer[RRC_BUF_SIZE] = {0};
888
  int size = do_RRCReconfiguration(ue_p,
889 890 891 892 893
                                   buffer,
                                   RRC_BUF_SIZE,
                                   xid,
                                   NULL,
                                   NULL,
894
                                   DRB_Release_configList2,
895 896 897 898
                                   NULL,
                                   NULL,
                                   dedicatedNAS_MessageList,
                                   NULL);
899
  LOG_DUMPMSG(NR_RRC,DEBUG_RRC,(char *)buffer,size, "[MSG] RRC Reconfiguration\n");
900 901 902 903 904 905 906

  /* Free all NAS PDUs */
  if (nas_length > 0) {
    /* Free the NAS PDU buffer and invalidate it */
    free(nas_buffer);
  }

907
  LOG_I(NR_RRC, "[gNB %d] Frame %d, Logical Channel DL-DCCH, Generate NR_RRCReconfiguration (bytes %d, UE RNTI %x)\n", ctxt_pP->module_id, ctxt_pP->frame, size, ue_p->rnti);
908 909
  LOG_D(NR_RRC,
        "[FRAME %05d][RRC_gNB][MOD %u][][--- PDCP_DATA_REQ/%d Bytes (rrcReconfiguration to UE %x MUI %d) --->][PDCP][MOD %u][RB %u]\n",
910 911 912 913 914 915 916
        ctxt_pP->frame,
        ctxt_pP->module_id,
        size,
        ue_p->rnti,
        rrc_gNB_mui,
        ctxt_pP->module_id,
        DCCH);
luis_pereira87's avatar
luis_pereira87 committed
917

918
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
919
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
920 921
}

922 923 924 925
//-----------------------------------------------------------------------------
/*
* Process the RRC Reconfiguration Complete from the UE
*/
926
static void rrc_gNB_process_RRCReconfigurationComplete(const protocol_ctxt_t *const ctxt_pP, rrc_gNB_ue_context_t *ue_context_pP, const uint8_t xid)
927
{
928
  int                                 drb_id;
mir's avatar
mir committed
929 930 931 932
  uint8_t kRRCenc[16] = {0};
  uint8_t kRRCint[16] = {0};
  uint8_t kUPenc[16] = {0};
  uint8_t kUPint[16] = {0};
laurent's avatar
laurent committed
933
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
934
  NR_DRB_ToAddModList_t *DRB_configList = createDRBlist(ue_p, false);
935

936 937
  /* Derive the keys from kgnb */
  if (DRB_configList != NULL) {
mir's avatar
mir committed
938 939
    nr_derive_key(UP_ENC_ALG, ue_p->ciphering_algorithm, ue_p->kgnb, kUPenc);
    nr_derive_key(UP_INT_ALG, ue_p->integrity_algorithm, ue_p->kgnb, kUPint);
940 941
  }

mir's avatar
mir committed
942 943
  nr_derive_key(RRC_ENC_ALG, ue_p->ciphering_algorithm, ue_p->kgnb, kRRCenc);
  nr_derive_key(RRC_INT_ALG, ue_p->integrity_algorithm, ue_p->kgnb, kRRCint);
944

mir's avatar
mir committed
945
  /* Refresh SRBs/DRBs */
946
  LOG_D(NR_RRC, "Configuring PDCP DRBs/SRBs for UE %04x\n", ue_p->rnti);
947
  ue_context_pP->ue_context.ue_reconfiguration_after_reestablishment_counter++;
948

949
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, false);
Robert Schmidt's avatar
Robert Schmidt committed
950
  nr_pdcp_add_srbs(ctxt_pP->enb_flag,
951
                   ue_p->rrc_ue_id,
Robert Schmidt's avatar
Robert Schmidt committed
952 953 954 955 956
                   SRBs,
                   (ue_p->integrity_algorithm << 4) | ue_p->ciphering_algorithm,
                   kRRCenc,
                   kRRCint);
  freeSRBlist(SRBs);
957
  nr_pdcp_add_drbs(ctxt_pP->enb_flag,
958
                   ue_p->rrc_ue_id,
959
                   DRB_configList,
960
                   (ue_p->integrity_algorithm << 4) | ue_p->ciphering_algorithm,
961
                   kUPenc,
962
                   kUPint);
963

964 965 966 967 968
  /* Loop through DRBs and establish if necessary */
  if (DRB_configList != NULL) {
    for (int i = 0; i < DRB_configList->list.count; i++) {
      if (DRB_configList->list.array[i]) {
        drb_id = (int)DRB_configList->list.array[i]->drb_Identity;
969 970 971 972 973 974 975
        LOG_A(NR_RRC,
              "[gNB %d] Frame  %d : Logical Channel UL-DCCH, Received NR_RRCReconfigurationComplete from UE rnti %lx, reconfiguring DRB %d\n",
              ctxt_pP->module_id,
              ctxt_pP->frame,
              ctxt_pP->rntiMaybeUEid,
              (int)DRB_configList->list.array[i]->drb_Identity);
        //(int)*DRB_configList->list.array[i]->pdcp_Config->moreThanOneRLC->primaryPath.logicalChannel);
976

977 978
        if (ue_p->DRB_active[drb_id - 1] == 0) {
          ue_p->DRB_active[drb_id - 1] = DRB_ACTIVE;
979 980
          LOG_D(NR_RRC, "[gNB %d] Frame %d: Establish RLC UM Bidirectional, DRB %d Active\n",
                  ctxt_pP->module_id, ctxt_pP->frame, (int)DRB_configList->list.array[i]->drb_Identity);
981

982 983 984
          LOG_D(NR_RRC,
                  PROTOCOL_NR_RRC_CTXT_UE_FMT" RRC_gNB --- MAC_CONFIG_REQ  (DRB) ---> MAC_gNB\n",
                  PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP));
985

yaojie's avatar
yaojie committed
986 987 988
          //if (DRB_configList->list.array[i]->pdcp_Config->moreThanOneRLC->primaryPath.logicalChannel) {
          //  nr_DRB2LCHAN[i] = (uint8_t) * DRB_configList->list.array[i]->pdcp_Config->moreThanOneRLC->primaryPath.logicalChannel;
          //}
989

990
            // rrc_mac_config_req_eNB
laurent's avatar
laurent committed
991
        } else { // remove LCHAN from MAC/PHY
992
          if (ue_p->DRB_active[drb_id] == 1) {
yoshio.inoue's avatar
yoshio.inoue committed
993
            /* TODO : It may be needed if gNB goes into full stack working. */
994 995 996 997
            // DRB has just been removed so remove RLC + PDCP for DRB
            /*      rrc_pdcp_config_req (ctxt_pP->module_id, frameP, 1, CONFIG_ACTION_REMOVE,
            (ue_mod_idP * NB_RB_MAX) + DRB2LCHAN[i],UNDEF_SECURITY_MODE);
            */
yaojie's avatar
yaojie committed
998
            /*rrc_rlc_config_req(ctxt_pP,
999 1000 1001
                                SRB_FLAG_NO,
                                MBMS_FLAG_NO,
                                CONFIG_ACTION_REMOVE,
Robert Schmidt's avatar
Robert Schmidt committed
1002
                                nr_DRB2LCHAN[i]);*/
1003 1004
          }

1005
          // ue_p->DRB_active[drb_id] = 0;
1006 1007 1008 1009 1010
          LOG_D(NR_RRC, PROTOCOL_NR_RRC_CTXT_UE_FMT" RRC_eNB --- MAC_CONFIG_REQ  (DRB) ---> MAC_eNB\n",
                  PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP));

          // rrc_mac_config_req_eNB

1011
        } // end else of if (ue_p->DRB_active[drb_id] == 0)
1012 1013 1014 1015
      } // end if (DRB_configList->list.array[i])
    } // end for (int i = 0; i < DRB_configList->list.count; i++)

  } // end if DRB_configList != NULL
1016
  freeDRBlist(DRB_configList);
1017
}
1018

yaojie's avatar
yaojie committed
1019
//-----------------------------------------------------------------------------
1020
static void rrc_gNB_generate_RRCReestablishment(rrc_gNB_ue_context_t *ue_context_pP,
1021
                                                const uint8_t *masterCellGroup_from_DU,
1022
                                                const rnti_t old_rnti,
1023
                                                const nr_rrc_du_container_t *du)
yaojie's avatar
yaojie committed
1024 1025
//-----------------------------------------------------------------------------
{
1026 1027
  module_id_t module_id = 0;
  gNB_RRC_INST *rrc = RC.nrrrc[module_id];
1028
  int enable_ciphering = 0;
1029
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
1030

1031
  uint8_t buffer[RRC_BUF_SIZE] = {0};
1032 1033
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(module_id);
  ue_p->xids[xid] = RRC_REESTABLISH;
1034
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, true);
1035 1036 1037
  const f1ap_served_cell_info_t *cell_info = &du->setup_req->cell[0].info;
  uint32_t ssb_arfcn = get_ssb_arfcn(cell_info, du->mib, du->sib1);
  int size = do_RRCReestablishment(ue_context_pP, buffer, RRC_BUF_SIZE, xid, cell_info->nr_pci, ssb_arfcn);
1038

1039
  LOG_I(NR_RRC, "[RAPROC] UE %04x Logical Channel DL-DCCH, Generating NR_RRCReestablishment (bytes %d)\n", ue_p->rnti, size);
1040

mir's avatar
mir committed
1041 1042 1043
  uint8_t kRRCenc[16] = {0};
  uint8_t kRRCint[16] = {0};
  uint8_t kUPenc[16] = {0};
1044
  /* Derive the keys from kgnb */
laurent's avatar
laurent committed
1045
  if (ue_p->Srb[1].Active)
mir's avatar
mir committed
1046
    nr_derive_key(UP_ENC_ALG, ue_p->ciphering_algorithm, ue_p->kgnb, kUPenc);
1047

mir's avatar
mir committed
1048 1049
  nr_derive_key(RRC_ENC_ALG, ue_p->ciphering_algorithm, ue_p->kgnb, kRRCenc);
  nr_derive_key(RRC_INT_ALG, ue_p->integrity_algorithm, ue_p->kgnb, kRRCint);
laurent's avatar
laurent committed
1050
  freeSRBlist(SRBs);
1051
  LOG_I(NR_RRC, "Set PDCP security UE %d RNTI %04x nca %ld nia %d in RRCReestablishment\n", ue_p->rrc_ue_id, ue_p->rnti, ue_p->ciphering_algorithm, ue_p->integrity_algorithm);
1052 1053 1054
  uint8_t security_mode =
      enable_ciphering ? ue_p->ciphering_algorithm | (ue_p->integrity_algorithm << 4) : 0 | (ue_p->integrity_algorithm << 4);

1055 1056 1057
  for (int srb_id = 1; srb_id < maxSRBs; srb_id++) {
    if (ue_p->Srb[srb_id].Active) {
      nr_pdcp_config_set_security(ue_p->rrc_ue_id, srb_id, security_mode, kRRCenc, kRRCint, kUPenc);
1058 1059
      // TODO: should send E1 UE Bearer Modification with PDCP Reestablishment flag
      nr_pdcp_reestablishment(ue_p->rrc_ue_id, srb_id, true);
1060 1061 1062
    }
  }

1063
  // TODO: should send E1 UE Bearer Modification with PDCP Reestablishment flag
1064 1065 1066 1067
  for (int drb_id = 1; drb_id <= MAX_DRBS_PER_UE; drb_id++) {
    if (ue_p->established_drbs[drb_id - 1].status != DRB_INACTIVE)
      nr_pdcp_reestablishment(ue_p->rrc_ue_id, drb_id, false);
  }
1068

1069
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
1070
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
1071 1072 1073 1074 1075
  uint32_t old_gNB_DU_ue_id = old_rnti;
  f1ap_dl_rrc_message_t dl_rrc = {.gNB_CU_ue_id = ue_p->rrc_ue_id,
                                  .gNB_DU_ue_id = ue_data.secondary_ue,
                                  .srb_id = DCCH,
                                  .old_gNB_DU_ue_id = &old_gNB_DU_ue_id};
Robert Schmidt's avatar
Robert Schmidt committed
1076
  deliver_dl_rrc_message_data_t data = {.rrc = rrc, .dl_rrc = &dl_rrc, .assoc_id = ue_data.du_assoc_id};
1077
  nr_pdcp_data_req_srb(ue_p->rrc_ue_id, DCCH, rrc_gNB_mui++, size, (unsigned char *const)buffer, rrc_deliver_dl_rrc_message, &data);
1078 1079
}

1080 1081 1082 1083 1084
/// @brief Function tha processes RRCReestablishmentComplete message sent by the UE, after RRCReestasblishment request.
/// @param ctxt_pP Protocol context containing information regarding the UE and gNB
/// @param reestablish_rnti is the old C-RNTI
/// @param ue_context_pP  UE context container information regarding the UE
/// @param xid Transaction Identifier used in RRC messages
1085 1086 1087
static void rrc_gNB_process_RRCReestablishmentComplete(const protocol_ctxt_t *const ctxt_pP,
                                                       rrc_gNB_ue_context_t *ue_context_pP,
                                                       const uint8_t xid)
1088
{
1089
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
1090 1091 1092
  LOG_I(NR_RRC,
        "[RAPROC] UE %04x Logical Channel UL-DCCH, processing NR_RRCReestablishmentComplete from UE (SRB1 Active)\n",
        ue_p->rnti);
1093 1094 1095

  int i = 0;

1096
  uint8_t new_xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
1097
  ue_p->xids[new_xid] = RRC_REESTABLISH_COMPLETE;
1098
  ue_p->StatusRrc = NR_RRC_CONNECTED;
laurent's avatar
laurent committed
1099 1100

  ue_p->Srb[1].Active = 1;
1101 1102 1103

  uint8_t send_security_mode_command = false;
  nr_rrc_pdcp_config_security(ctxt_pP, ue_context_pP, send_security_mode_command);
1104

1105 1106
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
  NR_CellGroupConfig_t *cellGroupConfig = calloc(1, sizeof(NR_CellGroupConfig_t));
1107

1108
  cellGroupConfig->spCellConfig = ue_p->masterCellGroup->spCellConfig;
1109
  cellGroupConfig->mac_CellGroupConfig = ue_p->masterCellGroup->mac_CellGroupConfig;
1110
  cellGroupConfig->physicalCellGroupConfig = ue_p->masterCellGroup->physicalCellGroupConfig;
1111 1112 1113 1114 1115 1116 1117 1118 1119
  cellGroupConfig->rlc_BearerToReleaseList = NULL;
  cellGroupConfig->rlc_BearerToAddModList = calloc(1, sizeof(*cellGroupConfig->rlc_BearerToAddModList));

  /*
   * Get SRB2, DRB configuration from the existing UE context,
   * also start from SRB2 (i=1) and not from SRB1 (i=0).
   */
  for (i = 1; i < ue_p->masterCellGroup->rlc_BearerToAddModList->list.count; ++i)
    asn1cSeqAdd(&cellGroupConfig->rlc_BearerToAddModList->list, ue_p->masterCellGroup->rlc_BearerToAddModList->list.array[i]);
1120 1121

  for (i = 0; i < cellGroupConfig->rlc_BearerToAddModList->list.count; i++) {
1122 1123
    asn1cCallocOne(cellGroupConfig->rlc_BearerToAddModList->list.array[i]->reestablishRLC,
                   NR_RLC_BearerConfig__reestablishRLC_true);
1124 1125
  }

1126
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, true);
1127 1128 1129
  NR_DRB_ToAddModList_t *DRBs = createDRBlist(ue_p, true);

  uint8_t buffer[RRC_BUF_SIZE] = {0};
1130
  int size = do_RRCReconfiguration(ue_p,
1131 1132 1133
                                   buffer,
                                   RRC_BUF_SIZE,
                                   new_xid,
laurent's avatar
laurent committed
1134
                                   SRBs,
1135
                                   DRBs,
1136 1137 1138 1139 1140
                                   NULL,
                                   NULL,
                                   NULL, // MeasObj_list,
                                   NULL,
                                   cellGroupConfig);
laurent's avatar
laurent committed
1141
  freeSRBlist(SRBs);
1142
  freeDRBlist(DRBs);
1143
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC, (char *)buffer, size, "[MSG] RRC Reconfiguration\n");
1144

1145 1146 1147 1148 1149 1150 1151
  AssertFatal(size > 0, "cannot encode RRC Reconfiguration\n");
  LOG_I(NR_RRC,
        "UE %d RNTI %04x: Generate NR_RRCReconfiguration after reestablishment complete (bytes %d)\n",
        ue_p->rrc_ue_id,
        ue_p->rnti,
        size);
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
1152
}
1153 1154
//-----------------------------------------------------------------------------

1155 1156
int nr_rrc_reconfiguration_req(rrc_gNB_ue_context_t         *const ue_context_pP,
                               protocol_ctxt_t              *const ctxt_pP,
1157 1158
                               const int                    dl_bwp_id,
                               const int                    ul_bwp_id) {
1159 1160

  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
1161
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
1162
  ue_p->xids[xid] = RRC_DEDICATED_RECONF;
1163

1164
  NR_CellGroupConfig_t *masterCellGroup = ue_p->masterCellGroup;
1165
  if (dl_bwp_id > 0) {
1166 1167 1168
    *masterCellGroup->spCellConfig->spCellConfigDedicated->firstActiveDownlinkBWP_Id = dl_bwp_id;
    *masterCellGroup->spCellConfig->spCellConfigDedicated->defaultDownlinkBWP_Id = dl_bwp_id;
  }
1169
  if (ul_bwp_id > 0) {
1170 1171
    *masterCellGroup->spCellConfig->spCellConfigDedicated->uplinkConfig->firstActiveUplinkBWP_Id = ul_bwp_id;
  }
1172

1173
  uint8_t buffer[RRC_BUF_SIZE];
1174
  int size = do_RRCReconfiguration(ue_p, buffer, RRC_BUF_SIZE, xid, NULL, NULL, NULL, NULL, NULL, NULL, masterCellGroup);
1175

1176
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
1177
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
luis_pereira87's avatar
luis_pereira87 committed
1178

1179 1180 1181
  return 0;
}

Robert Schmidt's avatar
Robert Schmidt committed
1182
static void rrc_handle_RRCSetupRequest(gNB_RRC_INST *rrc, sctp_assoc_t assoc_id, const NR_RRCSetupRequest_IEs_t *rrcSetupRequest, const f1ap_initial_ul_rrc_message_t *msg)
1183
{
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
  rrc_gNB_ue_context_t *ue_context_p = NULL;
  if (NR_InitialUE_Identity_PR_randomValue == rrcSetupRequest->ue_Identity.present) {
    /* randomValue                         BIT STRING (SIZE (39)) */
    if (rrcSetupRequest->ue_Identity.choice.randomValue.size != 5) { // 39-bit random value
      LOG_E(NR_RRC,
            "wrong InitialUE-Identity randomValue size, expected 5, provided %lu",
            (long unsigned int)rrcSetupRequest->ue_Identity.choice.randomValue.size);
      return;
    }
    uint64_t random_value = 0;
    memcpy(((uint8_t *)&random_value) + 3,
           rrcSetupRequest->ue_Identity.choice.randomValue.buf,
           rrcSetupRequest->ue_Identity.choice.randomValue.size);

    /* if there is already a registered UE (with another RNTI) with this random_value,
     * the current one must be removed from MAC/PHY (zombie UE)
     */
    if ((ue_context_p = rrc_gNB_ue_context_random_exist(rrc, random_value))) {
      LOG_W(NR_RRC, "new UE rnti (coming with random value) is already there, removing UE %x from MAC/PHY\n", msg->crnti);
      AssertFatal(false, "not implemented\n");
    }
1205

Robert Schmidt's avatar
Robert Schmidt committed
1206
    ue_context_p = rrc_gNB_create_ue_context(assoc_id, msg->crnti, rrc, random_value, msg->gNB_DU_ue_id);
1207 1208 1209 1210 1211 1212 1213 1214 1215
  } else if (NR_InitialUE_Identity_PR_ng_5G_S_TMSI_Part1 == rrcSetupRequest->ue_Identity.present) {
    /* <5G-S-TMSI> = <AMF Set ID><AMF Pointer><5G-TMSI> 48-bit */
    /* ng-5G-S-TMSI-Part1                  BIT STRING (SIZE (39)) */
    if (rrcSetupRequest->ue_Identity.choice.ng_5G_S_TMSI_Part1.size != 5) {
      LOG_E(NR_RRC,
            "wrong ng_5G_S_TMSI_Part1 size, expected 5, provided %lu \n",
            (long unsigned int)rrcSetupRequest->ue_Identity.choice.ng_5G_S_TMSI_Part1.size);
      return;
    }
1216

1217
    uint64_t s_tmsi_part1 = bitStr_to_uint64(&rrcSetupRequest->ue_Identity.choice.ng_5G_S_TMSI_Part1);
1218

1219 1220 1221
    // memcpy(((uint8_t *) & random_value) + 3,
    //         rrcSetupRequest->ue_Identity.choice.ng_5G_S_TMSI_Part1.buf,
    //         rrcSetupRequest->ue_Identity.choice.ng_5G_S_TMSI_Part1.size);
1222

1223 1224 1225 1226
    if ((ue_context_p = rrc_gNB_ue_context_5g_s_tmsi_exist(rrc, s_tmsi_part1))) {
      gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
      LOG_I(NR_RRC, " 5G-S-TMSI-Part1 exists, old rnti %04x => %04x\n", UE->rnti, msg->crnti);
      AssertFatal(false, "not implemented\n");
1227

1228 1229 1230 1231
      /* replace rnti in the context */
      UE->rnti = msg->crnti;
    } else {
      LOG_I(NR_RRC, "UE %04x 5G-S-TMSI-Part1 doesn't exist, setting ng_5G_S_TMSI_Part1 => %ld\n", msg->crnti, s_tmsi_part1);
1232

Robert Schmidt's avatar
Robert Schmidt committed
1233
      ue_context_p = rrc_gNB_create_ue_context(assoc_id, msg->crnti, rrc, s_tmsi_part1, msg->gNB_DU_ue_id);
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
      AssertFatal(ue_context_p != NULL, "out of memory\n");
      gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
      UE->Initialue_identity_5g_s_TMSI.presence = true;
      UE->ng_5G_S_TMSI_Part1 = s_tmsi_part1;
    }
  } else {
    uint64_t random_value = 0;
    memcpy(((uint8_t *)&random_value) + 3,
           rrcSetupRequest->ue_Identity.choice.randomValue.buf,
           rrcSetupRequest->ue_Identity.choice.randomValue.size);

Robert Schmidt's avatar
Robert Schmidt committed
1245
    ue_context_p = rrc_gNB_create_ue_context(assoc_id, msg->crnti, rrc, random_value, msg->gNB_DU_ue_id);
1246 1247 1248 1249
    LOG_E(NR_RRC, "RRCSetupRequest without random UE identity or S-TMSI not supported, let's reject the UE %04x\n", msg->crnti);
    rrc_gNB_generate_RRCReject(0, ue_context_p);
    return;
  }
yaojie's avatar
yaojie committed
1250

1251 1252 1253 1254 1255 1256
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
  UE = &ue_context_p->ue_context;
  UE->establishment_cause = rrcSetupRequest->establishmentCause;
  UE->Srb[1].Active = 1;
  rrc_gNB_generate_RRCSetup(0, msg->crnti, ue_context_p, msg->du2cu_rrc_container, msg->du2cu_rrc_container_length);
}
1257

1258
static const char *get_reestab_cause(NR_ReestablishmentCause_t c)
1259
{
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  switch (c) {
    case NR_ReestablishmentCause_otherFailure:
      return "Other Failure";
    case NR_ReestablishmentCause_handoverFailure:
      return "Handover Failure";
    case NR_ReestablishmentCause_reconfigurationFailure:
      return "Reconfiguration Failure";
    default:
      break;
  }
  return "UNKNOWN Failure (ASN.1 decoder error?)";
}
1272

1273 1274 1275 1276
static void rrc_handle_RRCReestablishmentRequest(gNB_RRC_INST *rrc, sctp_assoc_t assoc_id, const NR_RRCReestablishmentRequest_IEs_t *req, const f1ap_initial_ul_rrc_message_t *msg)
{
  uint64_t random_value = 0;
  const char *scause = get_reestab_cause(req->reestablishmentCause);
1277
  const long physCellId = req->ue_Identity.physCellId;
1278
  LOG_D(NR_RRC, "UE %04x physCellId %ld NR_RRCReestablishmentRequest cause %s\n", msg->crnti, physCellId, scause);
1279

1280 1281 1282 1283 1284
  const nr_rrc_du_container_t *du = get_du_by_assoc_id(rrc, assoc_id);
  if (du == NULL) {
    LOG_E(RRC, "received CCCH message, but no corresponding DU found\n");
    return;
  }
1285

1286 1287 1288 1289 1290
  if (du->mib == NULL || du->sib1 == NULL) {
    /* we don't have MIB/SIB1 of the DU, and therefore cannot generate the
     * Reestablishment (as we would need the SSB's ARFCN, which we cannot
     * compute). So generate RRC Setup instead */
    LOG_E(NR_RRC, "Reestablishment request: no MIB/SIB1 of DU present, cannot do reestablishment, force setup request\n");
1291
    goto fallback_rrc_setup;
1292 1293 1294 1295
  }

  rnti_t old_rnti = req->ue_Identity.c_RNTI;
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context_by_rnti(rrc, assoc_id, old_rnti);
1296 1297
  if (ue_context_p == NULL) {
    LOG_E(NR_RRC, "NR_RRCReestablishmentRequest without UE context, fallback to RRC setup\n");
1298
    goto fallback_rrc_setup;
1299
  }
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
  const f1ap_served_cell_info_t *cell_info = &du->setup_req->cell[0].info;
  if (physCellId != cell_info->nr_pci) {
    /* UE was moving from previous cell so quickly that RRCReestablishment for previous cell was received in this cell */
    LOG_I(NR_RRC,
          "RRC Reestablishment Request from different physCellId (%ld) than current physCellId (%d), fallback to RRC setup\n",
          physCellId,
          cell_info->nr_pci);
    /* 38.401 8.7: "If the UE accessed from a gNB-DU other than the original
     * one, the gNB-CU should trigger the UE Context Setup procedure". Let's
     * assume that the old DU will trigger a release request, also freeing the
     * ongoing context at the CU. Hence, create new below */
1312
    goto fallback_rrc_setup;
1313 1314
  }

1315
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1316 1317 1318 1319 1320 1321
  // 3GPP TS 38.321 version 15.13.0 Section 7.1 Table 7.1-1: RNTI values
  if (req->ue_Identity.c_RNTI < 0x1 || req->ue_Identity.c_RNTI > 0xffef) {
    /* c_RNTI range error should not happen */
    LOG_E(NR_RRC,
          "NR_RRCReestablishmentRequest c_RNTI %04lx range error, fallback to RRC setup\n",
          req->ue_Identity.c_RNTI);
1322
    goto fallback_rrc_setup;
1323
  }
1324

1325 1326 1327
  if (!UE->as_security_active) {
    /* no active security context, need to restart entire connection */
    LOG_E(NR_RRC, "UE requested Reestablishment without activated AS security\n");
1328
    goto fallback_rrc_setup;
1329 1330
  }

1331
  /* TODO: start timer in ITTI and drop UE if it does not come back */
1332

1333 1334 1335
  // update with new RNTI, and update secondary UE association
  UE->rnti = msg->crnti;
  cu_remove_f1_ue_data(UE->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
1336
  f1_ue_data_t ue_data = {.secondary_ue = msg->gNB_DU_ue_id, .du_assoc_id = assoc_id};
1337
  cu_add_f1_ue_data(UE->rrc_ue_id, &ue_data);
1338

1339
  LOG_I(NR_RRC, "Accept Reestablishment Request UE physCellId %ld cause %s\n", physCellId, scause);
1340

1341
  rrc_gNB_generate_RRCReestablishment(ue_context_p, msg->du2cu_rrc_container, old_rnti, du);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  return;

fallback_rrc_setup:
  fill_random(&random_value, sizeof(random_value));
  random_value = random_value & 0x7fffffffff; /* random value is 39 bits */

  rrc_gNB_ue_context_t *new = rrc_gNB_create_ue_context(assoc_id, msg->crnti, rrc, random_value, msg->gNB_DU_ue_id);
  new->ue_context.Srb[1].Active = 1;
  rrc_gNB_generate_RRCSetup(0, msg->crnti, new, msg->du2cu_rrc_container, msg->du2cu_rrc_container_length);
  return;
1352 1353
}

Xue Song's avatar
Xue Song committed
1354 1355 1356 1357 1358
/*! \fn uint64_t bitStr_to_uint64(BIT_STRING_t *)
 *\brief  This function extract at most a 64 bits value from a BIT_STRING_t object, the exact bits number depend on the BIT_STRING_t contents.
 *\param[in] pointer to the BIT_STRING_t object.
 *\return the extracted value.
 */
1359
static inline uint64_t bitStr_to_uint64(const BIT_STRING_t *asn) {
Xue Song's avatar
Xue Song committed
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  uint64_t result = 0;
  int index;
  int shift;

  DevCheck ((asn->size > 0) && (asn->size <= 8), asn->size, 0, 0);

  shift = ((asn->size - 1) * 8) - asn->bits_unused;
  for (index = 0; index < (asn->size - 1); index++) {
    result |= (uint64_t)asn->buf[index] << shift;
    shift -= 8;
  }

  result |= asn->buf[index] >> asn->bits_unused;

  return result;
}

Robert Schmidt's avatar
Robert Schmidt committed
1377
static void rrc_gNB_process_MeasurementReport(rrc_gNB_ue_context_t *ue_context, NR_MeasurementReport_t *measurementReport)
1378 1379 1380 1381 1382 1383 1384
{
  if (LOG_DEBUGFLAG(DEBUG_ASN1))
    xer_fprint(stdout, &asn_DEF_NR_MeasurementReport, (void *)measurementReport);

  DevAssert(measurementReport->criticalExtensions.present == NR_MeasurementReport__criticalExtensions_PR_measurementReport
            && measurementReport->criticalExtensions.choice.measurementReport != NULL);

1385
  gNB_RRC_UE_t *ue_ctxt = &ue_context->ue_context;
Robert Schmidt's avatar
Robert Schmidt committed
1386 1387
  ASN_STRUCT_FREE(asn_DEF_NR_MeasResults, ue_ctxt->measResults);
  ue_ctxt->measResults = NULL;
1388

1389 1390 1391
  const NR_MeasId_t id = measurementReport->criticalExtensions.choice.measurementReport->measResults.measId;
  AssertFatal(id, "unexpected MeasResult for MeasurementId %ld received\n", id);
  asn1cCallocOne(ue_ctxt->measResults, measurementReport->criticalExtensions.choice.measurementReport->measResults);
Robert Schmidt's avatar
Robert Schmidt committed
1392 1393 1394
  /* we "keep" the measurement report, so set to 0 */
  free(measurementReport->criticalExtensions.choice.measurementReport);
  measurementReport->criticalExtensions.choice.measurementReport = NULL;
1395 1396
}

1397
static int handle_rrcReestablishmentComplete(const protocol_ctxt_t *const ctxt_pP,
1398
                                             rrc_gNB_ue_context_t *ue_context_p,
1399 1400
                                             const NR_RRCReestablishmentComplete_t *reestablishment_complete)
{
1401 1402
  DevAssert(ue_context_p != NULL);
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

  DevAssert(reestablishment_complete->criticalExtensions.present
            == NR_RRCReestablishmentComplete__criticalExtensions_PR_rrcReestablishmentComplete);
  rrc_gNB_process_RRCReestablishmentComplete(ctxt_pP,
                                             ue_context_p,
                                             reestablishment_complete->rrc_TransactionIdentifier);

  UE->ue_reestablishment_counter++;
  return 0;
}

static int handle_ueCapabilityInformation(const protocol_ctxt_t *const ctxt_pP,
                                          rrc_gNB_ue_context_t *ue_context_p,
                                          const NR_UECapabilityInformation_t *ue_cap_info)
{
  AssertFatal(ue_context_p != NULL, "Processing %s() for UE %lx, ue_context_p is NULL\n", __func__, ctxt_pP->rntiMaybeUEid);
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;

  LOG_I(NR_RRC, "got UE capabilities for UE %lx\n", ctxt_pP->rntiMaybeUEid);
  int eutra_index = -1;

  if (ue_cap_info->criticalExtensions.present == NR_UECapabilityInformation__criticalExtensions_PR_ueCapabilityInformation) {
    const NR_UE_CapabilityRAT_ContainerList_t *ue_CapabilityRAT_ContainerList =
        ue_cap_info->criticalExtensions.choice.ueCapabilityInformation->ue_CapabilityRAT_ContainerList;
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438

    /* Encode UE-CapabilityRAT-ContainerList for sending to the DU */
    free(UE->ue_cap_buffer.buf);
    UE->ue_cap_buffer.len = uper_encode_to_new_buffer(&asn_DEF_NR_UE_CapabilityRAT_ContainerList,
                                                      NULL,
                                                      ue_CapabilityRAT_ContainerList,
                                                      (void **)&UE->ue_cap_buffer.buf);
    if (UE->ue_cap_buffer.len <= 0) {
      LOG_E(RRC, "could not encode UE-CapabilityRAT-ContainerList, abort handling capabilities\n");
      return -1;
    }

1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
    for (int i = 0; i < ue_CapabilityRAT_ContainerList->list.count; i++) {
      const NR_UE_CapabilityRAT_Container_t *ue_cap_container = ue_CapabilityRAT_ContainerList->list.array[i];
      if (ue_cap_container->rat_Type == NR_RAT_Type_nr) {
        if (UE->UE_Capability_nr) {
          ASN_STRUCT_FREE(asn_DEF_NR_UE_NR_Capability, UE->UE_Capability_nr);
          UE->UE_Capability_nr = 0;
        }

        asn_dec_rval_t dec_rval = uper_decode(NULL,
                                              &asn_DEF_NR_UE_NR_Capability,
                                              (void **)&UE->UE_Capability_nr,
                                              ue_cap_container->ue_CapabilityRAT_Container.buf,
                                              ue_cap_container->ue_CapabilityRAT_Container.size,
                                              0,
                                              0);
        if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
          xer_fprint(stdout, &asn_DEF_NR_UE_NR_Capability, UE->UE_Capability_nr);
        }

        if ((dec_rval.code != RC_OK) && (dec_rval.consumed == 0)) {
          LOG_E(NR_RRC,
                PROTOCOL_NR_RRC_CTXT_UE_FMT " Failed to decode nr UE capabilities (%zu bytes)\n",
                PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
                dec_rval.consumed);
          ASN_STRUCT_FREE(asn_DEF_NR_UE_NR_Capability, UE->UE_Capability_nr);
          UE->UE_Capability_nr = 0;
        }

        UE->UE_Capability_size = ue_cap_container->ue_CapabilityRAT_Container.size;
        if (eutra_index != -1) {
          LOG_E(NR_RRC, "fatal: more than 1 eutra capability\n");
          exit(1);
        }
        eutra_index = i;
      }

      if (ue_cap_container->rat_Type == NR_RAT_Type_eutra_nr) {
        if (UE->UE_Capability_MRDC) {
          ASN_STRUCT_FREE(asn_DEF_NR_UE_MRDC_Capability, UE->UE_Capability_MRDC);
          UE->UE_Capability_MRDC = 0;
        }
        asn_dec_rval_t dec_rval = uper_decode(NULL,
                                              &asn_DEF_NR_UE_MRDC_Capability,
                                              (void **)&UE->UE_Capability_MRDC,
                                              ue_cap_container->ue_CapabilityRAT_Container.buf,
                                              ue_cap_container->ue_CapabilityRAT_Container.size,
                                              0,
                                              0);

        if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
          xer_fprint(stdout, &asn_DEF_NR_UE_MRDC_Capability, UE->UE_Capability_MRDC);
        }

        if ((dec_rval.code != RC_OK) && (dec_rval.consumed == 0)) {
          LOG_E(NR_RRC,
                PROTOCOL_NR_RRC_CTXT_FMT " Failed to decode nr UE capabilities (%zu bytes)\n",
                PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
                dec_rval.consumed);
          ASN_STRUCT_FREE(asn_DEF_NR_UE_MRDC_Capability, UE->UE_Capability_MRDC);
          UE->UE_Capability_MRDC = 0;
        }
        UE->UE_MRDC_Capability_size = ue_cap_container->ue_CapabilityRAT_Container.size;
      }

      if (ue_cap_container->rat_Type == NR_RAT_Type_eutra) {
        // TODO
      }
    }

    if (eutra_index == -1)
      return -1;
  }

1512
  rrc_gNB_send_NGAP_UE_CAPABILITIES_IND(ctxt_pP, ue_context_p, ue_cap_info);
1513

1514 1515 1516 1517 1518 1519 1520
  // we send the UE capabilities request before RRC connection is complete,
  // so we cannot have a PDU session yet
  AssertFatal(UE->nb_of_pdusessions == 0, "logic bug: received capabilities while PDU session established\n");
  // TODO: send UE context modification response with UE capabilities to
  // allow DU configure CellGroupConfig
  rrc_gNB_generate_defaultRRCReconfiguration(ctxt_pP, ue_context_p);

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
  return 0;
}

static int handle_rrcSetupComplete(const protocol_ctxt_t *const ctxt_pP,
                                   rrc_gNB_ue_context_t *ue_context_p,
                                   const NR_RRCSetupComplete_t *setup_complete)
{
  if (!ue_context_p) {
    LOG_I(NR_RRC, "Processing NR_RRCSetupComplete UE %lx, ue_context_p is NULL\n", ctxt_pP->rntiMaybeUEid);
    return -1;
  }
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;

  NR_RRCSetupComplete_IEs_t *setup_complete_ies = setup_complete->criticalExtensions.choice.rrcSetupComplete;

  if (setup_complete_ies->ng_5G_S_TMSI_Value != NULL) {
    if (setup_complete_ies->ng_5G_S_TMSI_Value->present == NR_RRCSetupComplete_IEs__ng_5G_S_TMSI_Value_PR_ng_5G_S_TMSI_Part2) {
      if (setup_complete_ies->ng_5G_S_TMSI_Value->choice.ng_5G_S_TMSI_Part2.size != 2) {
        LOG_E(NR_RRC,
              "wrong ng_5G_S_TMSI_Part2 size, expected 2, provided %lu",
              (long unsigned int)
                  setup_complete->criticalExtensions.choice.rrcSetupComplete->ng_5G_S_TMSI_Value->choice.ng_5G_S_TMSI_Part2.size);
        return -1;
      }

      if (UE->ng_5G_S_TMSI_Part1 != 0) {
        UE->ng_5G_S_TMSI_Part2 = BIT_STRING_to_uint16(&setup_complete_ies->ng_5G_S_TMSI_Value->choice.ng_5G_S_TMSI_Part2);
      }

      /* TODO */
    } else if (setup_complete_ies->ng_5G_S_TMSI_Value->present == NR_RRCSetupComplete_IEs__ng_5G_S_TMSI_Value_PR_ng_5G_S_TMSI) {
      if (setup_complete_ies->ng_5G_S_TMSI_Value->choice.ng_5G_S_TMSI.size != 6) {
        LOG_E(NR_RRC,
              "wrong ng_5G_S_TMSI size, expected 6, provided %lu",
              (long unsigned int)setup_complete_ies->ng_5G_S_TMSI_Value->choice.ng_5G_S_TMSI.size);
        return -1;
      }

      uint64_t fiveg_s_TMSI = bitStr_to_uint64(&setup_complete_ies->ng_5G_S_TMSI_Value->choice.ng_5G_S_TMSI);
      LOG_I(NR_RRC,
            "Received rrcSetupComplete, 5g_s_TMSI: 0x%lX, amf_set_id: 0x%lX(%ld), amf_pointer: 0x%lX(%ld), 5g TMSI: 0x%X \n",
            fiveg_s_TMSI,
            fiveg_s_TMSI >> 38,
            fiveg_s_TMSI >> 38,
            (fiveg_s_TMSI >> 32) & 0x3F,
            (fiveg_s_TMSI >> 32) & 0x3F,
            (uint32_t)fiveg_s_TMSI);
      if (UE->Initialue_identity_5g_s_TMSI.presence) {
        UE->Initialue_identity_5g_s_TMSI.amf_set_id = fiveg_s_TMSI >> 38;
        UE->Initialue_identity_5g_s_TMSI.amf_pointer = (fiveg_s_TMSI >> 32) & 0x3F;
        UE->Initialue_identity_5g_s_TMSI.fiveg_tmsi = (uint32_t)fiveg_s_TMSI;
      }
    }
  }

  rrc_gNB_process_RRCSetupComplete(ctxt_pP, ue_context_p, setup_complete->criticalExtensions.choice.rrcSetupComplete);
  LOG_I(NR_RRC, PROTOCOL_NR_RRC_CTXT_UE_FMT " UE State = NR_RRC_CONNECTED \n", PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP));
  return 0;
}

static void handle_rrcReconfigurationComplete(const protocol_ctxt_t *const ctxt_pP,
                                              rrc_gNB_ue_context_t *ue_context_p,
                                              const NR_RRCReconfigurationComplete_t *reconfig_complete)
{
  LOG_I(NR_RRC, "Receive RRC Reconfiguration Complete message UE %lx\n", ctxt_pP->rntiMaybeUEid);
  AssertFatal(ue_context_p != NULL, "Processing %s() for UE %lx, ue_context_p is NULL\n", __func__, ctxt_pP->rntiMaybeUEid);
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;

  uint8_t xid = reconfig_complete->rrc_TransactionIdentifier;
  rrc_gNB_process_RRCReconfigurationComplete(ctxt_pP, ue_context_p, xid);

1592
  bool successful_reconfig = true;
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
  switch (UE->xids[xid]) {
    case RRC_PDUSESSION_RELEASE: {
      gtpv1u_gnb_delete_tunnel_req_t req = {0};
      gtpv1u_delete_ngu_tunnel(ctxt_pP->instance, &req);
      // NGAP_PDUSESSION_RELEASE_RESPONSE
      rrc_gNB_send_NGAP_PDUSESSION_RELEASE_RESPONSE(ctxt_pP, ue_context_p, xid);
    } break;
    case RRC_PDUSESSION_ESTABLISH:
      if (UE->nb_of_pdusessions > 0)
        rrc_gNB_send_NGAP_PDUSESSION_SETUP_RESP(ctxt_pP, ue_context_p, xid);
      break;
    case RRC_PDUSESSION_MODIFY:
      rrc_gNB_send_NGAP_PDUSESSION_MODIFY_RESP(ctxt_pP, ue_context_p, xid);
      break;
    case RRC_DEFAULT_RECONF:
      rrc_gNB_send_NGAP_INITIAL_CONTEXT_SETUP_RESP(ctxt_pP, ue_context_p);
      break;
    case RRC_REESTABLISH_COMPLETE:
    case RRC_DEDICATED_RECONF:
      /* do nothing */
      break;
    default:
      LOG_E(RRC, "Received unexpected transaction type %d for xid %d\n", UE->xids[xid], xid);
      successful_reconfig = false;
      break;
1618
  }
1619 1620

  gNB_RRC_INST *rrc = RC.nrrrc[0];
1621
  f1_ue_data_t ue_data = cu_get_f1_ue_data(UE->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
1622
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
1623
  f1ap_ue_context_modif_req_t ue_context_modif_req = {
1624
    .gNB_CU_ue_id = UE->rrc_ue_id,
1625
    .gNB_DU_ue_id = ue_data.secondary_ue,
1626 1627 1628
    .plmn.mcc = rrc->configuration.mcc[0],
    .plmn.mnc = rrc->configuration.mnc[0],
    .plmn.mnc_digit_length = rrc->configuration.mnc_digit_length[0],
1629 1630 1631 1632
    .nr_cellid = rrc->nr_cellid,
    .servCellId = 0, /* TODO: correct value? */
    .ReconfigComplOutcome = successful_reconfig ? RRCreconf_success : RRCreconf_failure,
  };
Robert Schmidt's avatar
Robert Schmidt committed
1633
  rrc->mac_rrc.ue_context_modification_request(ue_data.du_assoc_id, &ue_context_modif_req);
1634
}
Xue Song's avatar
Xue Song committed
1635
//-----------------------------------------------------------------------------
1636 1637 1638 1639
int rrc_gNB_decode_dcch(const protocol_ctxt_t *const ctxt_pP,
                        const rb_id_t Srb_id,
                        const uint8_t *const Rx_sdu,
                        const sdu_size_t sdu_sizeP)
Xue Song's avatar
Xue Song committed
1640 1641
//-----------------------------------------------------------------------------
{
1642
  gNB_RRC_INST *gnb_rrc_inst = RC.nrrrc[ctxt_pP->module_id];
Xue Song's avatar
Xue Song committed
1643

1644 1645 1646 1647 1648 1649 1650
  /* we look up by CU UE ID! Do NOT change back to RNTI! */
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(gnb_rrc_inst, ctxt_pP->rntiMaybeUEid);
  if (!ue_context_p) {
    LOG_E(RRC, "could not find UE context for CU UE ID %lu, aborting transaction\n", ctxt_pP->rntiMaybeUEid);
    return -1;
  }

1651
  if ((Srb_id != 1) && (Srb_id != 2)) {
1652
    LOG_E(NR_RRC, "Received message on SRB%ld, should not have ...\n", Srb_id);
1653
  } else {
1654
    LOG_D(NR_RRC, "Received message on SRB%ld\n", Srb_id);
1655 1656
  }

1657
  LOG_D(NR_RRC, "Decoding UL-DCCH Message\n");
1658
  {
1659
    for (int i = 0; i < sdu_sizeP; i++) {
1660
      LOG_T(NR_RRC, "%x.", Rx_sdu[i]);
Xue Song's avatar
Xue Song committed
1661 1662
    }

1663 1664
    LOG_T(NR_RRC, "\n");
  }
Xue Song's avatar
Xue Song committed
1665

1666 1667 1668
  NR_UL_DCCH_Message_t *ul_dcch_msg = NULL;
  asn_dec_rval_t dec_rval = uper_decode(NULL, &asn_DEF_NR_UL_DCCH_Message, (void **)&ul_dcch_msg, Rx_sdu, sdu_sizeP, 0, 0);

1669
  if ((dec_rval.code != RC_OK) && (dec_rval.consumed == 0)) {
1670
    LOG_E(NR_RRC, "Failed to decode UL-DCCH (%zu bytes)\n", dec_rval.consumed);
1671 1672 1673
    return -1;
  }

1674 1675 1676 1677
  if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
    xer_fprint(stdout, &asn_DEF_NR_UL_DCCH_Message, (void *)ul_dcch_msg);
  }

1678 1679 1680
  if (ul_dcch_msg->message.present == NR_UL_DCCH_MessageType_PR_c1) {
    switch (ul_dcch_msg->message.choice.c1->present) {
      case NR_UL_DCCH_MessageType__c1_PR_NOTHING:
1681
        LOG_I(NR_RRC, "Received PR_NOTHING on UL-DCCH-Message\n");
1682
        break;
Xue Song's avatar
Xue Song committed
1683

1684
      case NR_UL_DCCH_MessageType__c1_PR_rrcReconfigurationComplete:
1685
        handle_rrcReconfigurationComplete(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.rrcReconfigurationComplete);
1686 1687 1688
        break;

      case NR_UL_DCCH_MessageType__c1_PR_rrcSetupComplete:
1689 1690
        if (handle_rrcSetupComplete(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.rrcSetupComplete) == -1)
          return -1;
1691
        break;
wujing's avatar
wujing committed
1692

1693 1694 1695 1696 1697 1698 1699 1700
      case NR_UL_DCCH_MessageType__c1_PR_measurementReport:
        DevAssert(ul_dcch_msg != NULL
                  && ul_dcch_msg->message.present == NR_UL_DCCH_MessageType_PR_c1
                  && ul_dcch_msg->message.choice.c1
                  && ul_dcch_msg->message.choice.c1->present == NR_UL_DCCH_MessageType__c1_PR_measurementReport);
        rrc_gNB_process_MeasurementReport(ue_context_p, ul_dcch_msg->message.choice.c1->choice.measurementReport);
        break;

1701
      case NR_UL_DCCH_MessageType__c1_PR_ulInformationTransfer:
Robert Schmidt's avatar
Robert Schmidt committed
1702
        LOG_D(NR_RRC, "Recived RRC GNB UL Information Transfer \n");
1703
        if (!ue_context_p) {
Robert Schmidt's avatar
Robert Schmidt committed
1704
          LOG_W(NR_RRC, "Processing ulInformationTransfer UE %lx, ue_context_p is NULL\n", ctxt_pP->rntiMaybeUEid);
1705 1706
          break;
        }
wujing's avatar
wujing committed
1707

1708 1709
        LOG_D(NR_RRC, "[MSG] RRC UL Information Transfer \n");
        LOG_DUMPMSG(RRC, DEBUG_RRC, (char *)Rx_sdu, sdu_sizeP, "[MSG] RRC UL Information Transfer \n");
wujing's avatar
wujing committed
1710

1711
        rrc_gNB_send_NGAP_UPLINK_NAS(ctxt_pP, ue_context_p, ul_dcch_msg);
1712
        break;
wujing's avatar
wujing committed
1713

1714
      case NR_UL_DCCH_MessageType__c1_PR_securityModeComplete:
1715
        // to avoid segmentation fault
1716 1717 1718 1719
        if (!ue_context_p) {
          LOG_I(NR_RRC, "Processing securityModeComplete UE %lx, ue_context_p is NULL\n", ctxt_pP->rntiMaybeUEid);
          break;
        }
1720 1721

        LOG_I(NR_RRC,
1722
              PROTOCOL_NR_RRC_CTXT_UE_FMT " received securityModeComplete on UL-DCCH %d from UE\n",
1723 1724 1725
              PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
              DCCH);
        LOG_D(NR_RRC,
1726 1727
              PROTOCOL_NR_RRC_CTXT_UE_FMT
              " RLC RB %02d --- RLC_DATA_IND %d bytes "
1728 1729 1730 1731 1732
              "(securityModeComplete) ---> RRC_eNB\n",
              PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
              DCCH,
              sdu_sizeP);

1733
        if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
1734 1735 1736
          xer_fprint(stdout, &asn_DEF_NR_UL_DCCH_Message, (void *)ul_dcch_msg);
        }

Cedric Roux's avatar
Cedric Roux committed
1737 1738
        /* configure ciphering */
        nr_rrc_pdcp_config_security(ctxt_pP, ue_context_p, 1);
1739
        ue_context_p->ue_context.as_security_active = true;
Cedric Roux's avatar
Cedric Roux committed
1740

1741 1742 1743
        rrc_gNB_generate_UECapabilityEnquiry(ctxt_pP, ue_context_p);
        break;

1744 1745 1746 1747 1748 1749 1750 1751 1752
      case NR_UL_DCCH_MessageType__c1_PR_securityModeFailure:
        LOG_DUMPMSG(NR_RRC, DEBUG_RRC, (char *)Rx_sdu, sdu_sizeP, "[MSG] NR RRC Security Mode Failure\n");
        LOG_W(NR_RRC,
              PROTOCOL_RRC_CTXT_UE_FMT
              " RLC RB %02d --- RLC_DATA_IND %d bytes "
              "(securityModeFailure) ---> RRC_gNB\n",
              PROTOCOL_RRC_CTXT_UE_ARGS(ctxt_pP),
              DCCH,
              sdu_sizeP);
1753

1754 1755
        if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
          xer_fprint(stdout, &asn_DEF_NR_UL_DCCH_Message, (void *)ul_dcch_msg);
1756 1757
        }

1758 1759
        rrc_gNB_generate_UECapabilityEnquiry(ctxt_pP, ue_context_p);
        break;
1760

1761 1762 1763 1764 1765
      case NR_UL_DCCH_MessageType__c1_PR_ueCapabilityInformation:
        if (handle_ueCapabilityInformation(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.ueCapabilityInformation)
            == -1)
          return -1;
        break;
1766

1767
      case NR_UL_DCCH_MessageType__c1_PR_rrcReestablishmentComplete:
1768
        if (handle_rrcReestablishmentComplete(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.rrcReestablishmentComplete)
1769 1770 1771
            == -1)
          return -1;
        break;
1772

1773 1774
      default:
        break;
Xue Song's avatar
Xue Song committed
1775
    }
1776
  }
1777
  ASN_STRUCT_FREE(asn_DEF_NR_UL_DCCH_Message, ul_dcch_msg);
1778
  return 0;
Xue Song's avatar
Xue Song committed
1779 1780
}

Robert Schmidt's avatar
Robert Schmidt committed
1781
void rrc_gNB_process_initial_ul_rrc_message(sctp_assoc_t assoc_id, const f1ap_initial_ul_rrc_message_t *ul_rrc)
1782
{
Robert Schmidt's avatar
Robert Schmidt committed
1783
  AssertFatal(assoc_id != 0, "illegal assoc_id == 0: should be -1 (monolithic) or >0 (split)\n");
1784

1785
  gNB_RRC_INST *rrc = RC.nrrrc[0];
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
  LOG_I(NR_RRC, "Decoding CCCH: RNTI %04x, payload_size %d\n", ul_rrc->crnti, ul_rrc->rrc_container_length);
  NR_UL_CCCH_Message_t *ul_ccch_msg = NULL;
  asn_dec_rval_t dec_rval = uper_decode(NULL,
                                        &asn_DEF_NR_UL_CCCH_Message,
                                        (void **)&ul_ccch_msg,
                                        ul_rrc->rrc_container,
                                        ul_rrc->rrc_container_length,
                                        0,
                                        0);
  if (dec_rval.code != RC_OK || dec_rval.consumed == 0) {
    LOG_E(NR_RRC, " FATAL Error in receiving CCCH\n");
1797 1798
    return;
  }
1799

1800 1801 1802 1803 1804
  if (ul_ccch_msg->message.present == NR_UL_CCCH_MessageType_PR_c1) {
    switch (ul_ccch_msg->message.choice.c1->present) {
      case NR_UL_CCCH_MessageType__c1_PR_NOTHING:
        LOG_W(NR_RRC, "Received PR_NOTHING on UL-CCCH-Message, ignoring message\n");
        break;
Robert Schmidt's avatar
Robert Schmidt committed
1805

1806 1807
      case NR_UL_CCCH_MessageType__c1_PR_rrcSetupRequest:
        LOG_D(NR_RRC, "Received RRCSetupRequest on UL-CCCH-Message (UE rnti %04x)\n", ul_rrc->crnti);
Robert Schmidt's avatar
Robert Schmidt committed
1808
        rrc_handle_RRCSetupRequest(rrc, assoc_id, &ul_ccch_msg->message.choice.c1->choice.rrcSetupRequest->rrcSetupRequest, ul_rrc);
1809
        break;
1810

1811 1812 1813
      case NR_UL_CCCH_MessageType__c1_PR_rrcResumeRequest:
        LOG_E(NR_RRC, "Received rrcResumeRequest message, but handling is not implemented\n");
        break;
Xue Song's avatar
Xue Song committed
1814

1815 1816 1817 1818
      case NR_UL_CCCH_MessageType__c1_PR_rrcReestablishmentRequest: {
        LOG_D(NR_RRC, "Received RRCReestablishmentRequest on UL-CCCH-Message (UE RNTI %04x)\n", ul_rrc->crnti);
        rrc_handle_RRCReestablishmentRequest(
            rrc,
Robert Schmidt's avatar
Robert Schmidt committed
1819
            assoc_id,
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
            &ul_ccch_msg->message.choice.c1->choice.rrcReestablishmentRequest->rrcReestablishmentRequest,
            ul_rrc);
      } break;

      case NR_UL_CCCH_MessageType__c1_PR_rrcSystemInfoRequest:
        LOG_I(NR_RRC, "UE %04x receive rrcSystemInfoRequest message \n", ul_rrc->crnti);
        /* TODO */
        break;

      default:
        LOG_E(NR_RRC, "UE %04x Unknown message\n", ul_rrc->crnti);
        break;
    }
1833
  }
1834
  ASN_STRUCT_FREE(asn_DEF_NR_UL_CCCH_Message, ul_ccch_msg);
1835 1836 1837 1838 1839 1840 1841

  if (ul_rrc->rrc_container)
    free(ul_rrc->rrc_container);
  if (ul_rrc->du2cu_rrc_container)
    free(ul_rrc->du2cu_rrc_container);
}

Cedric Roux's avatar
Cedric Roux committed
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
void rrc_gNB_process_release_request(const module_id_t gnb_mod_idP, x2ap_ENDC_sgnb_release_request_t *m)
{
  gNB_RRC_INST *rrc = RC.nrrrc[gnb_mod_idP];
  rrc_remove_nsa_user(rrc, m->rnti);
}

void rrc_gNB_process_dc_overall_timeout(const module_id_t gnb_mod_idP, x2ap_ENDC_dc_overall_timeout_t *m)
{
  gNB_RRC_INST *rrc = RC.nrrrc[gnb_mod_idP];
  rrc_remove_nsa_user(rrc, m->rnti);
}

laurent's avatar
tmp  
laurent committed
1854 1855
static void rrc_CU_process_ue_context_setup_response(MessageDef *msg_p, instance_t instance)
{
1856
  f1ap_ue_context_setup_t *resp = &F1AP_UE_CONTEXT_SETUP_RESP(msg_p);
1857
  gNB_RRC_INST *rrc = RC.nrrrc[instance];
1858 1859 1860 1861 1862
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, resp->gNB_CU_ue_id);
  if (!ue_context_p) {
    LOG_E(RRC, "could not find UE context for CU UE ID %u, aborting transaction\n", resp->gNB_CU_ue_id);
    return;
  }
1863
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1864

1865 1866 1867 1868 1869 1870 1871
  NR_CellGroupConfig_t *cellGroupConfig = NULL;
  asn_dec_rval_t dec_rval = uper_decode_complete(NULL,
                                                 &asn_DEF_NR_CellGroupConfig,
                                                 (void **)&cellGroupConfig,
                                                 (uint8_t *)resp->du_to_cu_rrc_information->cellGroupConfig,
                                                 resp->du_to_cu_rrc_information->cellGroupConfig_length);
  AssertFatal(dec_rval.code == RC_OK && dec_rval.consumed > 0, "Cell group config decode error\n");
1872

1873 1874 1875
  if (UE->masterCellGroup) {
    ASN_STRUCT_FREE(asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);
    LOG_I(RRC, "UE %04x replacing existing CellGroupConfig with new one received from DU\n", UE->rnti);
1876
  }
1877 1878
  UE->masterCellGroup = cellGroupConfig;
  if (LOG_DEBUGFLAG(DEBUG_ASN1))
1879
    xer_fprint(stdout, &asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);
1880

1881 1882 1883
  /* at this point, we don't have to do anything: the UE context setup request
   * includes the Security Command, whose response will trigger the following
   * messages (UE capability, to be specific) */
1884 1885
}

1886 1887 1888 1889 1890
static void rrc_CU_process_ue_context_release_request(MessageDef *msg_p)
{
  const int instance = 0;
  f1ap_ue_context_release_req_t *req = &F1AP_UE_CONTEXT_RELEASE_REQ(msg_p);
  gNB_RRC_INST *rrc = RC.nrrrc[instance];
1891 1892 1893 1894 1895
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, req->gNB_CU_ue_id);
  if (!ue_context_p) {
    LOG_E(RRC, "could not find UE context for CU UE ID %u, aborting transaction\n", req->gNB_CU_ue_id);
    return;
  }
1896 1897

  /* TODO: marshall types correctly */
1898
  LOG_I(NR_RRC, "received UE Context Release Request for UE %u, forwarding to AMF\n", req->gNB_CU_ue_id);
1899 1900 1901 1902 1903 1904
  rrc_gNB_send_NGAP_UE_CONTEXT_RELEASE_REQ(instance,
                                           ue_context_p,
                                           NGAP_CAUSE_RADIO_NETWORK,
                                           NGAP_CAUSE_RADIO_NETWORK_RADIO_CONNECTION_WITH_UE_LOST);
}

Robert Schmidt's avatar
Robert Schmidt committed
1905 1906 1907 1908 1909 1910 1911
static void rrc_delete_ue_data(gNB_RRC_UE_t *UE)
{
  ASN_STRUCT_FREE(asn_DEF_NR_UE_NR_Capability, UE->UE_Capability_nr);
  ASN_STRUCT_FREE(asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);
  ASN_STRUCT_FREE(asn_DEF_NR_MeasResults, UE->measResults);
}

1912 1913 1914 1915 1916
static void rrc_CU_process_ue_context_release_complete(MessageDef *msg_p)
{
  const int instance = 0;
  f1ap_ue_context_release_complete_t *complete = &F1AP_UE_CONTEXT_RELEASE_COMPLETE(msg_p);
  gNB_RRC_INST *rrc = RC.nrrrc[instance];
1917 1918 1919 1920 1921
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, complete->gNB_CU_ue_id);
  if (!ue_context_p) {
    LOG_E(RRC, "could not find UE context for CU UE ID %u, aborting transaction\n", complete->gNB_CU_ue_id);
    return;
  }
1922 1923
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;

1924 1925 1926 1927
  /* we call nr_pdcp_remove_UE() in the handler of E1 bearer release, but if we
   * are in E1, we also need to free the UE in the CU-CP, so call it twice to
   * cover all cases */
  nr_pdcp_remove_UE(UE->rrc_ue_id);
1928
  rrc_gNB_send_NGAP_UE_CONTEXT_RELEASE_COMPLETE(instance, UE->rrc_ue_id);
1929
  LOG_I(NR_RRC, "removed UE CU UE ID %u/RNTI %04x \n", UE->rrc_ue_id, UE->rnti);
Robert Schmidt's avatar
Robert Schmidt committed
1930
  rrc_delete_ue_data(UE);
1931 1932 1933
  rrc_gNB_remove_ue_context(rrc, ue_context_p);
}

laurent's avatar
tmp  
laurent committed
1934 1935
static void rrc_CU_process_ue_context_modification_response(MessageDef *msg_p, instance_t instance)
{
1936
  f1ap_ue_context_modif_resp_t *resp = &F1AP_UE_CONTEXT_MODIFICATION_RESP(msg_p);
1937
  protocol_ctxt_t ctxt = {.rntiMaybeUEid = resp->gNB_CU_ue_id, .module_id = instance, .instance = instance, .enb_flag = 1, .eNB_index = instance};
1938
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt.module_id];
1939 1940 1941 1942 1943
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, resp->gNB_CU_ue_id);
  if (!ue_context_p) {
    LOG_E(RRC, "could not find UE context for CU UE ID %u, aborting transaction\n", resp->gNB_CU_ue_id);
    return;
  }
1944
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1945

1946 1947
  if (resp->drbs_to_be_setup_length > 0) {
    e1ap_bearer_setup_req_t req = {0};
1948 1949
    // TODO: bug: we receive the DRBs, but we don't associate to a PDU session
    // -> we are not sure which PDU session this is, and fill "all"
1950
    req.numPDUSessionsMod = UE->nb_of_pdusessions;
1951
    req.gNB_cu_cp_ue_id = UE->rrc_ue_id;
1952
    req.gNB_cu_up_ue_id = UE->rrc_ue_id;
1953
    for (int i = 0; i < req.numPDUSessionsMod; i++) {
1954
      req.pduSessionMod[i].sessionId = UE->pduSession[i].param.pdusession_id;
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
      req.pduSessionMod[i].numDRB2Modify = resp->drbs_to_be_setup_length;
      for (int j = 0; j < resp->drbs_to_be_setup_length; j++) {
        f1ap_drb_to_be_setup_t *drb_f1 = resp->drbs_to_be_setup + j;
        DRB_nGRAN_to_setup_t *drb_e1 = req.pduSessionMod[i].DRBnGRanModList + j;

        drb_e1->id = drb_f1->drb_id;
        drb_e1->numDlUpParam = drb_f1->up_dl_tnl_length;
        drb_e1->DlUpParamList[0].tlAddress = drb_f1->up_dl_tnl[0].tl_address;
        drb_e1->DlUpParamList[0].teId = drb_f1->up_dl_tnl[0].teid;
      }
1965
    }
1966

1967 1968
    // send the F1 response message up to update F1-U tunnel info
    // it seems the rrc transaction id (xid) is not needed here
1969 1970
    sctp_assoc_t assoc_id = get_existing_cuup_for_ue(rrc, UE);
    rrc->cucp_cuup.bearer_context_mod(assoc_id, &req);
1971
  }
1972

1973 1974 1975 1976 1977 1978 1979 1980
  if (resp->du_to_cu_rrc_information != NULL && resp->du_to_cu_rrc_information->cellGroupConfig != NULL) {
    NR_CellGroupConfig_t *cellGroupConfig = NULL;
    asn_dec_rval_t dec_rval = uper_decode_complete(NULL,
                                                   &asn_DEF_NR_CellGroupConfig,
                                                   (void **)&cellGroupConfig,
                                                   (uint8_t *)resp->du_to_cu_rrc_information->cellGroupConfig,
                                                   resp->du_to_cu_rrc_information->cellGroupConfig_length);
    AssertFatal(dec_rval.code == RC_OK && dec_rval.consumed > 0, "Cell group config decode error\n");
matzakos's avatar
matzakos committed
1981

1982 1983 1984
    if (UE->masterCellGroup) {
      ASN_STRUCT_FREE(asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);
      LOG_I(RRC, "UE %04x replacing existing CellGroupConfig with new one received from DU\n", UE->rnti);
1985
    }
1986
    UE->masterCellGroup = cellGroupConfig;
1987

1988
    rrc_gNB_generate_dedicatedRRCReconfiguration(&ctxt, ue_context_p);
1989
  }
1990 1991
}

1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
static void rrc_CU_process_ue_modification_required(MessageDef *msg_p)
{
  f1ap_ue_context_modif_required_t *required = &F1AP_UE_CONTEXT_MODIFICATION_REQUIRED(msg_p);
  protocol_ctxt_t ctxt = {.rntiMaybeUEid = required->gNB_CU_ue_id, .module_id = 0, .instance = 0, .enb_flag = 1, .eNB_index = 0};
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt.module_id];
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, required->gNB_CU_ue_id);
  if (ue_context_p == NULL) {
    LOG_E(RRC, "Could not find UE context for CU UE ID %d, cannot handle UE context modification request\n", required->gNB_CU_ue_id);
    f1ap_ue_context_modif_refuse_t refuse = {
      .gNB_CU_ue_id = required->gNB_CU_ue_id,
      .gNB_DU_ue_id = required->gNB_DU_ue_id,
      .cause = F1AP_CAUSE_RADIO_NETWORK,
      .cause_value = F1AP_CauseRadioNetwork_unknown_or_already_allocated_gnb_cu_ue_f1ap_id,
    };
Robert Schmidt's avatar
Robert Schmidt committed
2006
    rrc->mac_rrc.ue_context_modification_refuse(msg_p->ittiMsgHeader.originInstance, &refuse);
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
    return;
  }

  if (required->du_to_cu_rrc_information && required->du_to_cu_rrc_information->cellGroupConfig) {
    gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
    LOG_I(RRC,
          "UE Context Modification Required: new CellGroupConfig for UE ID %d/RNTI %04x, triggering reconfiguration\n",
          UE->rrc_ue_id,
          UE->rnti);

    NR_CellGroupConfig_t *cellGroupConfig = NULL;
    asn_dec_rval_t dec_rval = uper_decode_complete(NULL,
                                                   &asn_DEF_NR_CellGroupConfig,
                                                   (void **)&cellGroupConfig,
                                                   (uint8_t *)required->du_to_cu_rrc_information->cellGroupConfig,
                                                   required->du_to_cu_rrc_information->cellGroupConfig_length);
    if (dec_rval.code != RC_OK && dec_rval.consumed == 0) {
      LOG_E(RRC, "Cell group config decode error, refusing reconfiguration\n");
      f1ap_ue_context_modif_refuse_t refuse = {
        .gNB_CU_ue_id = required->gNB_CU_ue_id,
        .gNB_DU_ue_id = required->gNB_DU_ue_id,
        .cause = F1AP_CAUSE_PROTOCOL,
        .cause_value = F1AP_CauseProtocol_transfer_syntax_error,
      };
Robert Schmidt's avatar
Robert Schmidt committed
2031
      rrc->mac_rrc.ue_context_modification_refuse(msg_p->ittiMsgHeader.originInstance, &refuse);
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
      return;
    }

    if (UE->masterCellGroup) {
      ASN_STRUCT_FREE(asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);
      LOG_I(RRC, "UE %d/RNTI %04x replacing existing CellGroupConfig with new one received from DU\n", UE->rrc_ue_id, UE->rnti);
    }
    UE->masterCellGroup = cellGroupConfig;
    if (LOG_DEBUGFLAG(DEBUG_ASN1))
      xer_fprint(stdout, &asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);

    /* trigger reconfiguration */
    nr_rrc_reconfiguration_req(ue_context_p, &ctxt, 0, 0);
    //rrc_gNB_generate_dedicatedRRCReconfiguration(&ctxt, ue_context_p);
    //rrc_gNB_generate_defaultRRCReconfiguration(&ctxt, ue_context_p);
    return;
  }
  LOG_W(RRC,
        "nothing to be done after UE Context Modification Required for UE ID %d/RNTI %04x\n",
        required->gNB_CU_ue_id,
        required->gNB_DU_ue_id);
}

2055 2056 2057 2058
unsigned int mask_flip(unsigned int x) {
  return((((x>>8) + (x<<8))&0xffff)>>6);
}

2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
static pdusession_level_qos_parameter_t *get_qos_characteristics(const int qfi, rrc_pdu_session_param_t *pduSession)
{
  pdusession_t *pdu = &pduSession->param;
  for (int i = 0; i < pdu->nb_qos; i++) {
    if (qfi == pdu->qos[i].qfi)
      return &pdu->qos[i];
  }
  AssertFatal(1 == 0, "The pdu session %d does not contain a qos flow with qfi = %d\n", pdu->pdusession_id, qfi);
  return NULL;
}

2070
/**
2071
 * @brief E1AP Bearer Context Setup Response processing on CU-CP
2072
*/
2073
void rrc_gNB_process_e1_bearer_context_setup_resp(e1ap_bearer_setup_resp_t *resp, instance_t instance)
2074 2075
{
  gNB_RRC_INST *rrc = RC.nrrrc[0];
2076 2077
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, resp->gNB_cu_cp_ue_id);
  AssertFatal(ue_context_p != NULL, "did not find UE with CU UE ID %d\n", resp->gNB_cu_cp_ue_id);
2078
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
2079

2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
  // currently: we don't have "infrastructure" to save the CU-UP UE ID, so we
  // assume (and below check) that CU-UP UE ID == CU-CP UE ID
  AssertFatal(resp->gNB_cu_cp_ue_id == resp->gNB_cu_up_ue_id,
              "cannot handle CU-UP UE ID different from CU-CP UE ID (%d vs %d)\n",
              resp->gNB_cu_cp_ue_id,
              resp->gNB_cu_up_ue_id);

  // save the tunnel address for the PDU sessions
  for (int i=0; i < resp->numPDUSessions; i++) {
    pdu_session_setup_t *e1_pdu = &resp->pduSession[i];
    rrc_pdu_session_param_t *rrc_pdu = find_pduSession(UE, e1_pdu->id, false);
    if (rrc_pdu == NULL) {
      LOG_W(RRC, "E1: received setup for PDU session %ld, but has not been requested\n", e1_pdu->id);
      continue;
    }
    rrc_pdu->param.gNB_teid_N3 = e1_pdu->teId;
    memcpy(&rrc_pdu->param.gNB_addr_N3.buffer, &e1_pdu->tlAddress, sizeof(uint8_t) * 4);
    rrc_pdu->param.gNB_addr_N3.length = sizeof(in_addr_t);
  }

2100
  /* Instruction towards the DU for DRB configuration and tunnel creation */
2101
  int nb_drb = resp->pduSession[0].numDRBSetup;
2102
  f1ap_drb_to_be_setup_t drbs[nb_drb];
2103
  rrc_pdu_session_param_t *RRC_pduSession = find_pduSession(UE, resp->pduSession[0].id, false);
2104
  DevAssert(RRC_pduSession);
2105
  for (int i = 0; i < nb_drb; i++) {
2106
    DRB_nGRAN_setup_t *drb_config = &resp->pduSession[0].DRBnGRanList[i];
2107
    drbs[i].drb_id = resp->pduSession[0].DRBnGRanList[i].id;
2108
    drbs[i].rlc_mode = rrc->configuration.um_on_default_drb ? RLC_MODE_UM : RLC_MODE_AM;
2109
    drbs[i].up_ul_tnl[0].tl_address = drb_config->UpParamList[0].tlAddress;
2110
    drbs[i].up_ul_tnl[0].port = rrc->eth_params_s.my_portd;
2111
    drbs[i].up_ul_tnl[0].teid = drb_config->UpParamList[0].teId;
2112
    drbs[i].up_ul_tnl_length = 1;
2113 2114 2115

    /* pass QoS info to MAC */
    int nb_qos_flows = drb_config->numQosFlowSetup;
2116
    AssertFatal(nb_qos_flows > 0, "must map at least one flow to a DRB\n");
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
    drbs[i].drb_info.flows_to_be_setup_length = nb_qos_flows;
    drbs[i].drb_info.flows_mapped_to_drb = (f1ap_flows_mapped_to_drb_t *)calloc(nb_qos_flows, sizeof(f1ap_flows_mapped_to_drb_t));
    AssertFatal(drbs[i].drb_info.flows_mapped_to_drb, "could not allocate memory\n");
    for (int j = 0; j < nb_qos_flows; j++) {
      drbs[i].drb_info.flows_mapped_to_drb[j].qfi = drb_config->qosFlows[j].qfi;

      pdusession_level_qos_parameter_t *in_qos_char = get_qos_characteristics(drb_config->qosFlows[j].qfi, RRC_pduSession);
      f1ap_qos_characteristics_t *qos_char = &drbs[i].drb_info.flows_mapped_to_drb[j].qos_params.qos_characteristics;
      if (in_qos_char->fiveQI_type == dynamic) {
        qos_char->qos_type = dynamic;
        qos_char->dynamic.fiveqi = in_qos_char->fiveQI;
        qos_char->dynamic.qos_priority_level = in_qos_char->qos_priority;
      } else {
        qos_char->qos_type = non_dynamic;
        qos_char->non_dynamic.fiveqi = in_qos_char->fiveQI;
        qos_char->non_dynamic.qos_priority_level = in_qos_char->qos_priority;
      }
    }
2135 2136 2137
    /* the DRB QoS parameters: we just reuse the ones from the first flow */
    drbs[i].drb_info.drb_qos = drbs[i].drb_info.flows_mapped_to_drb[0].qos_params;

2138 2139
    /* pass NSSAI info to MAC */
    drbs[i].nssai = RRC_pduSession->param.nssai;
2140 2141 2142
  }

  /* Instruction towards the DU for SRB2 configuration */
2143 2144 2145 2146 2147 2148 2149 2150
  int nb_srb = 0;
  f1ap_srb_to_be_setup_t srbs[1];
  if (UE->Srb[2].Active == 0) {
    UE->Srb[2].Active = 1;
    nb_srb = 1;
    srbs[0].srb_id = 2;
    srbs[0].lcid = 2;
  }
2151

2152 2153 2154 2155 2156 2157 2158
  if (!UE->as_security_active) {
    /* no AS security active, need to send UE context setup req with security
     * command (and the bearers) */
    AssertFatal(false, "not implemented yet\n");
    return;
  }

2159
  /* Gather UE capability if present */
2160 2161 2162 2163 2164 2165 2166 2167
  cu_to_du_rrc_information_t cu2du = {0};
  cu_to_du_rrc_information_t *cu2du_p = NULL;
  if (UE->ue_cap_buffer.len > 0 && UE->ue_cap_buffer.buf != NULL) {
    cu2du_p = &cu2du;
    cu2du.uE_CapabilityRAT_ContainerList = UE->ue_cap_buffer.buf;
    cu2du.uE_CapabilityRAT_ContainerList_length = UE->ue_cap_buffer.len;
  }

2168
  f1_ue_data_t ue_data = cu_get_f1_ue_data(UE->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
2169
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
2170
  f1ap_ue_context_modif_req_t ue_context_modif_req = {
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
      .gNB_CU_ue_id = UE->rrc_ue_id,
      .gNB_DU_ue_id = ue_data.secondary_ue,
      .plmn.mcc = rrc->configuration.mcc[0],
      .plmn.mnc = rrc->configuration.mnc[0],
      .plmn.mnc_digit_length = rrc->configuration.mnc_digit_length[0],
      .nr_cellid = rrc->nr_cellid,
      .servCellId = 0, /* TODO: correct value? */
      .srbs_to_be_setup_length = nb_srb,
      .srbs_to_be_setup = srbs,
      .drbs_to_be_setup_length = nb_drb,
      .drbs_to_be_setup = drbs,
      .cu_to_du_rrc_information = cu2du_p,
2183
  };
Robert Schmidt's avatar
Robert Schmidt committed
2184
  rrc->mac_rrc.ue_context_modification_request(ue_data.du_assoc_id, &ue_context_modif_req);
2185 2186
}

2187
/**
2188
 * @brief E1AP Bearer Context Modification Response processing on CU-CP
2189
*/
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
void rrc_gNB_process_e1_bearer_context_modif_resp(const e1ap_bearer_modif_resp_t *resp)
{
  gNB_RRC_INST *rrc = RC.nrrrc[0];
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(rrc, resp->gNB_cu_cp_ue_id);
  if (ue_context_p == NULL) {
    LOG_E(RRC, "no UE with CU-CP UE ID %d found\n", resp->gNB_cu_cp_ue_id);
    return;
  }

  // there is not really anything to do here as of now
  for (int i = 0; i < resp->numPDUSessionsMod; ++i) {
    const pdu_session_modif_t *pdu = &resp->pduSessionMod[i];
    LOG_I(RRC, "UE %d: PDU session ID %ld modified %d bearers\n", resp->gNB_cu_cp_ue_id, pdu->id, pdu->numDRBModified);
  }
}

2206 2207 2208
/**
 * @brief E1AP Bearer Context Release processing
*/
2209 2210 2211 2212 2213 2214 2215 2216 2217
void rrc_gNB_process_e1_bearer_context_release_cplt(const e1ap_bearer_release_cplt_t *cplt)
{
  // there is not really anything to do here as of now
  // note that we don't check for the UE: it does not exist anymore if the F1
  // UE context release complete arrived from the DU first, after which we free
  // the UE context
  LOG_I(RRC, "UE %d: received bearer release complete\n", cplt->gNB_cu_cp_ue_id);
}

2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
static void print_rrc_meas(FILE *f, const NR_MeasResults_t *measresults)
{
  DevAssert(measresults->measResultServingMOList.list.count >= 1);
  if (measresults->measResultServingMOList.list.count > 1)
    LOG_W(RRC, "Received %d MeasResultServMO, but handling only 1!\n", measresults->measResultServingMOList.list.count);

  NR_MeasResultServMO_t *measresultservmo = measresults->measResultServingMOList.list.array[0];
  NR_MeasResultNR_t *measresultnr = &measresultservmo->measResultServingCell;
  NR_MeasQuantityResults_t *mqr = measresultnr->measResult.cellResults.resultsSSB_Cell;

  fprintf(f, "    servingCellId %ld MeasResultNR for phyCellId %ld:\n      resultSSB:", measresultservmo->servCellId, *measresultnr->physCellId);
  if (mqr != NULL) {
    const long rrsrp = *mqr->rsrp - 156;
    const float rrsrq = (float) (*mqr->rsrq - 87) / 2.0f;
    const float rsinr = (float) (*mqr->sinr - 46) / 2.0f;
    fprintf(f, "RSRP %ld dBm RSRQ %.1f dB SINR %.1f dB\n", rrsrp, rrsrq, rsinr);
  } else {
    fprintf(f, "NOT PROVIDED\n");
  }
}

2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
static const char *get_rrc_connection_status_text(NR_UE_STATE_t state)
{
  switch (state) {
    case NR_RRC_INACTIVE: return "inactive";
    case NR_RRC_IDLE: return "idle";
    case NR_RRC_SI_RECEIVED: return "SI-received";
    case NR_RRC_CONNECTED: return "connected";
    case NR_RRC_RECONFIGURED: return "reconfigured";
    case NR_RRC_HO_EXECUTION: return "HO-execution";
    default: AssertFatal(false, "illegal RRC state %d\n", state); return "illegal";
  }
  return "illegal";
}

static const char *get_pdusession_status_text(pdu_session_status_t status)
{
  switch (status) {
    case PDU_SESSION_STATUS_NEW: return "new";
    case PDU_SESSION_STATUS_DONE: return "done";
    case PDU_SESSION_STATUS_ESTABLISHED: return "established";
    case PDU_SESSION_STATUS_REESTABLISHED: return "reestablished";
    case PDU_SESSION_STATUS_TOMODIFY: return "to-modify";
    case PDU_SESSION_STATUS_FAILED: return "failed";
    case PDU_SESSION_STATUS_TORELEASE: return "to-release";
    case PDU_SESSION_STATUS_RELEASED: return "released";
    default: AssertFatal(false, "illegal PDU status code %d\n", status); return "illegal";
  }
  return "illegal";
}

2269 2270 2271 2272 2273 2274 2275 2276 2277
static void write_rrc_stats(const gNB_RRC_INST *rrc)
{
  const char *filename = "nrRRC_stats.log";
  FILE *f = fopen(filename, "w");
  if (f == NULL) {
    LOG_E(NR_RRC, "cannot open %s for writing\n", filename);
    return;
  }

2278
  int i = 0;
2279 2280
  rrc_gNB_ue_context_t *ue_context_p = NULL;
  /* cast is necessary to eliminate warning "discards ‘const’ qualifier" */
2281 2282
  RB_FOREACH(ue_context_p, rrc_nr_ue_tree_s, &((gNB_RRC_INST *)rrc)->rrc_ue_head)
  {
2283
    const gNB_RRC_UE_t *ue_ctxt = &ue_context_p->ue_context;
2284
    f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_ctxt->rrc_ue_id);
2285

2286 2287 2288 2289 2290 2291 2292
    fprintf(f,
            "UE %d CU UE ID %d DU UE ID %d RNTI %04x random identity %016lx",
            i,
            ue_ctxt->rrc_ue_id,
            ue_data.secondary_ue,
            ue_ctxt->rnti,
            ue_ctxt->random_ue_identity);
2293
    if (ue_ctxt->Initialue_identity_5g_s_TMSI.presence)
2294
      fprintf(f, " S-TMSI %x", ue_ctxt->Initialue_identity_5g_s_TMSI.fiveg_tmsi);
2295
    fprintf(f, ":\n");
2296

2297 2298 2299 2300 2301 2302 2303 2304
    fprintf(f, "    RRC status %s\n", get_rrc_connection_status_text(ue_ctxt->StatusRrc));

    if (ue_ctxt->nb_of_pdusessions == 0)
      fprintf(f, "    (no PDU sessions)\n");
    for (int nb_pdu = 0; nb_pdu < ue_ctxt->nb_of_pdusessions; ++nb_pdu) {
      const rrc_pdu_session_param_t *pdu = &ue_ctxt->pduSession[nb_pdu];
      fprintf(f, "    PDU session %d ID %d status %s\n", nb_pdu, pdu->param.pdusession_id, get_pdusession_status_text(pdu->status));
    }
2305

2306 2307 2308 2309 2310 2311 2312 2313
    fprintf(f, "    associated DU: ");
    if (ue_data.du_assoc_id == -1)
      fprintf(f, " (local/integrated CU-DU)");
    else if (ue_data.du_assoc_id == 0)
      fprintf(f, " DU offline/unavailable");
    else
      fprintf(f, " DU assoc ID %d", ue_data.du_assoc_id);
    fprintf(f, "\n");
2314 2315 2316

    if (ue_ctxt->measResults)
      print_rrc_meas(f, ue_ctxt->measResults);
2317
    ++i;
2318 2319
  }

2320 2321 2322
  fprintf(f, "\n");
  dump_du_info(rrc, f);

2323 2324 2325
  fclose(f);
}

2326
void *rrc_gnb_task(void *args_p) {
laurent's avatar
tmp  
laurent committed
2327
  MessageDef *msg_p;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2328 2329
  instance_t                         instance;
  int                                result;
2330
  protocol_ctxt_t ctxt = {.module_id = 0, .enb_flag = 1, .instance = 0, .rntiMaybeUEid = 0, .frame = -1, .subframe = -1, .eNB_index = 0, .brOption = false};
2331 2332

  long stats_timer_id = 1;
2333 2334 2335 2336 2337
  if (!IS_SOFTMODEM_NOSTATS_BIT) {
    /* timer to write stats to file */
    timer_setup(1, 0, TASK_RRC_GNB, 0, TIMER_PERIODIC, NULL, &stats_timer_id);
  }
  
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2338 2339
  itti_mark_task_ready(TASK_RRC_GNB);
  LOG_I(NR_RRC,"Entering main loop of NR_RRC message task\n");
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2340 2341

  while (1) {
2342
    // Wait for a message
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2343
    itti_receive_msg(TASK_RRC_GNB, &msg_p);
laurent's avatar
tmp  
laurent committed
2344
    const char *msg_name_p = ITTI_MSG_NAME(msg_p);
2345
    instance = ITTI_MSG_DESTINATION_INSTANCE(msg_p);
2346 2347 2348 2349 2350
    LOG_D(NR_RRC,
          "RRC GNB Task Received %s for instance %ld from task %s\n",
          ITTI_MSG_NAME(msg_p),
          ITTI_MSG_DESTINATION_INSTANCE(msg_p),
          ITTI_MSG_ORIGIN_NAME(msg_p));
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2351
    switch (ITTI_MSG_ID(msg_p)) {
2352
      case TERMINATE_MESSAGE:
Xue Song's avatar
Xue Song committed
2353
        LOG_W(NR_RRC, " *** Exiting NR_RRC thread\n");
2354 2355
        itti_exit_task();
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2356

2357
      case MESSAGE_TEST:
2358
        LOG_I(NR_RRC, "[gNB %ld] Received %s\n", instance, msg_name_p);
2359
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2360

2361 2362 2363 2364 2365 2366
      case TIMER_HAS_EXPIRED:
        /* only this one handled for now */
        DevAssert(TIMER_HAS_EXPIRED(msg_p).timer_id == stats_timer_id);
        write_rrc_stats(RC.nrrrc[0]);
        break;

2367 2368 2369
      case F1AP_INITIAL_UL_RRC_MESSAGE:
        AssertFatal(NODE_IS_CU(RC.nrrrc[instance]->node_type) || NODE_IS_MONOLITHIC(RC.nrrrc[instance]->node_type),
                    "should not receive F1AP_INITIAL_UL_RRC_MESSAGE, need call by CU!\n");
Robert Schmidt's avatar
Robert Schmidt committed
2370
        rrc_gNB_process_initial_ul_rrc_message(msg_p->ittiMsgHeader.originInstance, &F1AP_INITIAL_UL_RRC_MESSAGE(msg_p));
2371
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2372 2373

      /* Messages from PDCP */
2374
      case F1AP_UL_RRC_MESSAGE:
2375 2376 2377
        PROTOCOL_CTXT_SET_BY_INSTANCE(&ctxt,
                                      instance,
                                      GNB_FLAG_YES,
2378
                                      F1AP_UL_RRC_MESSAGE(msg_p).gNB_CU_ue_id,
2379 2380
                                      0,
                                      0);
2381 2382 2383 2384 2385 2386 2387
        LOG_D(NR_RRC,
              "Decoding DCCH %d: ue %04lx, inst %ld, ctxt %p, size %d\n",
              F1AP_UL_RRC_MESSAGE(msg_p).srb_id,
              ctxt.rntiMaybeUEid,
              instance,
              &ctxt,
              F1AP_UL_RRC_MESSAGE(msg_p).rrc_container_length);
Xue Song's avatar
Xue Song committed
2388
        rrc_gNB_decode_dcch(&ctxt,
2389 2390 2391 2392
                            F1AP_UL_RRC_MESSAGE(msg_p).srb_id,
                            F1AP_UL_RRC_MESSAGE(msg_p).rrc_container,
                            F1AP_UL_RRC_MESSAGE(msg_p).rrc_container_length);
        free(F1AP_UL_RRC_MESSAGE(msg_p).rrc_container);
Xue Song's avatar
Xue Song committed
2393
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2394

Xue Song's avatar
Xue Song committed
2395
      case NGAP_DOWNLINK_NAS:
laurent's avatar
tmp  
laurent committed
2396
        rrc_gNB_process_NGAP_DOWNLINK_NAS(msg_p, instance, &rrc_gNB_mui);
Xue Song's avatar
Xue Song committed
2397 2398
        break;

2399
      case NGAP_PDUSESSION_SETUP_REQ:
laurent's avatar
tmp  
laurent committed
2400
        rrc_gNB_process_NGAP_PDUSESSION_SETUP_REQ(msg_p, instance);
2401 2402
        break;

2403
      case NGAP_PDUSESSION_MODIFY_REQ:
laurent's avatar
tmp  
laurent committed
2404
        rrc_gNB_process_NGAP_PDUSESSION_MODIFY_REQ(msg_p, instance);
2405 2406 2407
        break;

      case NGAP_PDUSESSION_RELEASE_COMMAND:
laurent's avatar
tmp  
laurent committed
2408
        rrc_gNB_process_NGAP_PDUSESSION_RELEASE_COMMAND(msg_p, instance);
2409 2410
        break;

Xue Song's avatar
Xue Song committed
2411 2412
      /* Messages from F1AP task */
      case F1AP_SETUP_REQ:
2413
        AssertFatal(!NODE_IS_DU(RC.nrrrc[instance]->node_type), "should not receive F1AP_SETUP_REQUEST in DU!\n");
2414
        rrc_gNB_process_f1_setup_req(&F1AP_SETUP_REQ(msg_p), msg_p->ittiMsgHeader.originInstance);
Xue Song's avatar
Xue Song committed
2415
        break;
2416

2417
      case F1AP_UE_CONTEXT_SETUP_RESP:
laurent's avatar
tmp  
laurent committed
2418
        rrc_CU_process_ue_context_setup_response(msg_p, instance);
2419
        break;
2420

2421
      case F1AP_UE_CONTEXT_MODIFICATION_RESP:
laurent's avatar
tmp  
laurent committed
2422
        rrc_CU_process_ue_context_modification_response(msg_p, instance);
2423 2424
        break;

2425 2426 2427 2428
      case F1AP_UE_CONTEXT_MODIFICATION_REQUIRED:
        rrc_CU_process_ue_modification_required(msg_p);
        break;

2429
      case F1AP_UE_CONTEXT_RELEASE_REQ:
2430
        rrc_CU_process_ue_context_release_request(msg_p);
2431 2432 2433 2434
        break;

      case F1AP_UE_CONTEXT_RELEASE_COMPLETE:
        rrc_CU_process_ue_context_release_complete(msg_p);
2435
        break;
Xue Song's avatar
Xue Song committed
2436

2437 2438 2439 2440
      case F1AP_LOST_CONNECTION:
        rrc_CU_process_f1_lost_connection(RC.nrrrc[0], &F1AP_LOST_CONNECTION(msg_p), msg_p->ittiMsgHeader.originInstance);
        break;

2441
      /* Messages from X2AP */
2442
      case X2AP_ENDC_SGNB_ADDITION_REQ:
2443
        LOG_I(NR_RRC, "Received ENDC sgNB addition request from X2AP \n");
2444
        rrc_gNB_process_AdditionRequestInformation(instance, &X2AP_ENDC_SGNB_ADDITION_REQ(msg_p));
2445
        break;
2446

2447
      case X2AP_ENDC_SGNB_RECONF_COMPLETE:
Melissa Elkadi's avatar
Melissa Elkadi committed
2448
        LOG_A(NR_RRC, "Handling of reconfiguration complete message at RRC gNB is pending \n");
2449
        break;
Xue Song's avatar
Xue Song committed
2450

2451
      case NGAP_INITIAL_CONTEXT_SETUP_REQ:
laurent's avatar
tmp  
laurent committed
2452
        rrc_gNB_process_NGAP_INITIAL_CONTEXT_SETUP_REQ(msg_p, instance);
yaojie's avatar
yaojie committed
2453
        break;
2454

Cedric Roux's avatar
Cedric Roux committed
2455 2456
      case X2AP_ENDC_SGNB_RELEASE_REQUEST:
        LOG_I(NR_RRC, "Received ENDC sgNB release request from X2AP \n");
2457
        rrc_gNB_process_release_request(instance, &X2AP_ENDC_SGNB_RELEASE_REQUEST(msg_p));
Cedric Roux's avatar
Cedric Roux committed
2458 2459 2460
        break;

      case X2AP_ENDC_DC_OVERALL_TIMEOUT:
2461
        rrc_gNB_process_dc_overall_timeout(instance, &X2AP_ENDC_DC_OVERALL_TIMEOUT(msg_p));
Cedric Roux's avatar
Cedric Roux committed
2462 2463
        break;

2464
      case NGAP_UE_CONTEXT_RELEASE_REQ:
laurent's avatar
tmp  
laurent committed
2465
        rrc_gNB_process_NGAP_UE_CONTEXT_RELEASE_REQ(msg_p, instance);
2466 2467 2468
        break;

      case NGAP_UE_CONTEXT_RELEASE_COMMAND:
laurent's avatar
tmp  
laurent committed
2469
        rrc_gNB_process_NGAP_UE_CONTEXT_RELEASE_COMMAND(msg_p, instance);
2470 2471
        break;

2472
      case E1AP_SETUP_REQ:
2473
        rrc_gNB_process_e1_setup_req(msg_p->ittiMsgHeader.originInstance, &E1AP_SETUP_REQ(msg_p));
2474 2475 2476 2477
        break;

      case E1AP_BEARER_CONTEXT_SETUP_RESP:
        rrc_gNB_process_e1_bearer_context_setup_resp(&E1AP_BEARER_CONTEXT_SETUP_RESP(msg_p), instance);
2478
        break;
2479

2480 2481 2482 2483
      case E1AP_BEARER_CONTEXT_MODIFICATION_RESP:
        rrc_gNB_process_e1_bearer_context_modif_resp(&E1AP_BEARER_CONTEXT_MODIFICATION_RESP(msg_p));
        break;

2484 2485 2486 2487
      case E1AP_BEARER_CONTEXT_RELEASE_CPLT:
        rrc_gNB_process_e1_bearer_context_release_cplt(&E1AP_BEARER_CONTEXT_RELEASE_CPLT(msg_p));
        break;

2488 2489 2490 2491
      case E1AP_LOST_CONNECTION: /* CUCP */
        rrc_gNB_process_e1_lost_connection(RC.nrrrc[0], &E1AP_LOST_CONNECTION(msg_p), msg_p->ittiMsgHeader.originInstance);
        break;

2492
      case NGAP_PAGING_IND:
laurent's avatar
tmp  
laurent committed
2493
        rrc_gNB_process_PAGING_IND(msg_p, instance);
2494 2495
        break;

2496
      default:
2497
        LOG_E(NR_RRC, "[gNB %ld] Received unexpected message %s\n", instance, msg_name_p);
2498
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2499 2500 2501 2502 2503 2504 2505
    }

    result = itti_free(ITTI_MSG_ORIGIN_ID(msg_p), msg_p);
    AssertFatal(result == EXIT_SUCCESS, "Failed to free memory (%d)!\n", result);
    msg_p = NULL;
  }
}
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2506

2507 2508 2509
typedef struct deliver_ue_ctxt_setup_data_t {
  gNB_RRC_INST *rrc;
  f1ap_ue_context_setup_t *setup_req;
Robert Schmidt's avatar
Robert Schmidt committed
2510
  sctp_assoc_t assoc_id;
2511
} deliver_ue_ctxt_setup_data_t;
2512 2513 2514
static void rrc_deliver_ue_ctxt_setup_req(void *deliver_pdu_data, ue_id_t ue_id, int srb_id, char *buf, int size, int sdu_id)
{
  DevAssert(deliver_pdu_data != NULL);
2515 2516 2517
  deliver_ue_ctxt_setup_data_t *data = deliver_pdu_data;
  data->setup_req->rrc_container = (uint8_t*)buf;
  data->setup_req->rrc_container_length = size;
Robert Schmidt's avatar
Robert Schmidt committed
2518
  data->rrc->mac_rrc.ue_context_setup_request(data->assoc_id, data->setup_req);
2519 2520
}

heshanyun's avatar
heshanyun committed
2521 2522 2523 2524
//-----------------------------------------------------------------------------
void
rrc_gNB_generate_SecurityModeCommand(
  const protocol_ctxt_t *const ctxt_pP,
Xue Song's avatar
Xue Song committed
2525
  rrc_gNB_ue_context_t  *const ue_context_pP
heshanyun's avatar
heshanyun committed
2526 2527 2528 2529 2530
)
//-----------------------------------------------------------------------------
{
  uint8_t                             buffer[100];
  uint8_t                             size;
2531
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
2532
  AssertFatal(!ue_p->as_security_active, "logic error: security already active\n");
2533

2534
  T(T_ENB_RRC_SECURITY_MODE_COMMAND, T_INT(ctxt_pP->module_id), T_INT(ctxt_pP->frame), T_INT(ctxt_pP->subframe), T_INT(ctxt_pP->rntiMaybeUEid));
2535
  NR_IntegrityProtAlgorithm_t integrity_algorithm = (NR_IntegrityProtAlgorithm_t)ue_p->integrity_algorithm;
2536
  size = do_NR_SecurityModeCommand(ctxt_pP, buffer, rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id), ue_p->ciphering_algorithm, integrity_algorithm);
heshanyun's avatar
heshanyun committed
2537
  LOG_DUMPMSG(NR_RRC,DEBUG_RRC,(char *)buffer,size,"[MSG] RRC Security Mode Command\n");
2538
  LOG_I(NR_RRC, "UE %04x Logical Channel DL-DCCH, Generate SecurityModeCommand (bytes %d)\n", ue_p->rnti, size);
2539

2540 2541
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
  AssertFatal(!NODE_IS_DU(rrc->node_type), "illegal node type DU!\n");
2542

2543 2544 2545 2546 2547 2548 2549 2550
  cu_to_du_rrc_information_t cu2du = {0};
  cu_to_du_rrc_information_t *cu2du_p = NULL;
  if (ue_p->ue_cap_buffer.len > 0 && ue_p->ue_cap_buffer.buf != NULL) {
    cu2du_p = &cu2du;
    cu2du.uE_CapabilityRAT_ContainerList = ue_p->ue_cap_buffer.buf;
    cu2du.uE_CapabilityRAT_ContainerList_length = ue_p->ue_cap_buffer.len;
  }

2551
  /* the callback will fill the UE context setup request and forward it */
2552
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
2553
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
2554
  f1ap_ue_context_setup_t ue_context_setup_req = {
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
      .gNB_CU_ue_id = ue_p->rrc_ue_id,
      .gNB_DU_ue_id = ue_data.secondary_ue,
      .plmn.mcc = rrc->configuration.mcc[0],
      .plmn.mnc = rrc->configuration.mnc[0],
      .plmn.mnc_digit_length = rrc->configuration.mnc_digit_length[0],
      .nr_cellid = rrc->nr_cellid,
      .servCellId = 0, /* TODO: correct value? */
      .srbs_to_be_setup = 0, /* no new SRBs */
      .drbs_to_be_setup = 0, /* no new DRBs */
      .cu_to_du_rrc_information = cu2du_p,
2565
  };
Robert Schmidt's avatar
Robert Schmidt committed
2566
  deliver_ue_ctxt_setup_data_t data = {.rrc = rrc, .setup_req = &ue_context_setup_req, .assoc_id = ue_data.du_assoc_id };
2567
  nr_pdcp_data_req_srb(ctxt_pP->rntiMaybeUEid, DCCH, rrc_gNB_mui++, size, buffer, rrc_deliver_ue_ctxt_setup_req, &data);
heshanyun's avatar
heshanyun committed
2568 2569
}

zhanghuiqin's avatar
zhanghuiqin committed
2570 2571 2572 2573 2574 2575 2576 2577 2578
void
rrc_gNB_generate_UECapabilityEnquiry(
  const protocol_ctxt_t *const ctxt_pP,
  rrc_gNB_ue_context_t          *const ue_context_pP
)
//-----------------------------------------------------------------------------
{
  uint8_t                             buffer[100];
  uint8_t                             size;
2579

2580
  T(T_ENB_RRC_UE_CAPABILITY_ENQUIRY, T_INT(ctxt_pP->module_id), T_INT(ctxt_pP->frame), T_INT(ctxt_pP->subframe), T_INT(ctxt_pP->rntiMaybeUEid));
Xue Song's avatar
Xue Song committed
2581
  size = do_NR_SA_UECapabilityEnquiry(
zhanghuiqin's avatar
zhanghuiqin committed
2582 2583 2584
           ctxt_pP,
           buffer,
           rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id));
2585 2586 2587
  LOG_I(NR_RRC,
        PROTOCOL_NR_RRC_CTXT_UE_FMT" Logical Channel DL-DCCH, Generate NR UECapabilityEnquiry (bytes %d)\n",
        PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
zhanghuiqin's avatar
zhanghuiqin committed
2588
        size);
2589

2590 2591
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
  AssertFatal(!NODE_IS_DU(rrc->node_type), "illegal node type DU!\n");
2592

2593 2594
  const gNB_RRC_UE_t *ue = &ue_context_pP->ue_context;
  nr_rrc_transfer_protected_rrc_message(rrc, ue, DCCH, buffer, size);
zhanghuiqin's avatar
zhanghuiqin committed
2595
}
heshanyun's avatar
heshanyun committed
2596

2597 2598 2599
typedef struct deliver_ue_ctxt_release_data_t {
  gNB_RRC_INST *rrc;
  f1ap_ue_context_release_cmd_t *release_cmd;
Robert Schmidt's avatar
Robert Schmidt committed
2600
  sctp_assoc_t assoc_id;
2601
} deliver_ue_ctxt_release_data_t;
2602 2603 2604
static void rrc_deliver_ue_ctxt_release_cmd(void *deliver_pdu_data, ue_id_t ue_id, int srb_id, char *buf, int size, int sdu_id)
{
  DevAssert(deliver_pdu_data != NULL);
2605 2606 2607
  deliver_ue_ctxt_release_data_t *data = deliver_pdu_data;
  data->release_cmd->rrc_container = (uint8_t*) buf;
  data->release_cmd->rrc_container_length = size;
Robert Schmidt's avatar
Robert Schmidt committed
2608
  data->rrc->mac_rrc.ue_context_release_command(data->assoc_id, data->release_cmd);
2609 2610
}

heshanyun's avatar
heshanyun committed
2611 2612 2613 2614 2615 2616
//-----------------------------------------------------------------------------
/*
* Generate the RRC Connection Release to UE.
* If received, UE should switch to RRC_IDLE mode.
*/
void
Xue Song's avatar
Xue Song committed
2617
rrc_gNB_generate_RRCRelease(
heshanyun's avatar
heshanyun committed
2618
  const protocol_ctxt_t *const ctxt_pP,
Xue Song's avatar
Xue Song committed
2619
  rrc_gNB_ue_context_t  *const ue_context_pP
heshanyun's avatar
heshanyun committed
2620 2621 2622
)
//-----------------------------------------------------------------------------
{
2623 2624
  uint8_t buffer[RRC_BUF_SIZE] = {0};
  int size = do_NR_RRCRelease(buffer, RRC_BUF_SIZE, rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id));
2625

heshanyun's avatar
heshanyun committed
2626
  LOG_I(NR_RRC,
Xue Song's avatar
Xue Song committed
2627 2628
        PROTOCOL_NR_RRC_CTXT_UE_FMT" Logical Channel DL-DCCH, Generate RRCRelease (bytes %d)\n",
        PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
heshanyun's avatar
heshanyun committed
2629 2630
        size);

2631
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
2632
  const gNB_RRC_UE_t *UE = &ue_context_pP->ue_context;
2633
  f1_ue_data_t ue_data = cu_get_f1_ue_data(UE->rrc_ue_id);
Robert Schmidt's avatar
Robert Schmidt committed
2634
  RETURN_IF_INVALID_ASSOC_ID(ue_data);
2635
  f1ap_ue_context_release_cmd_t ue_context_release_cmd = {
2636
    .gNB_CU_ue_id = UE->rrc_ue_id,
2637 2638 2639 2640 2641
    .gNB_DU_ue_id = ue_data.secondary_ue,
    .cause = F1AP_CAUSE_RADIO_NETWORK,
    .cause_value = 10, // 10 = F1AP_CauseRadioNetwork_normal_release
    .srb_id = DCCH,
  };
Robert Schmidt's avatar
Robert Schmidt committed
2642
  deliver_ue_ctxt_release_data_t data = {.rrc = rrc, .release_cmd = &ue_context_release_cmd, .assoc_id = ue_data.du_assoc_id};
2643
  nr_pdcp_data_req_srb(ctxt_pP->rntiMaybeUEid, DCCH, rrc_gNB_mui++, size, buffer, rrc_deliver_ue_ctxt_release_cmd, &data);
2644

2645 2646 2647 2648 2649 2650 2651
  sctp_assoc_t assoc_id = get_existing_cuup_for_ue(rrc, UE);
  e1ap_bearer_release_cmd_t cmd = {
    .gNB_cu_cp_ue_id = UE->rrc_ue_id,
    .gNB_cu_up_ue_id = UE->rrc_ue_id,
  };
  rrc->cucp_cuup.bearer_context_release(assoc_id, &cmd);

2652
  /* UE will be freed after UE context release complete */
heshanyun's avatar
heshanyun committed
2653
}
2654

2655 2656 2657 2658
int rrc_gNB_generate_pcch_msg(sctp_assoc_t assoc_id, const NR_SIB1_t *sib1, uint32_t tmsi, uint8_t paging_drx)
{
  instance_t instance = 0;
  uint8_t CC_id = 0;
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
  const unsigned int Ttab[4] = {32,64,128,256};
  uint8_t Tc;
  uint8_t Tue;
  uint32_t pfoffset;
  uint32_t N;  /* N: min(T,nB). total count of PF in one DRX cycle */
  uint32_t Ns = 0;  /* Ns: max(1,nB/T) */
  uint8_t i_s;  /* i_s = floor(UE_ID/N) mod Ns */
  uint32_t T;  /* DRX cycle */
  uint32_t length;
  uint8_t buffer[RRC_BUF_SIZE];

  /* get default DRX cycle from configuration */
  Tc = sib1->servingCellConfigCommon->downlinkConfigCommon.pcch_Config.defaultPagingCycle;

  Tue = paging_drx;
  /* set T = min(Tc,Tue) */
  T = Tc < Tue ? Ttab[Tc] : Ttab[Tue];
  /* set N = PCCH-Config->nAndPagingFrameOffset */
  switch (sib1->servingCellConfigCommon->downlinkConfigCommon.pcch_Config.nAndPagingFrameOffset.present) {
    case NR_PCCH_Config__nAndPagingFrameOffset_PR_oneT:
      N = T;
      pfoffset = 0;
      break;
    case NR_PCCH_Config__nAndPagingFrameOffset_PR_halfT:
      N = T/2;
      pfoffset = 1;
      break;
    case NR_PCCH_Config__nAndPagingFrameOffset_PR_quarterT:
      N = T/4;
      pfoffset = 3;
      break;
    case NR_PCCH_Config__nAndPagingFrameOffset_PR_oneEighthT:
      N = T/8;
      pfoffset = 7;
      break;
    case NR_PCCH_Config__nAndPagingFrameOffset_PR_oneSixteenthT:
      N = T/16;
      pfoffset = 15;
      break;
    default:
      LOG_E(RRC, "[gNB %ld] In rrc_gNB_generate_pcch_msg:  pfoffset error (pfoffset %d)\n",
            instance, sib1->servingCellConfigCommon->downlinkConfigCommon.pcch_Config.nAndPagingFrameOffset.present);
      return (-1);

  }

  switch (sib1->servingCellConfigCommon->downlinkConfigCommon.pcch_Config.ns) {
    case NR_PCCH_Config__ns_four:
      if(*sib1->servingCellConfigCommon->downlinkConfigCommon.initialDownlinkBWP.pdcch_ConfigCommon->choice.setup->pagingSearchSpace == 0){
        LOG_E(RRC, "[gNB %ld] In rrc_gNB_generate_pcch_msg:  ns error only 1 or 2 is allowed when pagingSearchSpace is 0\n",
              instance);
        return (-1);
      } else {
        Ns = 4;
      }
      break;
    case NR_PCCH_Config__ns_two:
      Ns = 2;
      break;
    case NR_PCCH_Config__ns_one:
      Ns = 1;
      break;
    default:
      LOG_E(RRC, "[gNB %ld] In rrc_gNB_generate_pcch_msg: ns error (ns %ld)\n",
            instance, sib1->servingCellConfigCommon->downlinkConfigCommon.pcch_Config.ns);
      return (-1);
  }

  /* insert data to UE_PF_PO or update data in UE_PF_PO */
  pthread_mutex_lock(&ue_pf_po_mutex);
  uint8_t i = 0;

  for (i = 0; i < MAX_MOBILES_PER_ENB; i++) {
    if ((UE_PF_PO[CC_id][i].enable_flag == true && UE_PF_PO[CC_id][i].ue_index_value == (uint16_t)(tmsi%1024))
        || (UE_PF_PO[CC_id][i].enable_flag != true)) {
      /* set T = min(Tc,Tue) */
      UE_PF_PO[CC_id][i].T = T;
      /* set UE_ID */
      UE_PF_PO[CC_id][i].ue_index_value = (uint16_t)(tmsi%1024);
      /* calculate PF and PO */
      /* set PF_min and PF_offset: (SFN + PF_offset) mod T = (T div N)*(UE_ID mod N) */
      UE_PF_PO[CC_id][i].PF_min = (T / N) * (UE_PF_PO[CC_id][i].ue_index_value % N);
      UE_PF_PO[CC_id][i].PF_offset = pfoffset;
      /* set i_s */
      /* i_s = floor(UE_ID/N) mod Ns */
      i_s = (uint8_t)((UE_PF_PO[CC_id][i].ue_index_value / N) % Ns);
      UE_PF_PO[CC_id][i].i_s = i_s;

      // TODO,set PO

      if (UE_PF_PO[CC_id][i].enable_flag == true) {
        //paging exist UE log
        LOG_D(NR_RRC,"[gNB %ld] CC_id %d In rrc_gNB_generate_pcch_msg: Update exist UE %d, T %d, N %d, PF %d, i_s %d, PF_offset %d\n", instance, CC_id, UE_PF_PO[CC_id][i].ue_index_value,
              T, N, UE_PF_PO[CC_id][i].PF_min, UE_PF_PO[CC_id][i].i_s, UE_PF_PO[CC_id][i].PF_offset);
      } else {
        /* set enable_flag */
        UE_PF_PO[CC_id][i].enable_flag = true;
        //paging new UE log
        LOG_D(NR_RRC,"[gNB %ld] CC_id %d In rrc_gNB_generate_pcch_msg: Insert a new UE %d, T %d, N %d, PF %d, i_s %d, PF_offset %d\n", instance, CC_id, UE_PF_PO[CC_id][i].ue_index_value,
              T, N, UE_PF_PO[CC_id][i].PF_min, UE_PF_PO[CC_id][i].i_s, UE_PF_PO[CC_id][i].PF_offset);
      }
      break;
    }
  }

  pthread_mutex_unlock(&ue_pf_po_mutex);

  /* Create message for PDCP (DLInformationTransfer_t) */
  length = do_NR_Paging (instance,
                         buffer,
                         tmsi);

  if (length == -1) {
    LOG_I(NR_RRC, "do_Paging error\n");
    return -1;
  }
  // TODO, send message to pdcp
2776
  (void) assoc_id;
2777 2778 2779

  return 0;
}