rrc_gNB.c 132 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 "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"
Xue Song's avatar
Xue Song committed
81

82
#include "rrc_gNB_GTPV1U.h"
83

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

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

90
#include "executables/softmodem-common.h"
laurent's avatar
laurent committed
91
#include <openair2/RRC/NR/rrc_gNB_UE_context.h>
Laurent's avatar
Laurent committed
92
#include <openair2/X2AP/x2ap_eNB.h>
mir's avatar
mir committed
93
#include <openair3/SECU/key_nas_deriver.h>
94
#include <openair3/ocp-gtpu/gtp_itf.h>
95
#include <openair2/RRC/NR/nr_rrc_proto.h>
96 97
#include "openair2/LAYER2/nr_pdcp/nr_pdcp_e1_api.h"
#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;

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

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

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
113 114
///---------------------------------------------------------------------------------------------------------------///
///---------------------------------------------------------------------------------------------------------------///
luis_pereira87's avatar
luis_pereira87 committed
115

116 117 118 119 120 121
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;
122
  long drb_priority[MAX_DRBS_PER_UE] = {0};
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  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
182

183 184
static void freeDRBlist(NR_DRB_ToAddModList_t *list)
{
laurent's avatar
laurent committed
185
  //ASN_STRUCT_FREE(asn_DEF_NR_DRB_ToAddModList, list);
186 187
  return;
}
188

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
typedef struct deliver_dl_rrc_message_data_s {
  const gNB_RRC_INST *rrc;
  f1ap_dl_rrc_message_t *dl_rrc;
} 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);
  data->rrc->mac_rrc.dl_rrc_message_transfer(data->dl_rrc);
}


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);
207 208
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
  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};
209
  deliver_dl_rrc_message_data_t data = {.rrc = rrc, .dl_rrc = &dl_rrc};
210
  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);
211
}
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
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_ul_band(const f1ap_served_cell_info_t *cell_info)
{
  return cell_info->mode == F1AP_MODE_TDD ? cell_info->tdd.freqinfo.band : cell_info->fdd.ul_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;
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
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);
  uint64_t scaling = band < 100 ? 1 : 3;

  uint64_t freqpointa = from_nrarfcn(band, scs, dl_arfcn);
  // offsetToPointA and kSSB are both on 15kHz SCS (see 38.211 sections 7.4.3.1
  // and 4.4.4.2)
  // 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);

  LOG_W(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);

  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;
272
    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);
273 274 275 276 277
  }

  return ssb_arfcn;
}

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
278 279 280
///---------------------------------------------------------------------------------------------------------------///
///---------------------------------------------------------------------------------------------------------------///

281
static void init_NR_SI(gNB_RRC_INST *rrc)
282
{
283 284 285
  if (!NODE_IS_DU(rrc->node_type)) {
    rrc->carrier.SIB23 = (uint8_t *) malloc16(100);
    AssertFatal(rrc->carrier.SIB23 != NULL, "cannot allocate memory for SIB");
286
    rrc->carrier.sizeof_SIB23 = do_SIB23_NR(&rrc->carrier);
287 288 289
    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");
  }
290

291
  if (get_softmodem_params()->phy_test > 0 || get_softmodem_params()->do_ra > 0) {
292
    AssertFatal(NODE_IS_MONOLITHIC(rrc->node_type), "phy_test and do_ra only work in monolithic\n");
293
    rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_allocate_new_ue_context(rrc);
294 295
    gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
    UE->spCellConfig = calloc(1, sizeof(struct NR_SpCellConfig));
296
    UE->spCellConfig->spCellConfigDedicated = RC.nrmac[0]->common_channels[0].pre_ServingCellConfig;
297 298 299
    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);
300
    }
301
  }
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
302
}
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
303

304
static void rrc_gNB_CU_DU_init(gNB_RRC_INST *rrc)
305 306
{
  switch (rrc->node_type) {
307 308 309 310
    case ngran_gNB_CUCP:
      mac_rrc_dl_f1ap_init(&rrc->mac_rrc);
      cucp_cuup_message_transfer_e1ap_init(rrc);
      break;
311 312
    case ngran_gNB_CU:
      mac_rrc_dl_f1ap_init(&rrc->mac_rrc);
313
      cucp_cuup_message_transfer_direct_init(rrc);
314
      break;
315 316 317 318
    case ngran_gNB:
      mac_rrc_dl_direct_init(&rrc->mac_rrc);
      cucp_cuup_message_transfer_direct_init(rrc);
       break;
319 320 321 322 323 324 325 326 327
    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;
  }
328
  cu_init_f1_ue_data();
329 330
}

331
void openair_rrc_gNB_configuration(gNB_RRC_INST *rrc, gNB_RrcConfigurationReq *configuration)
332
{
333 334 335
  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");
336
  rrc->module_id = 0;
337
  rrc_gNB_CU_DU_init(rrc);
338
  uid_linear_allocator_init(&rrc->uid_allocator);
339
  RB_INIT(&rrc->rrc_ue_head);
340
  rrc->configuration = *configuration;
341
   /// System Information INIT
342
  init_NR_SI(rrc);
343 344
  return;
} // END openair_rrc_gNB_configuration
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
345

346 347
static void rrc_gNB_process_AdditionRequestInformation(const module_id_t gnb_mod_idP, x2ap_ENDC_sgnb_addition_req_t *m)
{
348 349 350 351 352 353 354
  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];
355

356 357 358 359 360 361
  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;
  }
362

363 364 365 366 367
  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);
368 369
  LOG_A(NR_RRC, "Successfully parsed CG_ConfigInfo of size %zu bits. (%zu bytes)\n",
        dec_rval.consumed, (dec_rval.consumed +7/8));
370 371
}

372
//-----------------------------------------------------------------------------
373
unsigned int rrc_gNB_get_next_transaction_identifier(module_id_t gnb_mod_idP)
374 375
//-----------------------------------------------------------------------------
{
376 377 378 379 380 381
  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;
382 383
}

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
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);

407
  for (int i = 0; i < MAX_DRBS_PER_UE; i++) {
408 409 410 411 412 413 414 415 416 417 418 419
    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
420 421 422 423 424 425
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
426 427
  } else
    LOG_E(NR_RRC, "Call free SRB list on NULL pointer\n");
laurent's avatar
laurent committed
428 429
}

430
//-----------------------------------------------------------------------------
431 432
static void rrc_gNB_generate_RRCSetup(instance_t instance,
                                      rnti_t rnti,
433 434
                                      rrc_gNB_ue_context_t *const ue_context_pP,
                                      const uint8_t *masterCellGroup,
435
                                      int masterCellGroup_len)
436 437
//-----------------------------------------------------------------------------
{
438
  LOG_I(NR_RRC, "rrc_gNB_generate_RRCSetup for RNTI %04x\n", rnti);
439 440

  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
441
  gNB_RRC_INST *rrc = RC.nrrrc[instance];
442
  unsigned char buf[1024];
443 444
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(instance);
  ue_p->xids[xid] = RRC_SETUP;
445
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, false);
laurent's avatar
laurent committed
446 447

  int size = do_RRCSetup(ue_context_pP, buf, xid, masterCellGroup, masterCellGroup_len, &rrc->configuration, SRBs);
448
  AssertFatal(size > 0, "do_RRCSetup failed\n");
449
  AssertFatal(size <= 1024, "memory corruption\n");
450 451

  LOG_DUMPMSG(NR_RRC, DEBUG_RRC,
452 453
              (char *)buf,
              size,
454
              "[MSG] RRC Setup\n");
455
  nr_pdcp_add_srbs(true, ue_p->rrc_ue_id, SRBs, 0, NULL, NULL);
Eurecom's avatar
Eurecom committed
456

laurent's avatar
laurent committed
457
  freeSRBlist(SRBs);
458
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
459
  f1ap_dl_rrc_message_t dl_rrc = {
460
    .gNB_CU_ue_id = ue_p->rrc_ue_id,
461
    .gNB_DU_ue_id = ue_data.secondary_ue,
462 463
    .rrc_container = buf,
    .rrc_container_length = size,
464 465
    .srb_id = CCCH
  };
466
  rrc->mac_rrc.dl_rrc_message_transfer(&dl_rrc);
467 468
}

469
static void rrc_gNB_generate_RRCReject(module_id_t module_id, rrc_gNB_ue_context_t *const ue_context_pP)
470 471
//-----------------------------------------------------------------------------
{
472
  LOG_I(NR_RRC, "rrc_gNB_generate_RRCReject \n");
473
  gNB_RRC_INST *rrc = RC.nrrrc[module_id];
474
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
475

476
  unsigned char buf[1024];
477
  int size = do_RRCReject(module_id, buf);
478
  AssertFatal(size > 0, "do_RRCReject failed\n");
479
  AssertFatal(size <= 1024, "memory corruption\n");
480

481
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC,
482 483
              (char *)buf,
              size,
484
              "[MSG] RRCReject \n");
485
  LOG_I(NR_RRC, " [RAPROC] ue %04x Logical Channel DL-CCCH, Generating NR_RRCReject (bytes %d)\n", ue_p->rnti, size);
486

487
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
488
  f1ap_dl_rrc_message_t dl_rrc = {
489
    .gNB_CU_ue_id = ue_p->rrc_ue_id,
490
    .gNB_DU_ue_id = ue_data.secondary_ue,
491 492 493 494 495 496
    .rrc_container = buf,
    .rrc_container_length = size,
    .srb_id = CCCH,
    .execute_duplication  = 1,
    .RAT_frequency_priority_information.en_dc = 0
  };
497
  rrc->mac_rrc.dl_rrc_message_transfer(&dl_rrc);
498 499
}

Xue Song's avatar
Xue Song committed
500 501 502 503
//-----------------------------------------------------------------------------
/*
* Process the rrc setup complete message from UE (SRB1 Active)
*/
504
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
505 506
//-----------------------------------------------------------------------------
{
507
  LOG_A(NR_RRC, PROTOCOL_NR_RRC_CTXT_UE_FMT" [RAPROC] Logical Channel UL-DCCH, " "processing NR_RRCSetupComplete from UE (SRB1 Active)\n",
508
      PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP));
laurent's avatar
tmp  
laurent committed
509 510
  ue_context_pP->ue_context.Srb[1].Active = 1;
  ue_context_pP->ue_context.Srb[2].Active = 0;
511
  ue_context_pP->ue_context.StatusRrc = NR_RRC_CONNECTED;
512
  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
513

514
  if (get_softmodem_params()->sa) {
Xue Song's avatar
Xue Song committed
515
    rrc_gNB_send_NGAP_NAS_FIRST_REQ(ctxt_pP, ue_context_pP, rrcSetupComplete);
516 517 518
  } else {
    rrc_gNB_generate_SecurityModeCommand(ctxt_pP, ue_context_pP);
  }
Xue Song's avatar
Xue Song committed
519 520
}

Xue Song's avatar
Xue Song committed
521
//-----------------------------------------------------------------------------
522
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
523 524
//-----------------------------------------------------------------------------
{
525
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
526
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
527
  AssertFatal(ue_p->nb_of_pdusessions == 0, "logic bug: PDU sessions present before RRC Connection established\n");
528 529
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
  ue_p->xids[xid] = RRC_DEFAULT_RECONF;
530

531 532 533
  const nr_rrc_du_container_t *du = rrc->du;
  DevAssert(du != NULL);

534
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList = CALLOC(1, sizeof(*dedicatedNAS_MessageList));
535

536
  /* Add all NAS PDUs to the list */
537 538 539 540
  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);
541 542
    }

543 544
    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");
545 546
  }

547 548 549
  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);
550 551 552 553 554 555 556 557
  }

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

558 559 560 561
  AssertFatal(du->setup_req->num_cells_available == 1, "cannot handle more than one cell, but have %d\n", du->setup_req->num_cells_available);
  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);
562 563
  uint32_t ssb_arfcn = get_ssb_arfcn(cell_info, du->mib, du->sib1);
  NR_MeasConfig_t *measconfig = get_defaultMeasConfig(ssb_arfcn, band, scs);
564

565
  uint8_t buffer[RRC_BUF_SIZE] = {0};
566
  int size = do_RRCReconfiguration(ue_p,
567
                                   buffer,
568
                                   RRC_BUF_SIZE,
569 570 571 572 573 574 575 576
                                   xid,
                                   NULL, //*SRB_configList2,
                                   NULL, //*DRB_configList,
                                   NULL,
                                   NULL,
                                   measconfig,
                                   dedicatedNAS_MessageList,
                                   ue_p->masterCellGroup);
577
  AssertFatal(size > 0, "cannot encode RRCReconfiguration in %s()\n", __func__);
578
  LOG_W(NR_RRC, "do_RRCReconfiguration(): size %d\n", size);
Robert Schmidt's avatar
Robert Schmidt committed
579
  free_defaultMeasConfig(measconfig);
580

581 582 583
  if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
    xer_fprint(stdout, &asn_DEF_NR_CellGroupConfig, ue_p->masterCellGroup);
  }
584

585
  // suspicious if it is always malloced before ?
586
  free(ue_p->nas_pdu.buffer);
587

588
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC,(char *)buffer, size, "[MSG] RRC Reconfiguration\n");
589 590

  /* Free all NAS PDUs */
591 592 593 594
  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;
595 596 597
    }
  }

598 599 600 601 602 603
  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");
604

605
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
Xue Song's avatar
Xue Song committed
606 607
}

608
//-----------------------------------------------------------------------------
609
void rrc_gNB_generate_dedicatedRRCReconfiguration(const protocol_ctxt_t *const ctxt_pP, rrc_gNB_ue_context_t *ue_context_pP)
610 611 612 613
//-----------------------------------------------------------------------------
{
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];

614
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
615
  int drb_id_to_setup_start = 1;
616
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
617 618 619
  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;
620 621 622 623 624 625
  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
626 627
    if (drb_id_to_setup_start == 1)
      drb_id_to_setup_start = DRB_config->drb_Identity;
628
    int j = ue_p->nb_of_pdusessions - 1;
laurent's avatar
laurent committed
629
    AssertFatal(j >= 0, "");
630
    if (ue_p->pduSession[j].param.nas_pdu.buffer != NULL) {
631 632
      dedicatedNAS_Message = CALLOC(1, sizeof(NR_DedicatedNAS_Message_t));
      memset(dedicatedNAS_Message, 0, sizeof(OCTET_STRING_t));
633 634 635 636
      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;
637
      asn1cSeqAdd(&dedicatedNAS_MessageList->list, dedicatedNAS_Message);
638

639
      LOG_I(NR_RRC, "add NAS info with size %d (pdusession idx %d)\n", ue_p->pduSession[j].param.nas_pdu.length, j);
640 641
    } else {
      // TODO
laurent's avatar
laurent committed
642
      LOG_E(NR_RRC, "no NAS info (pdusession idx %d)\n", j);
643
    }
644

645
    ue_p->pduSession[j].xid = xid;
646
  }
luis_pereira87's avatar
luis_pereira87 committed
647
  freeDRBlist(DRB_configList);
648 649 650 651 652 653 654

  /* 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
655 656 657 658 659 660 661 662 663
  /* 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;
    }
  }

664
  NR_CellGroupConfig_t *cellGroupConfig = ue_p->masterCellGroup;
665

666
  uint8_t buffer[RRC_BUF_SIZE] = {0};
667
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, false);
668
  NR_DRB_ToAddModList_t *DRBs = createDRBlist(ue_p, false);
luis_pereira87's avatar
luis_pereira87 committed
669

670
  int size = do_RRCReconfiguration(ue_p,
671 672 673
                                   buffer,
                                   RRC_BUF_SIZE,
                                   xid,
laurent's avatar
laurent committed
674
                                   SRBs,
luis_pereira87's avatar
luis_pereira87 committed
675
                                   DRBs,
676
                                   ue_p->DRB_ReleaseList,
677 678 679 680
                                   NULL,
                                   NULL,
                                   dedicatedNAS_MessageList,
                                   cellGroupConfig);
681
  LOG_DUMPMSG(NR_RRC,DEBUG_RRC,(char *)buffer,size,"[MSG] RRC Reconfiguration\n");
laurent's avatar
laurent committed
682
  freeSRBlist(SRBs);
luis_pereira87's avatar
luis_pereira87 committed
683
  freeDRBlist(DRBs);
684 685 686
  ASN_STRUCT_FREE(asn_DEF_NR_DRB_ToReleaseList, ue_p->DRB_ReleaseList);
  ue_p->DRB_ReleaseList = NULL;

687
  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);
688 689
  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",
690 691 692 693 694 695 696
        ctxt_pP->frame,
        ctxt_pP->module_id,
        size,
        ue_p->rnti,
        rrc_gNB_mui,
        ctxt_pP->module_id,
        DCCH);
697

698
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
699 700
}

701
//-----------------------------------------------------------------------------
Masayuki Harada's avatar
Masayuki Harada committed
702
void
703 704 705 706 707
rrc_gNB_modify_dedicatedRRCReconfiguration(
  const protocol_ctxt_t     *const ctxt_pP,
  rrc_gNB_ue_context_t      *ue_context_pP)
//-----------------------------------------------------------------------------
{
708 709
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
  NR_DRB_ToAddModList_t *DRB_configList = fill_DRB_configList(ue_p);
710
  int qos_flow_index = 0;
711
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
712
  ue_p->xids[xid] = RRC_PDUSESSION_MODIFY;
713

714 715 716
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList =
      CALLOC(1, sizeof(*dedicatedNAS_MessageList));
  NR_DRB_ToAddMod_t *DRB_config = NULL;
717

718
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
719
    // bypass the new and already configured pdu sessions
720 721
    if (ue_p->pduSession[i].status >= PDU_SESSION_STATUS_DONE) {
      ue_p->pduSession[i].xid = xid;
722 723 724
      continue;
    }

725
    if (ue_p->pduSession[i].cause != NGAP_CAUSE_NOTHING) {
726
      // set xid of failure pdu session
727 728
      ue_p->pduSession[i].xid = xid;
      ue_p->pduSession[i].status = PDU_SESSION_STATUS_FAILED;
729 730 731 732
      continue;
    }

    // search exist DRB_config
733
    int j;
734
    for (j = 0; i < MAX_DRBS_PER_UE; j++) {
735 736
      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)
737 738 739
        break;
    }

740
    if (j == MAX_DRBS_PER_UE) {
741 742 743 744
      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;
745 746 747 748
      continue;
    }

    // Reference TS23501 Table 5.7.4-1: Standardized 5QI to QoS characteristics mapping
749 750
    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) {
751 752 753 754 755 756 757 758 759 760 761 762 763
        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:
764 765 766 767 768
          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;
769 770
          continue;
      }
771 772 773 774 775 776
      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,
777
            ue_p->pduSession[i].param.qos[qos_flow_index].fiveQI);
778 779
    }

780
    asn1cSeqAdd(&DRB_configList->list, DRB_config);
781

782 783
    ue_p->pduSession[i].status = PDU_SESSION_STATUS_DONE;
    ue_p->pduSession[i].xid = xid;
784

785 786 787 788
    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);
789
    } else {
790
      LOG_W(NR_RRC, "no NAS info (pdusession id %d)\n", ue_p->pduSession[i].param.pdusession_id);
791 792 793 794 795 796 797 798 799
    }
  }

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

800
  uint8_t buffer[RRC_BUF_SIZE];
801
  int size = do_RRCReconfiguration(ue_p,
802 803 804 805 806 807 808 809 810 811
                                   buffer,
                                   RRC_BUF_SIZE,
                                   xid,
                                   NULL,
                                   DRB_configList,
                                   NULL,
                                   NULL,
                                   NULL,
                                   dedicatedNAS_MessageList,
                                   NULL);
812 813 814
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC, (char *)buffer, size, "[MSG] RRC Reconfiguration\n");

  /* Free all NAS PDUs */
815 816
  for (int i = 0; i < ue_p->nb_of_pdusessions; i++) {
    if (ue_p->pduSession[i].param.nas_pdu.buffer != NULL) {
817
      /* Free the NAS PDU buffer and invalidate it */
818 819
      free(ue_p->pduSession[i].param.nas_pdu.buffer);
      ue_p->pduSession[i].param.nas_pdu.buffer = NULL;
820 821 822
    }
  }

823
  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);
824 825
  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",
826 827 828 829 830 831 832
        ctxt_pP->frame,
        ctxt_pP->module_id,
        size,
        ue_p->rnti,
        rrc_gNB_mui,
        ctxt_pP->module_id,
        DCCH);
833

834
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
835
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
836 837
}

838 839 840 841 842 843 844 845 846 847
//-----------------------------------------------------------------------------
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)
//-----------------------------------------------------------------------------
{
848
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
849

850
  NR_DRB_ToReleaseList_t *DRB_Release_configList2 = CALLOC(sizeof(*DRB_Release_configList2), 1);
851

852
  for (int i = 0; i < NB_RB_MAX; i++) {
853
    if ((ue_p->pduSession[i].status == PDU_SESSION_STATUS_TORELEASE) && ue_p->pduSession[i].xid == xid) {
854 855
      asn1cSequenceAdd(DRB_Release_configList2->list, NR_DRB_Identity_t, DRB_release);
      *DRB_release = i + 1;
856 857 858 859
    }
  }

  /* If list is empty free the list and reset the address */
860
  struct NR_RRCReconfiguration_v1530_IEs__dedicatedNAS_MessageList *dedicatedNAS_MessageList = NULL;
861
  if (nas_length > 0) {
862 863 864
    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);
865 866 867 868 869
    LOG_I(NR_RRC,"add NAS info with size %d\n", nas_length);
  } else {
    LOG_W(NR_RRC,"dedlicated NAS list is empty\n");
  }

870
  uint8_t buffer[RRC_BUF_SIZE] = {0};
871
  int size = do_RRCReconfiguration(ue_p,
872 873 874 875 876
                                   buffer,
                                   RRC_BUF_SIZE,
                                   xid,
                                   NULL,
                                   NULL,
877
                                   DRB_Release_configList2,
878 879 880 881
                                   NULL,
                                   NULL,
                                   dedicatedNAS_MessageList,
                                   NULL);
882
  LOG_DUMPMSG(NR_RRC,DEBUG_RRC,(char *)buffer,size, "[MSG] RRC Reconfiguration\n");
883 884 885 886 887 888 889

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

890
  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);
891 892
  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",
893 894 895 896 897 898 899
        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
900

901
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
902
  nr_rrc_transfer_protected_rrc_message(rrc, ue_p, DCCH, buffer, size);
903 904
}

905 906 907 908
//-----------------------------------------------------------------------------
/*
* Process the RRC Reconfiguration Complete from the UE
*/
909
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)
910
{
911
  int                                 drb_id;
mir's avatar
mir committed
912 913 914 915
  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
916
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
917
  NR_DRB_ToAddModList_t *DRB_configList = createDRBlist(ue_p, false);
918

919 920
  /* Derive the keys from kgnb */
  if (DRB_configList != NULL) {
mir's avatar
mir committed
921 922
    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);
923 924
  }

mir's avatar
mir committed
925 926
  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);
927

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

932
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, false);
Robert Schmidt's avatar
Robert Schmidt committed
933
  nr_pdcp_add_srbs(ctxt_pP->enb_flag,
934
                   ue_p->rrc_ue_id,
Robert Schmidt's avatar
Robert Schmidt committed
935 936 937 938 939
                   SRBs,
                   (ue_p->integrity_algorithm << 4) | ue_p->ciphering_algorithm,
                   kRRCenc,
                   kRRCint);
  freeSRBlist(SRBs);
940
  nr_pdcp_add_drbs(ctxt_pP->enb_flag,
941
                   ue_p->rrc_ue_id,
942
                   DRB_configList,
943
                   (ue_p->integrity_algorithm << 4) | ue_p->ciphering_algorithm,
944
                   kUPenc,
945
                   kUPint);
946

947 948 949 950 951
  /* 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;
952 953 954 955 956 957 958
        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);
959

960 961
        if (ue_p->DRB_active[drb_id - 1] == 0) {
          ue_p->DRB_active[drb_id - 1] = DRB_ACTIVE;
962 963
          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);
964

965 966 967
          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));
968

yaojie's avatar
yaojie committed
969 970 971
          //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;
          //}
972

973
            // rrc_mac_config_req_eNB
laurent's avatar
laurent committed
974
        } else { // remove LCHAN from MAC/PHY
975
          if (ue_p->DRB_active[drb_id] == 1) {
yoshio.inoue's avatar
yoshio.inoue committed
976
            /* TODO : It may be needed if gNB goes into full stack working. */
977 978 979 980
            // 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
981
            /*rrc_rlc_config_req(ctxt_pP,
982 983 984
                                SRB_FLAG_NO,
                                MBMS_FLAG_NO,
                                CONFIG_ACTION_REMOVE,
Robert Schmidt's avatar
Robert Schmidt committed
985
                                nr_DRB2LCHAN[i]);*/
986 987
          }

988
          // ue_p->DRB_active[drb_id] = 0;
989 990 991 992 993
          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

994
        } // end else of if (ue_p->DRB_active[drb_id] == 0)
995 996 997 998
      } // end if (DRB_configList->list.array[i])
    } // end for (int i = 0; i < DRB_configList->list.count; i++)

  } // end if DRB_configList != NULL
999
  freeDRBlist(DRB_configList);
1000
}
1001

yaojie's avatar
yaojie committed
1002
//-----------------------------------------------------------------------------
1003
static void rrc_gNB_generate_RRCReestablishment(rrc_gNB_ue_context_t *ue_context_pP,
1004
                                                const uint8_t *masterCellGroup_from_DU,
1005
                                                const rnti_t old_rnti,
1006
                                                const nr_rrc_du_container_t *du)
yaojie's avatar
yaojie committed
1007 1008
//-----------------------------------------------------------------------------
{
1009 1010
  module_id_t module_id = 0;
  gNB_RRC_INST *rrc = RC.nrrrc[module_id];
1011
  int enable_ciphering = 0;
1012
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
1013

1014
  uint8_t buffer[RRC_BUF_SIZE] = {0};
1015 1016
  uint8_t xid = rrc_gNB_get_next_transaction_identifier(module_id);
  ue_p->xids[xid] = RRC_REESTABLISH;
1017
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, true);
1018 1019 1020
  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);
1021

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

mir's avatar
mir committed
1024 1025 1026
  uint8_t kRRCenc[16] = {0};
  uint8_t kRRCint[16] = {0};
  uint8_t kUPenc[16] = {0};
1027
  /* Derive the keys from kgnb */
laurent's avatar
laurent committed
1028
  if (ue_p->Srb[1].Active)
mir's avatar
mir committed
1029
    nr_derive_key(UP_ENC_ALG, ue_p->ciphering_algorithm, ue_p->kgnb, kUPenc);
1030

mir's avatar
mir committed
1031 1032
  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
1033
  freeSRBlist(SRBs);
1034
  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);
1035 1036 1037
  uint8_t security_mode =
      enable_ciphering ? ue_p->ciphering_algorithm | (ue_p->integrity_algorithm << 4) : 0 | (ue_p->integrity_algorithm << 4);

1038 1039 1040 1041 1042 1043
  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);
    }
  }

1044
  // TODO: should send E1 UE Bearer Modification with PDCP Reestablishment flag
1045
  nr_pdcp_reestablishment(ue_p->rrc_ue_id);
1046

1047 1048 1049 1050 1051 1052 1053 1054
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
  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};
  deliver_dl_rrc_message_data_t data = {.rrc = rrc, .dl_rrc = &dl_rrc};
  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);
1055 1056
}

1057 1058 1059 1060 1061
/// @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
1062 1063 1064
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)
1065
{
1066
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
1067 1068 1069
  LOG_I(NR_RRC,
        "[RAPROC] UE %04x Logical Channel UL-DCCH, processing NR_RRCReestablishmentComplete from UE (SRB1 Active)\n",
        ue_p->rnti);
1070 1071 1072

  int i = 0;

1073
  uint8_t new_xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
1074
  ue_p->xids[new_xid] = RRC_REESTABLISH_COMPLETE;
1075
  ue_p->StatusRrc = NR_RRC_CONNECTED;
laurent's avatar
laurent committed
1076 1077 1078 1079 1080 1081 1082

  ue_p->Srb[1].Active = 1;
  if (get_softmodem_params()->sa) {
    uint8_t send_security_mode_command = false;
    nr_rrc_pdcp_config_security(ctxt_pP, ue_context_pP, send_security_mode_command);
    LOG_D(NR_RRC, "RRC Reestablishment - set security successfully \n");
  }
1083

1084 1085
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
  NR_CellGroupConfig_t *cellGroupConfig = calloc(1, sizeof(NR_CellGroupConfig_t));
1086

1087
  cellGroupConfig->spCellConfig = ue_p->masterCellGroup->spCellConfig;
1088
  cellGroupConfig->mac_CellGroupConfig = ue_p->masterCellGroup->mac_CellGroupConfig;
1089
  cellGroupConfig->physicalCellGroupConfig = ue_p->masterCellGroup->physicalCellGroupConfig;
1090 1091 1092 1093 1094 1095 1096 1097 1098
  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]);
1099 1100

  for (i = 0; i < cellGroupConfig->rlc_BearerToAddModList->list.count; i++) {
1101 1102
    asn1cCallocOne(cellGroupConfig->rlc_BearerToAddModList->list.array[i]->reestablishRLC,
                   NR_RLC_BearerConfig__reestablishRLC_true);
1103 1104
  }

1105
  NR_SRB_ToAddModList_t *SRBs = createSRBlist(ue_p, true);
1106 1107 1108
  NR_DRB_ToAddModList_t *DRBs = createDRBlist(ue_p, true);

  uint8_t buffer[RRC_BUF_SIZE] = {0};
1109
  int size = do_RRCReconfiguration(ue_p,
1110 1111 1112
                                   buffer,
                                   RRC_BUF_SIZE,
                                   new_xid,
laurent's avatar
laurent committed
1113
                                   SRBs,
1114
                                   DRBs,
1115 1116 1117 1118 1119
                                   NULL,
                                   NULL,
                                   NULL, // MeasObj_list,
                                   NULL,
                                   cellGroupConfig);
laurent's avatar
laurent committed
1120
  freeSRBlist(SRBs);
1121
  freeDRBlist(DRBs);
1122
  LOG_DUMPMSG(NR_RRC, DEBUG_RRC, (char *)buffer, size, "[MSG] RRC Reconfiguration\n");
1123

1124 1125 1126 1127 1128 1129 1130
  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);
1131
}
1132 1133
//-----------------------------------------------------------------------------

1134 1135
int nr_rrc_reconfiguration_req(rrc_gNB_ue_context_t         *const ue_context_pP,
                               protocol_ctxt_t              *const ctxt_pP,
1136 1137
                               const int                    dl_bwp_id,
                               const int                    ul_bwp_id) {
1138 1139

  uint8_t xid = rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id);
1140
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
1141
  ue_p->xids[xid] = RRC_DEDICATED_RECONF;
1142

1143
  NR_CellGroupConfig_t *masterCellGroup = ue_p->masterCellGroup;
1144
  if (dl_bwp_id > 0) {
1145 1146 1147
    *masterCellGroup->spCellConfig->spCellConfigDedicated->firstActiveDownlinkBWP_Id = dl_bwp_id;
    *masterCellGroup->spCellConfig->spCellConfigDedicated->defaultDownlinkBWP_Id = dl_bwp_id;
  }
1148
  if (ul_bwp_id > 0) {
1149 1150
    *masterCellGroup->spCellConfig->spCellConfigDedicated->uplinkConfig->firstActiveUplinkBWP_Id = ul_bwp_id;
  }
1151

1152
  uint8_t buffer[RRC_BUF_SIZE];
1153
  int size = do_RRCReconfiguration(ue_p, buffer, RRC_BUF_SIZE, xid, NULL, NULL, NULL, NULL, NULL, NULL, masterCellGroup);
1154

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

1158 1159 1160
  return 0;
}

1161
/*------------------------------------------------------------------------------*/
1162
static int nr_rrc_gNB_decode_ccch(module_id_t module_id, const f1ap_initial_ul_rrc_message_t *msg)
1163
{
1164
  asn_dec_rval_t                                    dec_rval;
1165
  NR_UL_CCCH_Message_t *ul_ccch_msg = NULL;
1166
  gNB_RRC_INST *gnb_rrc_inst = RC.nrrrc[module_id];
1167
  NR_RRCSetupRequest_IEs_t                         *rrcSetupRequest = NULL;
1168
  NR_RRCReestablishmentRequest_IEs_t rrcReestablishmentRequest;
1169
  rnti_t rnti = msg->crnti;
1170

Robert Schmidt's avatar
Robert Schmidt committed
1171 1172 1173 1174
  /* look up corresponding DU. For the moment, there is only one */
  const nr_rrc_du_container_t *du = gnb_rrc_inst->du;
  AssertFatal(du != NULL, "received CCCH message, but no corresponding DU found\n");

1175 1176 1177
  LOG_I(NR_RRC, "Decoding CCCH: RNTI %04x, payload_size %d\n", rnti, msg->rrc_container_length);
  dec_rval =
      uper_decode(NULL, &asn_DEF_NR_UL_CCCH_Message, (void **)&ul_ccch_msg, msg->rrc_container, msg->rrc_container_length, 0, 0);
1178

1179
  if (dec_rval.code != RC_OK || dec_rval.consumed == 0) {
1180
    LOG_E(NR_RRC, " FATAL Error in receiving CCCH\n");
1181 1182
    return -1;
  }
1183

1184 1185
  if (ul_ccch_msg->message.present == NR_UL_CCCH_MessageType_PR_c1) {
    switch (ul_ccch_msg->message.choice.c1->present) {
1186
      case NR_UL_CCCH_MessageType__c1_PR_NOTHING:
1187
        /* TODO */
1188
        LOG_I(NR_RRC, "Received PR_NOTHING on UL-CCCH-Message\n");
1189 1190 1191
        break;

      case NR_UL_CCCH_MessageType__c1_PR_rrcSetupRequest:
1192
        LOG_D(NR_RRC, "Received RRCSetupRequest on UL-CCCH-Message (UE rnti %04x)\n", rnti);
1193
        {
1194
          rrcSetupRequest = &ul_ccch_msg->message.choice.c1->choice.rrcSetupRequest->rrcSetupRequest;
1195
          rrc_gNB_ue_context_t *ue_context_p = NULL;
1196 1197 1198
          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
1199
              LOG_E(NR_RRC, "wrong InitialUE-Identity randomValue size, expected 5, provided %lu", (long unsigned int)rrcSetupRequest->ue_Identity.choice.randomValue.size);
1200
              ASN_STRUCT_FREE(asn_DEF_NR_UL_CCCH_Message, ul_ccch_msg);
1201 1202
              return -1;
            }
1203
            uint64_t random_value = 0;
1204
            memcpy(((uint8_t *)&random_value) + 3, rrcSetupRequest->ue_Identity.choice.randomValue.buf, rrcSetupRequest->ue_Identity.choice.randomValue.size);
1205 1206

            /* if there is already a registered UE (with another RNTI) with this random_value,
1207 1208
             * the current one must be removed from MAC/PHY (zombie UE)
             */
1209 1210
            if ((ue_context_p = rrc_gNB_ue_context_random_exist(gnb_rrc_inst, random_value))) {
              LOG_W(NR_RRC, "new UE rnti (coming with random value) is already there, removing UE %x from MAC/PHY\n", rnti);
1211
              AssertFatal(false, "not implemented\n");
1212 1213
            }

1214
            ue_context_p = rrc_gNB_create_ue_context(rnti, gnb_rrc_inst, random_value, msg->gNB_DU_ue_id);
1215 1216 1217 1218 1219
          } else if (NR_InitialUE_Identity_PR_ng_5G_S_TMSI_Part1 == rrcSetupRequest->ue_Identity.present) {
            /* TODO */
            /* <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) {
1220
              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);
1221
              ASN_STRUCT_FREE(asn_DEF_NR_UL_CCCH_Message, ul_ccch_msg);
1222 1223 1224 1225 1226 1227 1228 1229 1230
              return -1;
            }

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

            // 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);

1231 1232 1233
            if ((ue_context_p = rrc_gNB_ue_context_5g_s_tmsi_exist(gnb_rrc_inst, 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, rnti);
1234
              AssertFatal(false, "not implemented\n");
1235 1236

              /* replace rnti in the context */
1237
              UE->rnti = rnti;
1238
            } else {
1239
              LOG_I(NR_RRC, "UE %04x 5G-S-TMSI-Part1 doesn't exist, setting ng_5G_S_TMSI_Part1 => %ld\n", rnti, s_tmsi_part1);
1240

1241
              ue_context_p = rrc_gNB_create_ue_context(rnti, gnb_rrc_inst, s_tmsi_part1, msg->gNB_DU_ue_id);
1242
              AssertFatal(ue_context_p != NULL, "out of memory\n");
1243
              gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1244 1245
              UE->Initialue_identity_5g_s_TMSI.presence = true;
              UE->ng_5G_S_TMSI_Part1 = s_tmsi_part1;
1246
            }
1247 1248
          } else {
            /* TODO */
1249
            uint64_t random_value = 0;
1250
            memcpy(((uint8_t *)&random_value) + 3, rrcSetupRequest->ue_Identity.choice.randomValue.buf, rrcSetupRequest->ue_Identity.choice.randomValue.size);
1251

1252
            ue_context_p = rrc_gNB_create_ue_context(rnti, gnb_rrc_inst, random_value, msg->gNB_DU_ue_id);
1253 1254
            LOG_E(NR_RRC, "RRCSetupRequest without random UE identity or S-TMSI not supported, let's reject the UE %04x\n", rnti);
            rrc_gNB_generate_RRCReject(module_id, ue_context_p);
1255 1256
            break;
          }
1257 1258
          gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
          UE = &ue_context_p->ue_context;
1259
          UE->establishment_cause = rrcSetupRequest->establishmentCause;
laurent's avatar
laurent committed
1260
          UE->Srb[1].Active = 1;
1261 1262
          rrc_gNB_generate_RRCSetup(module_id,
                                    rnti,
1263
                                    ue_context_p,
1264 1265
                                    msg->du2cu_rrc_container,
                                    msg->du2cu_rrc_container_length);
1266
        }
1267 1268 1269
        break;

      case NR_UL_CCCH_MessageType__c1_PR_rrcResumeRequest:
1270
        LOG_I(NR_RRC, "receive rrcResumeRequest message \n");
1271 1272
        break;

1273
      case NR_UL_CCCH_MessageType__c1_PR_rrcReestablishmentRequest: {
1274 1275 1276 1277 1278
        LOG_DUMPMSG(NR_RRC,
                    DEBUG_RRC,
                    (char *)(msg->rrc_container),
                    msg->rrc_container_length,
                    "[MSG] RRC Reestablishment Request\n");
yaojie's avatar
yaojie committed
1279
        rrcReestablishmentRequest = ul_ccch_msg->message.choice.c1->choice.rrcReestablishmentRequest->rrcReestablishmentRequest;
1280 1281
        const NR_ReestablishmentCause_t cause = rrcReestablishmentRequest.reestablishmentCause;
        const long physCellId = rrcReestablishmentRequest.ue_Identity.physCellId;
yaojie's avatar
yaojie committed
1282
        LOG_I(NR_RRC,
1283
              "UE %04x physCellId %ld NR_RRCReestablishmentRequest cause %s\n",
1284
              rnti,
1285 1286 1287 1288
              physCellId,
              cause == NR_ReestablishmentCause_otherFailure
                  ? "Other Failure"
                  : (cause == NR_ReestablishmentCause_handoverFailure ? "Handover Failure" : "reconfigurationFailure"));
Robert Schmidt's avatar
Robert Schmidt committed
1289 1290 1291 1292

        AssertFatal(du->setup_req->num_cells_available == 1, "cannot handle more than one cell\n");
        const f1ap_served_cell_info_t *cell_info = &du->setup_req->cell[0].info;
        if (physCellId != cell_info->nr_pci) {
1293 1294
          /* UE was moving from previous cell so quickly that RRCReestablishment for previous cell was received in this cell */
          LOG_E(NR_RRC,
Robert Schmidt's avatar
Robert Schmidt committed
1295
                " NR_RRCReestablishmentRequest ue_Identity.physCellId(%ld) is not equal to current physCellId(%d), fallback to RRC establishment\n",
1296
                physCellId,
Robert Schmidt's avatar
Robert Schmidt committed
1297
                cell_info->nr_pci);
1298 1299 1300 1301
          /* 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" we did not implement this yet; TBD for Multi-DU */
          AssertFatal(false, "not implemented\n");
1302 1303
          break;
        }
1304

1305 1306 1307
        for (int i = 0; i < rrcReestablishmentRequest.ue_Identity.shortMAC_I.size; i++) {
          LOG_D(NR_RRC, "rrcReestablishmentRequest.ue_Identity.shortMAC_I.buf[%d] = %x\n", i, rrcReestablishmentRequest.ue_Identity.shortMAC_I.buf[i]);
        }
yaojie's avatar
yaojie committed
1308

1309 1310 1311
        rnti_t old_rnti = rrcReestablishmentRequest.ue_Identity.c_RNTI;
        // TODO: we need to check within a specific DU!
        rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context_by_rnti(gnb_rrc_inst, old_rnti);
1312
        gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1313 1314 1315 1316
        /* in case we need to do RRC Setup, give the UE a new random identity */
        uint64_t random_value;
        fill_random(&random_value, sizeof(random_value));
        random_value = random_value & 0x7fffffffff; /* random value is 39 bits */
1317
        if (ue_context_p == NULL) {
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
          LOG_E(NR_RRC, "NR_RRCReestablishmentRequest without UE context, fallback to RRC setup\n");
          ue_context_p = rrc_gNB_create_ue_context(rnti, gnb_rrc_inst, random_value, msg->gNB_DU_ue_id);
          ue_context_p->ue_context.Srb[1].Active = 1;
          rrc_gNB_generate_RRCSetup(module_id, rnti, ue_context_p, msg->du2cu_rrc_container, msg->du2cu_rrc_container_length);
          break;
        }

        // 3GPP TS 38.321 version 15.13.0 Section 7.1 Table 7.1-1: RNTI values
        if (rrcReestablishmentRequest.ue_Identity.c_RNTI < 0x1 || rrcReestablishmentRequest.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",
                rrcReestablishmentRequest.ue_Identity.c_RNTI);
          ue_context_p = rrc_gNB_create_ue_context(rnti, gnb_rrc_inst, random_value, msg->gNB_DU_ue_id);
          ue_context_p->ue_context.Srb[1].Active = 1;
          rrc_gNB_generate_RRCSetup(module_id, rnti, ue_context_p, msg->du2cu_rrc_container, msg->du2cu_rrc_container_length);
1334 1335
          break;
        }
1336

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

1339 1340 1341 1342 1343
        // update with new RNTI, and update secondary UE association
        UE->rnti = rnti;
        cu_remove_f1_ue_data(UE->rrc_ue_id);
        f1_ue_data_t ue_data = {.secondary_ue = rnti};
        cu_add_f1_ue_data(UE->rrc_ue_id, &ue_data);
1344

1345 1346
        UE->reestablishment_cause = cause;
        LOG_D(NR_RRC, "Accept RRCReestablishmentRequest from UE physCellId %ld cause %ld\n", physCellId, cause);
1347

1348
        rrc_gNB_generate_RRCReestablishment(ue_context_p,
1349
                                            msg->du2cu_rrc_container,
1350
                                            old_rnti,
1351
                                            du);
1352
      } break;
1353 1354

      case NR_UL_CCCH_MessageType__c1_PR_rrcSystemInfoRequest:
1355
        LOG_I(NR_RRC, "UE %04x receive rrcSystemInfoRequest message \n", rnti);
1356 1357 1358 1359
        /* TODO */
        break;

      default:
1360
        LOG_E(NR_RRC, "UE %04x Unknown message\n", rnti);
1361
        break;
1362
    }
1363
  }
1364
  ASN_STRUCT_FREE(asn_DEF_NR_UL_CCCH_Message, ul_ccch_msg);
1365
  return 0;
1366 1367
}

Xue Song's avatar
Xue Song committed
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
/*! \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.
 */
static inline uint64_t bitStr_to_uint64(BIT_STRING_t *asn) {
  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
1391
static void rrc_gNB_process_MeasurementReport(rrc_gNB_ue_context_t *ue_context, NR_MeasurementReport_t *measurementReport)
1392 1393 1394 1395 1396 1397 1398
{
  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);

1399
  gNB_RRC_UE_t *ue_ctxt = &ue_context->ue_context;
Robert Schmidt's avatar
Robert Schmidt committed
1400 1401
  ASN_STRUCT_FREE(asn_DEF_NR_MeasResults, ue_ctxt->measResults);
  ue_ctxt->measResults = NULL;
1402

1403 1404 1405
  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
1406 1407 1408
  /* we "keep" the measurement report, so set to 0 */
  free(measurementReport->criticalExtensions.choice.measurementReport);
  measurementReport->criticalExtensions.choice.measurementReport = NULL;
1409 1410
}

1411
static int handle_rrcReestablishmentComplete(const protocol_ctxt_t *const ctxt_pP,
1412
                                             rrc_gNB_ue_context_t *ue_context_p,
1413 1414
                                             const NR_RRCReestablishmentComplete_t *reestablishment_complete)
{
1415 1416
  DevAssert(ue_context_p != NULL);
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440

  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;
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452

    /* 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;
    }

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 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    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;
  }

  if (get_softmodem_params()->sa) {
    rrc_gNB_send_NGAP_UE_CAPABILITIES_IND(ctxt_pP, ue_context_p, ue_cap_info);
  }

1530 1531 1532 1533 1534 1535 1536
  // 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);

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 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
  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);

1608
  bool successful_reconfig = true;
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
  if (get_softmodem_params()->sa) {
    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;
1624
      case RRC_DEFAULT_RECONF:
1625
        rrc_gNB_send_NGAP_INITIAL_CONTEXT_SETUP_RESP(ctxt_pP, ue_context_p);
1626
        break;
1627
      case RRC_REESTABLISH_COMPLETE:
1628
      case RRC_DEDICATED_RECONF:
1629 1630
        /* do nothing */
        break;
1631
      default:
1632
        LOG_E(RRC, "Received unexpected transaction type %d for xid %d\n", UE->xids[xid], xid);
1633 1634
        successful_reconfig = false;
        break;
1635 1636
    }
  }
1637 1638

  gNB_RRC_INST *rrc = RC.nrrrc[0];
1639
  f1_ue_data_t ue_data = cu_get_f1_ue_data(UE->rrc_ue_id);
1640
  f1ap_ue_context_modif_req_t ue_context_modif_req = {
1641
    .gNB_CU_ue_id = UE->rrc_ue_id,
1642
    .gNB_DU_ue_id = ue_data.secondary_ue,
1643 1644 1645
    .plmn.mcc = rrc->configuration.mcc[0],
    .plmn.mnc = rrc->configuration.mnc[0],
    .plmn.mnc_digit_length = rrc->configuration.mnc_digit_length[0],
1646 1647 1648 1649 1650
    .nr_cellid = rrc->nr_cellid,
    .servCellId = 0, /* TODO: correct value? */
    .ReconfigComplOutcome = successful_reconfig ? RRCreconf_success : RRCreconf_failure,
  };
  rrc->mac_rrc.ue_context_modification_request(&ue_context_modif_req);
1651
}
Xue Song's avatar
Xue Song committed
1652
//-----------------------------------------------------------------------------
1653 1654 1655 1656
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
1657 1658
//-----------------------------------------------------------------------------
{
1659
  gNB_RRC_INST *gnb_rrc_inst = RC.nrrrc[ctxt_pP->module_id];
Xue Song's avatar
Xue Song committed
1660

1661 1662 1663 1664 1665 1666 1667
  /* 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;
  }

1668
  if ((Srb_id != 1) && (Srb_id != 2)) {
1669
    LOG_E(NR_RRC, "Received message on SRB%ld, should not have ...\n", Srb_id);
1670
  } else {
1671
    LOG_D(NR_RRC, "Received message on SRB%ld\n", Srb_id);
1672 1673
  }

1674
  LOG_D(NR_RRC, "Decoding UL-DCCH Message\n");
1675
  {
1676
    for (int i = 0; i < sdu_sizeP; i++) {
1677
      LOG_T(NR_RRC, "%x.", Rx_sdu[i]);
Xue Song's avatar
Xue Song committed
1678 1679
    }

1680 1681
    LOG_T(NR_RRC, "\n");
  }
Xue Song's avatar
Xue Song committed
1682

1683 1684 1685
  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);

1686
  if ((dec_rval.code != RC_OK) && (dec_rval.consumed == 0)) {
1687
    LOG_E(NR_RRC, "Failed to decode UL-DCCH (%zu bytes)\n", dec_rval.consumed);
1688 1689 1690
    return -1;
  }

1691 1692 1693 1694
  if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
    xer_fprint(stdout, &asn_DEF_NR_UL_DCCH_Message, (void *)ul_dcch_msg);
  }

1695 1696 1697
  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:
1698
        LOG_I(NR_RRC, "Received PR_NOTHING on UL-DCCH-Message\n");
1699
        break;
Xue Song's avatar
Xue Song committed
1700

1701
      case NR_UL_DCCH_MessageType__c1_PR_rrcReconfigurationComplete:
1702
        handle_rrcReconfigurationComplete(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.rrcReconfigurationComplete);
1703 1704 1705
        break;

      case NR_UL_DCCH_MessageType__c1_PR_rrcSetupComplete:
1706 1707
        if (handle_rrcSetupComplete(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.rrcSetupComplete) == -1)
          return -1;
1708
        break;
wujing's avatar
wujing committed
1709

1710 1711 1712 1713 1714 1715 1716 1717
      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;

1718
      case NR_UL_DCCH_MessageType__c1_PR_ulInformationTransfer:
Robert Schmidt's avatar
Robert Schmidt committed
1719
        LOG_D(NR_RRC, "Recived RRC GNB UL Information Transfer \n");
1720
        if (!ue_context_p) {
Robert Schmidt's avatar
Robert Schmidt committed
1721
          LOG_W(NR_RRC, "Processing ulInformationTransfer UE %lx, ue_context_p is NULL\n", ctxt_pP->rntiMaybeUEid);
1722 1723
          break;
        }
wujing's avatar
wujing committed
1724

1725 1726
        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
1727

1728 1729 1730 1731
        if (get_softmodem_params()->sa) {
          rrc_gNB_send_NGAP_UPLINK_NAS(ctxt_pP, ue_context_p, ul_dcch_msg);
        }
        break;
wujing's avatar
wujing committed
1732

1733
      case NR_UL_DCCH_MessageType__c1_PR_securityModeComplete:
1734
        // to avoid segmentation fault
1735 1736 1737 1738
        if (!ue_context_p) {
          LOG_I(NR_RRC, "Processing securityModeComplete UE %lx, ue_context_p is NULL\n", ctxt_pP->rntiMaybeUEid);
          break;
        }
1739 1740

        LOG_I(NR_RRC,
1741
              PROTOCOL_NR_RRC_CTXT_UE_FMT " received securityModeComplete on UL-DCCH %d from UE\n",
1742 1743 1744
              PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
              DCCH);
        LOG_D(NR_RRC,
1745 1746
              PROTOCOL_NR_RRC_CTXT_UE_FMT
              " RLC RB %02d --- RLC_DATA_IND %d bytes "
1747 1748 1749 1750 1751
              "(securityModeComplete) ---> RRC_eNB\n",
              PROTOCOL_NR_RRC_CTXT_UE_ARGS(ctxt_pP),
              DCCH,
              sdu_sizeP);

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

Cedric Roux's avatar
Cedric Roux committed
1756 1757 1758
        /* configure ciphering */
        nr_rrc_pdcp_config_security(ctxt_pP, ue_context_p, 1);

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

1762 1763 1764 1765 1766 1767 1768 1769 1770
      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);
1771

1772 1773
        if (LOG_DEBUGFLAG(DEBUG_ASN1)) {
          xer_fprint(stdout, &asn_DEF_NR_UL_DCCH_Message, (void *)ul_dcch_msg);
1774 1775
        }

1776 1777
        rrc_gNB_generate_UECapabilityEnquiry(ctxt_pP, ue_context_p);
        break;
1778

1779 1780 1781 1782 1783
      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;
1784

1785
      case NR_UL_DCCH_MessageType__c1_PR_rrcReestablishmentComplete:
1786
        if (handle_rrcReestablishmentComplete(ctxt_pP, ue_context_p, ul_dcch_msg->message.choice.c1->choice.rrcReestablishmentComplete)
1787 1788 1789
            == -1)
          return -1;
        break;
1790

1791 1792
      default:
        break;
Xue Song's avatar
Xue Song committed
1793
    }
1794
  }
1795
  ASN_STRUCT_FREE(asn_DEF_NR_UL_DCCH_Message, ul_dcch_msg);
1796
  return 0;
Xue Song's avatar
Xue Song committed
1797 1798
}

1799 1800 1801 1802 1803 1804 1805 1806
static bool rrc_gNB_plmn_matches(const gNB_RRC_INST *rrc, const f1ap_served_cell_info_t *info)
{
  const gNB_RrcConfigurationReq *conf = &rrc->configuration;
  return conf->num_plmn == 1 // F1 supports only one
    && conf->mcc[0] == info->plmn.mcc
    && conf->mnc[0] == info->plmn.mnc
    && rrc->nr_cellid == info->nr_cellid;
}
1807

1808
static void rrc_gNB_process_f1_setup_req(f1ap_setup_req_t *req, sctp_assoc_t assoc_id)
1809 1810 1811 1812
{
  gNB_RRC_INST *rrc = RC.nrrrc[0];
  DevAssert(rrc);

1813
  LOG_I(NR_RRC, "Received F1 Setup Request from gNB_DU %lu (%s) on assoc_id %d\n", req->gNB_DU_id, req->gNB_DU_name, assoc_id);
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851

  // check:
  // - it is the first DU
  // - it is one cell
  // - PLMN and Cell ID matches
  // else reject
  f1ap_setup_failure_t fail = {.cause = F1AP_CauseRadioNetwork_gNB_CU_Cell_Capacity_Exceeded};
  if (rrc->du != NULL) {
    const f1ap_setup_req_t *other = rrc->du->setup_req;
    LOG_E(NR_RRC, "can only handle one DU, but already serving DU %ld (%s)\n", other->gNB_DU_id, other->gNB_DU_name);
    rrc->mac_rrc.f1_setup_failure(&fail);
    return;
  }
  if (req->num_cells_available != 1) {
    LOG_E(NR_RRC, "can only handle on DU cell, but gNB_DU %ld has %d\n", req->gNB_DU_id, req->num_cells_available);
    rrc->mac_rrc.f1_setup_failure(&fail);
    return;
  }
  f1ap_served_cell_info_t *cell_info = &req->cell[0].info;
  if (!rrc_gNB_plmn_matches(rrc, cell_info)) {
    LOG_E(NR_RRC,
          "PLMN mismatch: CU %d%d cellID %ld, DU %d%d cellID %ld\n",
          rrc->configuration.mcc[0],
          rrc->configuration.mnc[0],
          rrc->nr_cellid,
          cell_info->plmn.mcc,
          cell_info->plmn.mnc,
          cell_info->nr_cellid);
    rrc->mac_rrc.f1_setup_failure(&fail);
    return;
  }
  // if there is no system info or no SIB1 and we run in SA mode, we cannot handle it
  const f1ap_gnb_du_system_info_t *sys_info = req->cell[0].sys_info;
  if (sys_info == NULL || sys_info->mib == NULL || (sys_info->sib1 == NULL && get_softmodem_params()->sa)) {
    LOG_E(NR_RRC, "no system information provided by DU, rejecting\n");
    rrc->mac_rrc.f1_setup_failure(&fail);
    return;
  }
1852

Robert Schmidt's avatar
Robert Schmidt committed
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
  /* do we need the MIB? for the moment, just check it is valid, then drop it */
  NR_BCCH_BCH_Message_t *mib = NULL;
  asn_dec_rval_t dec_rval =
      uper_decode_complete(NULL, &asn_DEF_NR_BCCH_BCH_Message, (void **)&mib, sys_info->mib, sys_info->mib_length);
  if (dec_rval.code != RC_OK || mib->message.present != NR_BCCH_BCH_MessageType_PR_mib
      || mib->message.choice.messageClassExtension == NULL) {
    LOG_E(RRC, "Failed to decode NR_BCCH_BCH_MESSAGE (%zu bits) of DU, rejecting DU\n", dec_rval.consumed);
    rrc->mac_rrc.f1_setup_failure(&fail);
    ASN_STRUCT_FREE(asn_DEF_NR_BCCH_BCH_Message, mib);
    return;
  }

Robert Schmidt's avatar
Robert Schmidt committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
  NR_SIB1_t *sib1 = NULL;
  if (sys_info->sib1) {
    dec_rval = uper_decode_complete(NULL, &asn_DEF_NR_SIB1, (void **)&sib1, sys_info->sib1, sys_info->sib1_length);
    if (dec_rval.code != RC_OK) {
      LOG_E(RRC, "Failed to decode NR_SIB1 (%zu bits) of DU, rejecting DU\n", dec_rval.consumed);
      rrc->mac_rrc.f1_setup_failure(&fail);
      ASN_STRUCT_FREE(asn_DEF_NR_SIB1, sib1);
      return;
    }
    if (LOG_DEBUGFLAG(DEBUG_ASN1))
      xer_fprint(stdout, &asn_DEF_NR_SIB1, sib1);
  }

1878
  LOG_I(RRC, "Accepting DU %ld (%s), sending F1 Setup Response\n", req->gNB_DU_id, req->gNB_DU_name);
Xue Song's avatar
Xue Song committed
1879

1880 1881 1882
  // we accept the DU
  rrc->du = calloc(1, sizeof(*rrc->du));
  AssertFatal(rrc->du != NULL, "out of memory\n");
1883
  rrc->du->assoc_id = assoc_id;
Xue Song's avatar
Xue Song committed
1884

1885 1886 1887 1888 1889 1890
  /* ITTI will free the setup request message via free(). So the memory
   * "inside" of the message will remain, but the "outside" container no, so
   * allocate memory and copy it in */
  rrc->du->setup_req = malloc(sizeof(*rrc->du->setup_req));
  AssertFatal(rrc->du->setup_req != NULL, "out of memory\n");
  *rrc->du->setup_req = *req;
Robert Schmidt's avatar
Robert Schmidt committed
1891 1892 1893
  rrc->du->mib = mib->message.choice.mib;
  mib->message.choice.mib = NULL;
  ASN_STRUCT_FREE(asn_DEF_NR_BCCH_BCH_MessageType, mib);
Robert Schmidt's avatar
Robert Schmidt committed
1894
  rrc->du->sib1 = sib1;
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927

  served_cells_to_activate_t cell = {
      .plmn = cell_info->plmn,
      .nr_cellid = cell_info->nr_cellid,
      .nrpci = cell_info->nr_pci,
      .num_SI = 0,
  };
  f1ap_setup_resp_t resp = {.num_cells_to_activate = 1, .cells_to_activate[0] = cell};
  if (rrc->node_name != NULL)
    resp.gNB_CU_name = strdup(rrc->node_name);
  rrc->mac_rrc.f1_setup_response(&resp);

  /*
  MessageDef *msg_p2 = itti_alloc_new_message(TASK_RRC_GNB, 0, F1AP_GNB_CU_CONFIGURATION_UPDATE);
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).gNB_CU_name = rrc->node_name;
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].plmn.mcc = rrc->configuration.mcc[0];
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].plmn.mnc = rrc->configuration.mnc[0];
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].plmn.mnc_digit_length = rrc->configuration.mnc_digit_length[0];
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].nr_cellid = rrc->nr_cellid;
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].nrpci = req->cell[0].info.nr_pci;
  int num_SI = 0;

  if (rrc->carrier.SIB23) {
    F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].SI_container[2] = rrc->carrier.SIB23;
    F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].SI_container_length[2] = rrc->carrier.sizeof_SIB23;
    num_SI++;
  }

  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).cells_to_activate[0].num_SI = num_SI;
  F1AP_GNB_CU_CONFIGURATION_UPDATE(msg_p2).num_cells_to_activate = 1;
  // send
  itti_send_msg_to_task(TASK_CU_F1, 0, msg_p2);
  */
Xue Song's avatar
Xue Song committed
1928 1929
}

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
void rrc_gNB_process_initial_ul_rrc_message(const f1ap_initial_ul_rrc_message_t *ul_rrc)
{
  // first get RRC instance (note, no the ITTI instance)
  module_id_t i = 0;
  for (i=0; i < RC.nb_nr_inst; i++) {
    gNB_RRC_INST *rrc = RC.nrrrc[i];
    if (rrc->nr_cellid == ul_rrc->nr_cellid)
      break;
  }
  //AssertFatal(i != RC.nb_nr_inst, "Cell_id not found\n");
  // TODO REMOVE_DU_RRC in monolithic mode, the MAC does not have the
  // nr_cellid. Thus, the above check would fail. For the time being, just put
  // a warning, as we handle one DU only anyway
  if (i == RC.nb_nr_inst) {
    i = 0;
    LOG_W(RRC, "initial UL RRC message nr_cellid %ld does not match RRC's %ld\n", ul_rrc->nr_cellid, RC.nrrrc[0]->nr_cellid);
  }
1947
  nr_rrc_gNB_decode_ccch(i, ul_rrc);
1948 1949 1950 1951 1952 1953 1954

  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
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
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
1967 1968
static void rrc_CU_process_ue_context_setup_response(MessageDef *msg_p, instance_t instance)
{
1969
  f1ap_ue_context_setup_t *resp = &F1AP_UE_CONTEXT_SETUP_RESP(msg_p);
1970
  gNB_RRC_INST *rrc = RC.nrrrc[instance];
1971 1972 1973 1974 1975
  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;
  }
1976
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
1977

1978 1979 1980 1981 1982 1983 1984
  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");
1985

1986 1987 1988
  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);
1989
  }
1990 1991
  UE->masterCellGroup = cellGroupConfig;
  if (LOG_DEBUGFLAG(DEBUG_ASN1))
1992
    xer_fprint(stdout, &asn_DEF_NR_CellGroupConfig, UE->masterCellGroup);
1993

1994 1995 1996
  /* 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) */
1997 1998
}

1999 2000 2001 2002 2003
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];
2004 2005 2006 2007 2008
  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;
  }
2009 2010

  /* TODO: marshall types correctly */
2011
  LOG_I(NR_RRC, "received UE Context Release Request for UE %u, forwarding to AMF\n", req->gNB_CU_ue_id);
2012 2013 2014 2015 2016 2017
  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
2018 2019 2020 2021 2022 2023 2024
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);
}

2025 2026 2027 2028 2029
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];
2030 2031 2032 2033 2034
  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;
  }
2035 2036
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;

2037 2038
  nr_pdcp_remove_UE(UE->rrc_ue_id);
  newGtpuDeleteAllTunnels(instance, UE->rrc_ue_id);
2039
  rrc_gNB_send_NGAP_UE_CONTEXT_RELEASE_COMPLETE(instance, UE->rrc_ue_id);
2040
  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
2041
  rrc_delete_ue_data(UE);
2042 2043 2044
  rrc_gNB_remove_ue_context(rrc, ue_context_p);
}

laurent's avatar
tmp  
laurent committed
2045 2046
static void rrc_CU_process_ue_context_modification_response(MessageDef *msg_p, instance_t instance)
{
2047
  f1ap_ue_context_modif_resp_t *resp = &F1AP_UE_CONTEXT_MODIFICATION_RESP(msg_p);
2048
  protocol_ctxt_t ctxt = {.rntiMaybeUEid = resp->gNB_CU_ue_id, .module_id = instance, .instance = instance, .enb_flag = 1, .eNB_index = instance};
2049
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt.module_id];
2050 2051 2052 2053 2054
  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;
  }
2055
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
2056

2057 2058 2059
  if (resp->drbs_to_be_setup_length > 0) {
    e1ap_bearer_setup_req_t req = {0};
    req.numPDUSessionsMod = UE->nb_of_pdusessions;
2060
    req.gNB_cu_cp_ue_id = UE->rrc_ue_id;
2061
    req.gNB_cu_up_ue_id = UE->rrc_ue_id;
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    for (int i = 0; i < req.numPDUSessionsMod; i++) {
      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;
      }
2073
    }
2074

2075 2076
    // send the F1 response message up to update F1-U tunnel info
    // it seems the rrc transaction id (xid) is not needed here
2077
    rrc->cucp_cuup.bearer_context_mod(&req, instance);
2078
  }
2079

2080 2081 2082 2083 2084 2085 2086 2087
  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
2088

2089 2090 2091
    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);
2092
    }
2093
    UE->masterCellGroup = cellGroupConfig;
2094

2095
    rrc_gNB_generate_dedicatedRRCReconfiguration(&ctxt, ue_context_p);
2096
  }
2097 2098
}

2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
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,
    };
    rrc->mac_rrc.ue_context_modification_refuse(&refuse);
    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,
      };
      rrc->mac_rrc.ue_context_modification_refuse(&refuse);
      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);
}

2162 2163 2164 2165
unsigned int mask_flip(unsigned int x) {
  return((((x>>8) + (x<<8))&0xffff)>>6);
}

2166
static unsigned int get_dl_bw_mask(const f1ap_served_cell_info_t *cell_info, const NR_UE_NR_Capability_t *cap)
2167
{
2168 2169
  int common_band = get_dl_band(cell_info);
  int common_scs  = get_ssb_scs(cell_info);
2170 2171 2172 2173 2174 2175
  for (int i=0;i<cap->rf_Parameters.supportedBandListNR.list.count;i++) {
     NR_BandNR_t *bandNRinfo = cap->rf_Parameters.supportedBandListNR.list.array[i];
     if (bandNRinfo->bandNR == common_band) {
       if (common_band < 257) { // FR1
          switch (common_scs) {
            case NR_SubcarrierSpacing_kHz15 :
2176
               if (bandNRinfo->channelBWs_DL &&
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
                   bandNRinfo->channelBWs_DL->choice.fr1 &&
                   bandNRinfo->channelBWs_DL->choice.fr1->scs_15kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_DL->choice.fr1->scs_15kHz->buf));
 	      break;
            case NR_SubcarrierSpacing_kHz30 :
               if (bandNRinfo->channelBWs_DL &&
                   bandNRinfo->channelBWs_DL->choice.fr1 &&
                   bandNRinfo->channelBWs_DL->choice.fr1->scs_30kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_DL->choice.fr1->scs_30kHz->buf));
              break;
            case NR_SubcarrierSpacing_kHz60 :
               if (bandNRinfo->channelBWs_DL &&
                   bandNRinfo->channelBWs_DL->choice.fr1 &&
                   bandNRinfo->channelBWs_DL->choice.fr1->scs_60kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_DL->choice.fr1->scs_60kHz->buf));
              break;
          }
       }
       else {
          switch (common_scs) {
            case NR_SubcarrierSpacing_kHz60 :
2198
               if (bandNRinfo->channelBWs_DL &&
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
                   bandNRinfo->channelBWs_DL->choice.fr2 &&
                   bandNRinfo->channelBWs_DL->choice.fr2->scs_60kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_DL->choice.fr2->scs_60kHz->buf));
              break;
            case NR_SubcarrierSpacing_kHz120 :
               if (bandNRinfo->channelBWs_DL &&
                   bandNRinfo->channelBWs_DL->choice.fr2 &&
                   bandNRinfo->channelBWs_DL->choice.fr2->scs_120kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_DL->choice.fr2->scs_120kHz->buf));
              break;
       }
     }
   }
  }
  return(0);
}

2216
static unsigned int get_ul_bw_mask(const f1ap_served_cell_info_t *cell_info, const NR_UE_NR_Capability_t *cap)
2217
{
2218 2219
  int common_band = get_ul_band(cell_info);
  int common_scs  = get_ssb_scs(cell_info);
2220 2221 2222 2223 2224 2225
  for (int i=0;i<cap->rf_Parameters.supportedBandListNR.list.count;i++) {
     NR_BandNR_t *bandNRinfo = cap->rf_Parameters.supportedBandListNR.list.array[i];
     if (bandNRinfo->bandNR == common_band) {
       if (common_band < 257) { // FR1
          switch (common_scs) {
            case NR_SubcarrierSpacing_kHz15 :
2226
               if (bandNRinfo->channelBWs_UL &&
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
                   bandNRinfo->channelBWs_UL->choice.fr1 &&
                   bandNRinfo->channelBWs_UL->choice.fr1->scs_15kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_UL->choice.fr1->scs_15kHz->buf));
 	      break;
            case NR_SubcarrierSpacing_kHz30 :
               if (bandNRinfo->channelBWs_UL &&
                   bandNRinfo->channelBWs_UL->choice.fr1 &&
                   bandNRinfo->channelBWs_UL->choice.fr1->scs_30kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_UL->choice.fr1->scs_30kHz->buf));
              break;
            case NR_SubcarrierSpacing_kHz60 :
               if (bandNRinfo->channelBWs_UL &&
                   bandNRinfo->channelBWs_UL->choice.fr1 &&
                   bandNRinfo->channelBWs_UL->choice.fr1->scs_60kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_UL->choice.fr1->scs_60kHz->buf));
              break;
          }
       }
       else {
          switch (common_scs) {
            case NR_SubcarrierSpacing_kHz60 :
2248
               if (bandNRinfo->channelBWs_UL &&
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
                   bandNRinfo->channelBWs_UL->choice.fr2 &&
                   bandNRinfo->channelBWs_UL->choice.fr2->scs_60kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_UL->choice.fr2->scs_60kHz->buf));
              break;
            case NR_SubcarrierSpacing_kHz120 :
               if (bandNRinfo->channelBWs_UL &&
                   bandNRinfo->channelBWs_UL->choice.fr2 &&
                   bandNRinfo->channelBWs_UL->choice.fr2->scs_120kHz)
                     return(mask_flip((unsigned int)*(uint16_t*)bandNRinfo->channelBWs_UL->choice.fr2->scs_120kHz->buf));
              break;
       }
     }
   }
  }
  return(0);
}

2266
static int get_ul_mimo_layersCB(const f1ap_served_cell_info_t *cell_info, const NR_UE_NR_Capability_t *cap)
2267
{
2268
  int common_scs  = get_ssb_scs(cell_info);
2269

2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
  // check featureSet
  NR_FeatureSets_t *fs=cap->featureSets;
  if (fs) {
    // go through UL feature sets and look for one with current SCS
    for (int i=0;i<fs->featureSetsUplinkPerCC->list.count;i++) {
       if (fs->featureSetsUplinkPerCC->list.array[i]->supportedSubcarrierSpacingUL == common_scs &&
           fs->featureSetsUplinkPerCC->list.array[i]->mimo_CB_PUSCH &&
           fs->featureSetsUplinkPerCC->list.array[i]->mimo_CB_PUSCH->maxNumberMIMO_LayersCB_PUSCH)
           return(1<<*fs->featureSetsUplinkPerCC->list.array[i]->mimo_CB_PUSCH->maxNumberMIMO_LayersCB_PUSCH);
    }
  }
  return(1);
}

2284
static int get_ul_mimo_layers(const f1ap_served_cell_info_t *cell_info, const NR_UE_NR_Capability_t *cap)
2285
{
2286
  int common_scs  = get_ssb_scs(cell_info);
2287

2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
  // check featureSet
  NR_FeatureSets_t *fs=cap->featureSets;
  if (fs) {
    // go through UL feature sets and look for one with current SCS
    for (int i=0;i<fs->featureSetsUplinkPerCC->list.count;i++) {
       if (fs->featureSetsUplinkPerCC->list.array[i]->supportedSubcarrierSpacingUL == common_scs &&
           fs->featureSetsUplinkPerCC->list.array[i]->maxNumberMIMO_LayersNonCB_PUSCH)
           return(1<<*fs->featureSetsUplinkPerCC->list.array[i]->maxNumberMIMO_LayersNonCB_PUSCH);
    }
  }
  return(1);
}

2301
static int get_dl_mimo_layers(const f1ap_served_cell_info_t *cell_info, const NR_UE_NR_Capability_t *cap)
2302
{
2303
  int common_scs  = get_ssb_scs(cell_info);
2304

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
  // check featureSet
  NR_FeatureSets_t *fs=cap->featureSets;
  if (fs) {
    // go through UL feature sets and look for one with current SCS
    for (int i=0;i<fs->featureSetsDownlinkPerCC->list.count;i++) {
       if (fs->featureSetsUplinkPerCC->list.array[i]->supportedSubcarrierSpacingUL == common_scs &&
           fs->featureSetsDownlinkPerCC->list.array[i]->maxNumberMIMO_LayersPDSCH)
           return(2<<*fs->featureSetsDownlinkPerCC->list.array[i]->maxNumberMIMO_LayersPDSCH);
    }
  }
  return(1);
}
2317

2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
int rrc_gNB_process_e1_setup_req(e1ap_setup_req_t *req, instance_t instance) {

  AssertFatal(req->supported_plmns <= PLMN_LIST_MAX_SIZE, "Supported PLMNs is more than PLMN_LIST_MAX_SIZE\n");
  gNB_RRC_INST *rrc = RC.nrrrc[0]; //TODO: remove hardcoding of RC index here
  MessageDef *msg_p = itti_alloc_new_message(TASK_RRC_GNB, instance, E1AP_SETUP_RESP);

  e1ap_setup_resp_t *resp = &E1AP_SETUP_RESP(msg_p);
  resp->transac_id = req->transac_id;

  for (int i=0; i < req->supported_plmns; i++) {
2328 2329
    if (rrc->configuration.mcc[i] != req->plmns[i].mcc ||
        rrc->configuration.mnc[i] != req->plmns[i].mnc) {
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
      LOG_E(NR_RRC, "PLMNs received from CUUP (mcc:%d, mnc:%d) did not match with PLMNs in RRC (mcc:%d, mnc:%d)\n",
            req->plmns[i].mcc, req->plmns[i].mnc, rrc->configuration.mcc[i], rrc->configuration.mnc[i]);
      return -1;
    }
  }

  itti_send_msg_to_task(TASK_CUCP_E1, instance, msg_p);

  return 0;
}

2341 2342 2343 2344 2345
void prepare_and_send_ue_context_modification_f1(rrc_gNB_ue_context_t *ue_context_p, e1ap_bearer_setup_resp_t *e1ap_resp)
{
  /* Generate a UE context modification request message towards the DU to
   * instruct the DU for SRB2 and DRB configuration and get the updates on
   * master cell group config from the DU*/
2346

2347
  gNB_RRC_INST *rrc = RC.nrrrc[0];
2348
  gNB_RRC_UE_t *UE = &ue_context_p->ue_context;
2349

2350 2351 2352 2353 2354
  /* Instruction towards the DU for DRB configuration and tunnel creation */
  int nb_drb = e1ap_resp->pduSession[0].numDRBSetup;
  f1ap_drb_to_be_setup_t drbs[nb_drb];
  for (int i = 0; i < nb_drb; i++) {
    drbs[i].drb_id = e1ap_resp->pduSession[0].DRBnGRanList[i].id;
2355
    drbs[i].rlc_mode = rrc->configuration.um_on_default_drb ? RLC_MODE_UM : RLC_MODE_AM;
2356 2357 2358 2359 2360 2361 2362
    drbs[i].up_ul_tnl[0].tl_address = e1ap_resp->pduSession[0].DRBnGRanList[i].UpParamList[0].tlAddress;
    drbs[i].up_ul_tnl[0].port = rrc->eth_params_s.my_portd;
    drbs[i].up_ul_tnl[0].teid = e1ap_resp->pduSession[0].DRBnGRanList[i].UpParamList[0].teId;
    drbs[i].up_ul_tnl_length = 1;
  }

  /* Instruction towards the DU for SRB2 configuration */
2363 2364 2365 2366 2367 2368 2369 2370
  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;
  }
2371

2372 2373 2374 2375 2376 2377 2378 2379
  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;
  }

2380
  f1_ue_data_t ue_data = cu_get_f1_ue_data(UE->rrc_ue_id);
2381
  f1ap_ue_context_modif_req_t ue_context_modif_req = {
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
      .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,
2394 2395
  };
  rrc->mac_rrc.ue_context_modification_request(&ue_context_modif_req);
2396 2397 2398 2399 2400
}

void rrc_gNB_process_e1_bearer_context_setup_resp(e1ap_bearer_setup_resp_t *resp, instance_t instance) {
  // Find the UE context from UE ID and send ITTI message to F1AP to send UE context modification message to DU

2401
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context(RC.nrrrc[instance], resp->gNB_cu_cp_ue_id);
2402
  AssertFatal(ue_context_p != NULL, "did not find UE with CU UE ID %d\n", resp->gNB_cu_cp_ue_id);
2403
  protocol_ctxt_t ctxt = {0};
2404
  PROTOCOL_CTXT_SET_BY_MODULE_ID(&ctxt, 0, GNB_FLAG_YES, resp->gNB_cu_cp_ue_id, 0, 0, 0);
2405

2406 2407 2408 2409 2410 2411 2412
  // 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);

2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
  gtpv1u_gnb_create_tunnel_resp_t create_tunnel_resp={0};
  create_tunnel_resp.num_tunnels = resp->numPDUSessions;
  for (int i=0; i < resp->numPDUSessions; i++) {
    create_tunnel_resp.pdusession_id[i]  = resp->pduSession[i].id;
    create_tunnel_resp.gnb_NGu_teid[i] = resp->pduSession[i].teId;
    memcpy(create_tunnel_resp.gnb_addr.buffer,
           &resp->pduSession[i].tlAddress,
           sizeof(in_addr_t));
    create_tunnel_resp.gnb_addr.length = sizeof(in_addr_t); // IPv4 byte length
  }

laurent's avatar
laurent committed
2424
  nr_rrc_gNB_process_GTPV1U_CREATE_TUNNEL_RESP(&ctxt, &create_tunnel_resp, 0);
2425 2426 2427 2428 2429

  // TODO: SV: combine e1ap_bearer_setup_req_t and e1ap_bearer_setup_resp_t and minimize assignments
  prepare_and_send_ue_context_modification_f1(ue_context_p, resp);
}

2430
static void rrc_CU_process_f1_lost_connection(gNB_RRC_INST *rrc, f1ap_lost_connection_t *lc, sctp_assoc_t assoc_id)
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
{
  AssertFatal(rrc->du != NULL, "no DU connected, cannot received F1 lost connection\n");
  AssertFatal(rrc->du->assoc_id == assoc_id,
              "previously connected DU (%d) does not match DU for which connection has been lost (%d)\n",
              rrc->du->assoc_id,
              assoc_id);
  (void) lc; // unused for the moment
  ASN_STRUCT_FREE(asn_DEF_NR_MIB, rrc->du->mib);
  ASN_STRUCT_FREE(asn_DEF_NR_SIB1, rrc->du->sib1);
  free(rrc->du);
  rrc->du = NULL;
  LOG_I(RRC, "dropping DU with assoc_id %d (UE connections remain, if any)\n", assoc_id);
}

2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
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");
  }
}

2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
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";
}

2496 2497 2498 2499 2500 2501 2502 2503 2504
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;
  }

2505
  int i = 0;
2506 2507
  rrc_gNB_ue_context_t *ue_context_p = NULL;
  /* cast is necessary to eliminate warning "discards ‘const’ qualifier" */
2508 2509
  RB_FOREACH(ue_context_p, rrc_nr_ue_tree_s, &((gNB_RRC_INST *)rrc)->rrc_ue_head)
  {
2510
    const gNB_RRC_UE_t *ue_ctxt = &ue_context_p->ue_context;
2511
    f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_ctxt->rrc_ue_id);
2512 2513 2514 2515
    /* currently, we support only one DU. If we support multiple, need to
     * search for the DU corresponding to this UE here */
    const nr_rrc_du_container_t *du = rrc->du;
    DevAssert(du != NULL);
2516

2517 2518 2519 2520 2521 2522 2523
    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);
2524
    if (ue_ctxt->Initialue_identity_5g_s_TMSI.presence)
2525
      fprintf(f, " S-TMSI %x", ue_ctxt->Initialue_identity_5g_s_TMSI.fiveg_tmsi);
2526
    fprintf(f, ":\n");
2527

2528 2529 2530 2531 2532 2533 2534 2535
    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));
    }
2536 2537

    if (ue_ctxt->UE_Capability_nr) {
2538 2539
      AssertFatal(du->setup_req->num_cells_available == 1, "only one cell supported at the moment\n");
      const f1ap_served_cell_info_t *cell_info = &du->setup_req->cell[0].info;
2540 2541
      fprintf(f,
              "    UE cap: BW DL %x. BW UL %x, DL MIMO Layers %d UL MIMO Layers (CB) %d UL MIMO Layers (nonCB) %d\n",
2542 2543 2544 2545 2546
              get_dl_bw_mask(cell_info, ue_ctxt->UE_Capability_nr),
              get_ul_bw_mask(cell_info, ue_ctxt->UE_Capability_nr),
              get_dl_mimo_layers(cell_info, ue_ctxt->UE_Capability_nr),
              get_ul_mimo_layersCB(cell_info, ue_ctxt->UE_Capability_nr),
              get_ul_mimo_layers(cell_info, ue_ctxt->UE_Capability_nr));
2547
    }
2548 2549 2550

    if (ue_ctxt->measResults)
      print_rrc_meas(f, ue_ctxt->measResults);
2551
    ++i;
2552 2553 2554 2555 2556
  }

  fclose(f);
}

WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2557 2558
///---------------------------------------------------------------------------------------------------------------///
///---------------------------------------------------------------------------------------------------------------///
2559
void *rrc_gnb_task(void *args_p) {
laurent's avatar
tmp  
laurent committed
2560
  MessageDef *msg_p;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2561 2562
  instance_t                         instance;
  int                                result;
2563
  protocol_ctxt_t ctxt = {.module_id = 0, .enb_flag = 1, .instance = 0, .rntiMaybeUEid = 0, .frame = -1, .subframe = -1, .eNB_index = 0, .brOption = false};
2564 2565

  long stats_timer_id = 1;
2566 2567 2568 2569 2570
  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
2571 2572
  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
2573 2574

  while (1) {
2575
    // Wait for a message
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2576
    itti_receive_msg(TASK_RRC_GNB, &msg_p);
laurent's avatar
tmp  
laurent committed
2577
    const char *msg_name_p = ITTI_MSG_NAME(msg_p);
2578
    instance = ITTI_MSG_DESTINATION_INSTANCE(msg_p);
laurent's avatar
tmp  
laurent committed
2579
    LOG_D(NR_RRC, "Received Msg %s\n", msg_name_p);
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2580
    switch (ITTI_MSG_ID(msg_p)) {
2581
      case TERMINATE_MESSAGE:
Xue Song's avatar
Xue Song committed
2582
        LOG_W(NR_RRC, " *** Exiting NR_RRC thread\n");
2583 2584
        itti_exit_task();
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2585

2586
      case MESSAGE_TEST:
2587
        LOG_I(NR_RRC, "[gNB %ld] Received %s\n", instance, msg_name_p);
2588
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2589

2590 2591 2592 2593 2594 2595
      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;

2596 2597 2598 2599 2600
      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");
        rrc_gNB_process_initial_ul_rrc_message(&F1AP_INITIAL_UL_RRC_MESSAGE(msg_p));
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2601 2602

      /* Messages from PDCP */
2603
      case F1AP_UL_RRC_MESSAGE:
2604 2605 2606
        PROTOCOL_CTXT_SET_BY_INSTANCE(&ctxt,
                                      instance,
                                      GNB_FLAG_YES,
2607
                                      F1AP_UL_RRC_MESSAGE(msg_p).gNB_CU_ue_id,
2608 2609
                                      0,
                                      0);
2610 2611 2612 2613 2614 2615 2616
        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
2617
        rrc_gNB_decode_dcch(&ctxt,
2618 2619 2620 2621
                            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
2622
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2623

Xue Song's avatar
Xue Song committed
2624
      case NGAP_DOWNLINK_NAS:
laurent's avatar
tmp  
laurent committed
2625
        rrc_gNB_process_NGAP_DOWNLINK_NAS(msg_p, instance, &rrc_gNB_mui);
Xue Song's avatar
Xue Song committed
2626 2627
        break;

2628
      case NGAP_PDUSESSION_SETUP_REQ:
laurent's avatar
tmp  
laurent committed
2629
        rrc_gNB_process_NGAP_PDUSESSION_SETUP_REQ(msg_p, instance);
2630 2631
        break;

2632
      case NGAP_PDUSESSION_MODIFY_REQ:
laurent's avatar
tmp  
laurent committed
2633
        rrc_gNB_process_NGAP_PDUSESSION_MODIFY_REQ(msg_p, instance);
2634 2635 2636
        break;

      case NGAP_PDUSESSION_RELEASE_COMMAND:
laurent's avatar
tmp  
laurent committed
2637
        rrc_gNB_process_NGAP_PDUSESSION_RELEASE_COMMAND(msg_p, instance);
2638 2639
        break;

Xue Song's avatar
Xue Song committed
2640 2641
      /* Messages from F1AP task */
      case F1AP_SETUP_REQ:
2642
        AssertFatal(!NODE_IS_DU(RC.nrrrc[instance]->node_type), "should not receive F1AP_SETUP_REQUEST in DU!\n");
2643
        rrc_gNB_process_f1_setup_req(&F1AP_SETUP_REQ(msg_p), msg_p->ittiMsgHeader.originInstance);
Xue Song's avatar
Xue Song committed
2644
        break;
2645

2646
      case F1AP_UE_CONTEXT_SETUP_RESP:
laurent's avatar
tmp  
laurent committed
2647
        rrc_CU_process_ue_context_setup_response(msg_p, instance);
2648
        break;
2649

2650
      case F1AP_UE_CONTEXT_MODIFICATION_RESP:
laurent's avatar
tmp  
laurent committed
2651
        rrc_CU_process_ue_context_modification_response(msg_p, instance);
2652 2653
        break;

2654 2655 2656 2657
      case F1AP_UE_CONTEXT_MODIFICATION_REQUIRED:
        rrc_CU_process_ue_modification_required(msg_p);
        break;

2658
      case F1AP_UE_CONTEXT_RELEASE_REQ:
2659
        rrc_CU_process_ue_context_release_request(msg_p);
2660 2661 2662 2663
        break;

      case F1AP_UE_CONTEXT_RELEASE_COMPLETE:
        rrc_CU_process_ue_context_release_complete(msg_p);
2664
        break;
Xue Song's avatar
Xue Song committed
2665

2666 2667 2668 2669
      case F1AP_LOST_CONNECTION:
        rrc_CU_process_f1_lost_connection(RC.nrrrc[0], &F1AP_LOST_CONNECTION(msg_p), msg_p->ittiMsgHeader.originInstance);
        break;

2670
      /* Messages from X2AP */
2671
      case X2AP_ENDC_SGNB_ADDITION_REQ:
2672
        LOG_I(NR_RRC, "Received ENDC sgNB addition request from X2AP \n");
2673
        rrc_gNB_process_AdditionRequestInformation(instance, &X2AP_ENDC_SGNB_ADDITION_REQ(msg_p));
2674
        break;
2675

2676
      case X2AP_ENDC_SGNB_RECONF_COMPLETE:
Melissa Elkadi's avatar
Melissa Elkadi committed
2677
        LOG_A(NR_RRC, "Handling of reconfiguration complete message at RRC gNB is pending \n");
2678
        break;
Xue Song's avatar
Xue Song committed
2679

2680
      case NGAP_INITIAL_CONTEXT_SETUP_REQ:
laurent's avatar
tmp  
laurent committed
2681
        rrc_gNB_process_NGAP_INITIAL_CONTEXT_SETUP_REQ(msg_p, instance);
yaojie's avatar
yaojie committed
2682
        break;
2683

Cedric Roux's avatar
Cedric Roux committed
2684 2685
      case X2AP_ENDC_SGNB_RELEASE_REQUEST:
        LOG_I(NR_RRC, "Received ENDC sgNB release request from X2AP \n");
2686
        rrc_gNB_process_release_request(instance, &X2AP_ENDC_SGNB_RELEASE_REQUEST(msg_p));
Cedric Roux's avatar
Cedric Roux committed
2687 2688 2689
        break;

      case X2AP_ENDC_DC_OVERALL_TIMEOUT:
2690
        rrc_gNB_process_dc_overall_timeout(instance, &X2AP_ENDC_DC_OVERALL_TIMEOUT(msg_p));
Cedric Roux's avatar
Cedric Roux committed
2691 2692
        break;

2693
      case NGAP_UE_CONTEXT_RELEASE_REQ:
laurent's avatar
tmp  
laurent committed
2694
        rrc_gNB_process_NGAP_UE_CONTEXT_RELEASE_REQ(msg_p, instance);
2695 2696 2697
        break;

      case NGAP_UE_CONTEXT_RELEASE_COMMAND:
laurent's avatar
tmp  
laurent committed
2698
        rrc_gNB_process_NGAP_UE_CONTEXT_RELEASE_COMMAND(msg_p, instance);
2699 2700
        break;

2701 2702 2703 2704 2705 2706 2707
      case E1AP_SETUP_REQ:
        rrc_gNB_process_e1_setup_req(&E1AP_SETUP_REQ(msg_p), instance);
        break;

      case E1AP_BEARER_CONTEXT_SETUP_RESP:
        rrc_gNB_process_e1_bearer_context_setup_resp(&E1AP_BEARER_CONTEXT_SETUP_RESP(msg_p), instance);

2708
      case NGAP_PAGING_IND:
laurent's avatar
tmp  
laurent committed
2709
        rrc_gNB_process_PAGING_IND(msg_p, instance);
2710 2711
        break;

2712
      default:
2713
        LOG_E(NR_RRC, "[gNB %ld] Received unexpected message %s\n", instance, msg_name_p);
2714
        break;
WEI-TAI CHEN's avatar
WEI-TAI CHEN committed
2715 2716 2717 2718 2719 2720 2721
    }

    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
2722

2723 2724 2725 2726
typedef struct deliver_ue_ctxt_setup_data_t {
  gNB_RRC_INST *rrc;
  f1ap_ue_context_setup_t *setup_req;
} deliver_ue_ctxt_setup_data_t;
2727 2728 2729
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);
2730 2731 2732 2733
  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;
  data->rrc->mac_rrc.ue_context_setup_request(data->setup_req);
2734 2735
}

heshanyun's avatar
heshanyun committed
2736 2737 2738 2739
//-----------------------------------------------------------------------------
void
rrc_gNB_generate_SecurityModeCommand(
  const protocol_ctxt_t *const ctxt_pP,
Xue Song's avatar
Xue Song committed
2740
  rrc_gNB_ue_context_t  *const ue_context_pP
heshanyun's avatar
heshanyun committed
2741 2742 2743 2744 2745
)
//-----------------------------------------------------------------------------
{
  uint8_t                             buffer[100];
  uint8_t                             size;
2746
  gNB_RRC_UE_t *ue_p = &ue_context_pP->ue_context;
2747

2748
  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));
2749
  NR_IntegrityProtAlgorithm_t integrity_algorithm = (NR_IntegrityProtAlgorithm_t)ue_p->integrity_algorithm;
2750
  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
2751
  LOG_DUMPMSG(NR_RRC,DEBUG_RRC,(char *)buffer,size,"[MSG] RRC Security Mode Command\n");
2752
  LOG_I(NR_RRC, "UE %04x Logical Channel DL-DCCH, Generate SecurityModeCommand (bytes %d)\n", ue_p->rnti, size);
2753

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

2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
  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;
  }

  const nr_rrc_du_container_t *du = rrc->du;
  DevAssert(du != NULL);

2768
  /* the callback will fill the UE context setup request and forward it */
2769
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue_p->rrc_ue_id);
2770
  f1ap_ue_context_setup_t ue_context_setup_req = {
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
      .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,
2781 2782 2783
  };
  deliver_ue_ctxt_setup_data_t data = {.rrc = rrc, .setup_req = &ue_context_setup_req};
  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
2784 2785
}

zhanghuiqin's avatar
zhanghuiqin committed
2786 2787 2788 2789 2790 2791 2792 2793 2794
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;
2795

2796
  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
2797
  size = do_NR_SA_UECapabilityEnquiry(
zhanghuiqin's avatar
zhanghuiqin committed
2798 2799 2800
           ctxt_pP,
           buffer,
           rrc_gNB_get_next_transaction_identifier(ctxt_pP->module_id));
2801 2802 2803
  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
2804
        size);
2805

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

2809 2810
  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
2811
}
heshanyun's avatar
heshanyun committed
2812

2813 2814 2815 2816
typedef struct deliver_ue_ctxt_release_data_t {
  gNB_RRC_INST *rrc;
  f1ap_ue_context_release_cmd_t *release_cmd;
} deliver_ue_ctxt_release_data_t;
2817 2818 2819
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);
2820 2821 2822 2823
  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;
  data->rrc->mac_rrc.ue_context_release_command(data->release_cmd);
2824 2825
}

heshanyun's avatar
heshanyun committed
2826 2827 2828 2829 2830 2831
//-----------------------------------------------------------------------------
/*
* Generate the RRC Connection Release to UE.
* If received, UE should switch to RRC_IDLE mode.
*/
void
Xue Song's avatar
Xue Song committed
2832
rrc_gNB_generate_RRCRelease(
heshanyun's avatar
heshanyun committed
2833
  const protocol_ctxt_t *const ctxt_pP,
Xue Song's avatar
Xue Song committed
2834
  rrc_gNB_ue_context_t  *const ue_context_pP
heshanyun's avatar
heshanyun committed
2835 2836 2837
)
//-----------------------------------------------------------------------------
{
2838 2839
  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));
2840

heshanyun's avatar
heshanyun committed
2841
  LOG_I(NR_RRC,
Xue Song's avatar
Xue Song committed
2842 2843
        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
2844 2845
        size);

2846
  gNB_RRC_INST *rrc = RC.nrrrc[ctxt_pP->module_id];
2847
  const gNB_RRC_UE_t *UE = &ue_context_pP->ue_context;
2848
  f1_ue_data_t ue_data = cu_get_f1_ue_data(UE->rrc_ue_id);
2849
  f1ap_ue_context_release_cmd_t ue_context_release_cmd = {
2850
    .gNB_CU_ue_id = UE->rrc_ue_id,
2851 2852 2853 2854 2855 2856 2857
    .gNB_DU_ue_id = ue_data.secondary_ue,
    .cause = F1AP_CAUSE_RADIO_NETWORK,
    .cause_value = 10, // 10 = F1AP_CauseRadioNetwork_normal_release
    .srb_id = DCCH,
  };
  deliver_ue_ctxt_release_data_t data = {.rrc = rrc, .release_cmd = &ue_context_release_cmd};
  nr_pdcp_data_req_srb(ctxt_pP->rntiMaybeUEid, DCCH, rrc_gNB_mui++, size, buffer, rrc_deliver_ue_ctxt_release_cmd, &data);
2858

2859
  /* UE will be freed after UE context release complete */
heshanyun's avatar
heshanyun committed
2860
}
2861

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
void rrc_gNB_trigger_new_bearer(int rnti)
{
  /* get RRC and UE */
  gNB_RRC_INST *rrc = RC.nrrrc[0];
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context_by_rnti(rrc, rnti);
  if (ue_context_p == NULL) {
    LOG_E(RRC, "unknown UE RNTI %04x\n", rnti);
    return;
  }
  gNB_RRC_UE_t *ue = &ue_context_p->ue_context;

  /* get the existing PDU sessoin */
  if (ue->nb_of_pdusessions < 1) {
    LOG_E(RRC, "no PDU session set up yet, cannot create additional bearer\n");
    return;
  }

  if (ue->established_drbs[0].status != DRB_INACTIVE
      && ue->established_drbs[1].status != DRB_INACTIVE) {
    LOG_E(RRC, "already have two established bearers, aborting\n");
    return;
  }

  e1ap_bearer_setup_req_t bearer_req = {0};
  bearer_req.gNB_cu_cp_ue_id = ue->rrc_ue_id;
  bearer_req.cipheringAlgorithm = ue->ciphering_algorithm;
  memcpy(bearer_req.encryptionKey, ue->kgnb, sizeof(ue->kgnb));
  bearer_req.integrityProtectionAlgorithm = ue->integrity_algorithm;
  memcpy(bearer_req.integrityProtectionKey, ue->kgnb, sizeof(ue->kgnb));
  bearer_req.ueDlAggMaxBitRate = 10000; /* probably does not matter */

  pdu_session_to_setup_t *pdu = &bearer_req.pduSession[0];
  //bearer_req.numPDUSessions++;
  bearer_req.numPDUSessions = 1;
  //pdu->sessionId = session->pdusession_id;
  //pdu->sst = msg->allowed_nssai[i].sST;
  //pdu->integrityProtectionIndication = rrc->security.do_drb_integrity ? E1AP_IntegrityProtectionIndication_required : E1AP_IntegrityProtectionIndication_not_needed;

  //pdu->confidentialityProtectionIndication = rrc->security.do_drb_ciphering ? E1AP_ConfidentialityProtectionIndication_required : E1AP_ConfidentialityProtectionIndication_not_needed;
  //pdu->teId = session->gtp_teid;
  pdu->numDRB2Setup = 1; // One DRB per PDU Session. TODO: Remove hardcoding
  DRB_nGRAN_to_setup_t *drb = &pdu->DRBnGRanList[0];
  int drb_id = 2;
  drb->id = drb_id;

  drb->defaultDRB = E1AP_DefaultDRB_false;
  drb->sDAP_Header_UL = !(rrc->configuration.enable_sdap);
  drb->sDAP_Header_DL = !(rrc->configuration.enable_sdap);

  drb->pDCP_SN_Size_UL = E1AP_PDCP_SN_Size_s_18;
  drb->pDCP_SN_Size_DL = E1AP_PDCP_SN_Size_s_18;

  drb->discardTimer = E1AP_DiscardTimer_infinity;
  drb->reorderingTimer = E1AP_T_Reordering_ms0;

  drb->rLC_Mode = E1AP_RLC_Mode_rlc_am;

  drb->numCellGroups = 1; // assume one cell group associated with a DRB

  for (int k=0; k < drb->numCellGroups; k++) {
    cell_group_t *cellGroup = drb->cellGroupList + k;
    cellGroup->id = 0; // MCG
  }

  int xid = rrc_gNB_get_next_transaction_identifier(0);
  /* generate a new bearer, it will be put into internal RRC state and picked
   * up later */
  generateDRB(ue,
              drb_id,
              &ue->pduSession[0],
              rrc->configuration.enable_sdap,
              rrc->security.do_drb_integrity,
              rrc->security.do_drb_ciphering);

  /* associate the new bearer to it */
  ue->xids[xid] = RRC_PDUSESSION_MODIFY;
  ue->pduSession[0].xid = xid; // hack: fake xid for ongoing PDU session
  LOG_W(RRC, "trigger new bearer %ld for UE %04x xid %d\n", drb->id, ue->rnti, xid);
  rrc->cucp_cuup.bearer_context_setup(&bearer_req, 0);
}

void rrc_gNB_trigger_release_bearer(int rnti)
{
  /* get RRC and UE */
  gNB_RRC_INST *rrc = RC.nrrrc[0];
  rrc_gNB_ue_context_t *ue_context_p = rrc_gNB_get_ue_context_by_rnti(rrc, rnti);
  if (ue_context_p == NULL) {
    LOG_E(RRC, "unknown UE RNTI %04x\n", rnti);
    return;
  }
  gNB_RRC_UE_t *ue = &ue_context_p->ue_context;

  if (ue->established_drbs[1].status == DRB_INACTIVE) {
    LOG_E(RRC, "no second bearer, aborting\n");
    return;
  }

  // don't use E1: bearer release is not implemented, call directly
  // into PDCP/SDAP and then send corresponding message via F1

  int drb_id = 2;
  ue->established_drbs[1].status = DRB_INACTIVE;
  ue->DRB_ReleaseList = calloc(1, sizeof(*ue->DRB_ReleaseList));
  AssertFatal(ue->DRB_ReleaseList != NULL, "out of memory\n");
  NR_DRB_Identity_t *asn1_drb = malloc(sizeof(*asn1_drb));
  AssertFatal(asn1_drb != NULL, "out of memory\n");
  int idx = 0;
  NR_DRB_ToAddModList_t *drb_list = createDRBlist(ue, false);
  while (idx < drb_list->list.count) {
    const NR_DRB_ToAddMod_t *drbc = drb_list->list.array[idx];
    if (drbc->drb_Identity == drb_id)
      break;
    ++idx;
  }
  if (idx < drb_list->list.count) {
    nr_pdcp_release_drb(rnti, drb_id);
    asn_sequence_del(&drb_list->list, idx, 1);
  }
  *asn1_drb = drb_id;
  asn1cSeqAdd(&ue->DRB_ReleaseList->list, asn1_drb);

  f1ap_drb_to_be_released_t drbs_to_be_released[1] = {{.rb_id = drb_id}};
  f1_ue_data_t ue_data = cu_get_f1_ue_data(ue->rrc_ue_id);
  f1ap_ue_context_modif_req_t ue_context_modif_req = {
    .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 = 0,
    .srbs_to_be_setup = NULL,
    .drbs_to_be_setup_length = 0,
    .drbs_to_be_setup = NULL,
    .drbs_to_be_released_length = 1,
    .drbs_to_be_released = drbs_to_be_released,
  };
  rrc->mac_rrc.ue_context_modification_request(&ue_context_modif_req);
}

3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
int rrc_gNB_generate_pcch_msg(uint32_t tmsi, uint8_t paging_drx, instance_t instance, uint8_t CC_id){
  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];
Robert Schmidt's avatar
Robert Schmidt committed
3014 3015 3016
  const nr_rrc_du_container_t *du = RC.nrrrc[0]->du;
  DevAssert(du != NULL);
  struct NR_SIB1 *sib1 = du->sib1;
3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126

  /* 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

  return 0;
}