config_ue.c 111 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * 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
 */

22
/* \file config_ue.c
23
 * \brief UE configuration performed by RRC or as a consequence of RRC procedures
24 25
 * \author R. Knopp, K.H. HSU
 * \date 2018
26
 * \version 0.1
27 28 29 30
 * \company Eurecom / NTUST
 * \email: knopp@eurecom.fr, kai-hsiang.hsu@eurecom.fr
 * \note
 * \warning
31
 */
32

33 34
#define _GNU_SOURCE

35
//#include "mac_defs.h"
36
#include <NR_MAC_gNB/mac_proto.h>
37
#include "NR_MAC_UE/mac_proto.h"
38
#include "NR_MAC-CellGroupConfig.h"
39
#include "LAYER2/NR_MAC_COMMON/nr_mac_common.h"
40 41
#include "common/utils/nr/nr_common.h"
#include "executables/softmodem-common.h"
42
#include "SCHED_NR/phy_frame_config_nr.h"
43
#include "oai_asn1.h"
44

francescomani's avatar
francescomani committed
45
void set_tdd_config_nr_ue(fapi_nr_tdd_table_t *tdd_table,
46
                          int mu,
francescomani's avatar
francescomani committed
47 48 49 50 51 52 53 54 55 56 57
                          NR_TDD_UL_DL_Pattern_t *pattern)
{
  const int nrofDownlinkSlots = pattern->nrofDownlinkSlots;
  const int nrofDownlinkSymbols = pattern->nrofDownlinkSymbols;
  const int nrofUplinkSlots = pattern->nrofUplinkSlots;
  const int nrofUplinkSymbols = pattern->nrofUplinkSymbols;
  const int nb_periods_per_frame = get_nb_periods_per_frame(pattern->dl_UL_TransmissionPeriodicity);
  const int nb_slots_per_period = ((1 << mu) * NR_NUMBER_OF_SUBFRAMES_PER_FRAME) / nb_periods_per_frame;
  tdd_table->tdd_period_in_slots = nb_slots_per_period;

  if ((nrofDownlinkSymbols + nrofUplinkSymbols) == 0)
58 59 60 61 62 63 64 65 66
    AssertFatal(nb_slots_per_period == (nrofDownlinkSlots + nrofUplinkSlots),
                "set_tdd_configuration_nr: given period is inconsistent with current tdd configuration, nrofDownlinkSlots %d, nrofUplinkSlots %d, nb_slots_per_period %d \n",
                nrofDownlinkSlots,nrofUplinkSlots,nb_slots_per_period);
  else {
    AssertFatal(nrofDownlinkSymbols + nrofUplinkSymbols < 14,"illegal symbol configuration DL %d, UL %d\n",nrofDownlinkSymbols,nrofUplinkSymbols);
    AssertFatal(nb_slots_per_period == (nrofDownlinkSlots + nrofUplinkSlots + 1),
                "set_tdd_configuration_nr: given period is inconsistent with current tdd configuration, nrofDownlinkSlots %d, nrofUplinkSlots %d, nrofMixed slots 1, nb_slots_per_period %d \n",
                nrofDownlinkSlots,nrofUplinkSlots,nb_slots_per_period);
  }
Raymond Knopp's avatar
Raymond Knopp committed
67

francescomani's avatar
francescomani committed
68
  tdd_table->max_tdd_periodicity_list = (fapi_nr_max_tdd_periodicity_t *) malloc(nb_slots_per_period * sizeof(fapi_nr_max_tdd_periodicity_t));
Raymond Knopp's avatar
Raymond Knopp committed
69

francescomani's avatar
francescomani committed
70 71 72
  for(int memory_alloc = 0 ; memory_alloc < nb_slots_per_period; memory_alloc++)
    tdd_table->max_tdd_periodicity_list[memory_alloc].max_num_of_symbol_per_slot_list =
      (fapi_nr_max_num_of_symbol_per_slot_t *) malloc(NR_NUMBER_OF_SYMBOLS_PER_SLOT*sizeof(fapi_nr_max_num_of_symbol_per_slot_t));
Raymond Knopp's avatar
Raymond Knopp committed
73

francescomani's avatar
francescomani committed
74 75
  int slot_number = 0;
  while(slot_number != nb_slots_per_period) {
76
    if(nrofDownlinkSlots != 0) {
francescomani's avatar
francescomani committed
77 78 79
      for (int number_of_symbol = 0; number_of_symbol < nrofDownlinkSlots * NR_NUMBER_OF_SYMBOLS_PER_SLOT; number_of_symbol++) {
        tdd_table->max_tdd_periodicity_list[slot_number].max_num_of_symbol_per_slot_list[number_of_symbol % NR_NUMBER_OF_SYMBOLS_PER_SLOT].slot_config = 0;
        if((number_of_symbol + 1) % NR_NUMBER_OF_SYMBOLS_PER_SLOT == 0)
80 81 82
          slot_number++;
      }
    }
Raymond Knopp's avatar
Raymond Knopp committed
83

84
    if (nrofDownlinkSymbols != 0 || nrofUplinkSymbols != 0) {
francescomani's avatar
francescomani committed
85 86
      for(int number_of_symbol = 0; number_of_symbol < nrofDownlinkSymbols; number_of_symbol++) {
        tdd_table->max_tdd_periodicity_list[slot_number].max_num_of_symbol_per_slot_list[number_of_symbol].slot_config = 0;
87
      }
francescomani's avatar
francescomani committed
88 89
      for(int number_of_symbol = nrofDownlinkSymbols; number_of_symbol < NR_NUMBER_OF_SYMBOLS_PER_SLOT - nrofUplinkSymbols; number_of_symbol++) {
        tdd_table->max_tdd_periodicity_list[slot_number].max_num_of_symbol_per_slot_list[number_of_symbol].slot_config = 2;
90
      }
francescomani's avatar
francescomani committed
91 92
      for(int number_of_symbol = NR_NUMBER_OF_SYMBOLS_PER_SLOT - nrofUplinkSymbols; number_of_symbol < NR_NUMBER_OF_SYMBOLS_PER_SLOT; number_of_symbol++) {
        tdd_table->max_tdd_periodicity_list[slot_number].max_num_of_symbol_per_slot_list[number_of_symbol].slot_config = 1;
93 94 95
      }
      slot_number++;
    }
Raymond Knopp's avatar
Raymond Knopp committed
96

97
    if(nrofUplinkSlots != 0) {
francescomani's avatar
francescomani committed
98 99 100
      for (int number_of_symbol = 0; number_of_symbol < nrofUplinkSlots * NR_NUMBER_OF_SYMBOLS_PER_SLOT; number_of_symbol++) {
        tdd_table->max_tdd_periodicity_list[slot_number].max_num_of_symbol_per_slot_list[number_of_symbol%NR_NUMBER_OF_SYMBOLS_PER_SLOT].slot_config = 1;
        if((number_of_symbol + 1) % NR_NUMBER_OF_SYMBOLS_PER_SLOT == 0)
101 102 103 104 105
          slot_number++;
      }
    }
  }
}
Raymond Knopp's avatar
Raymond Knopp committed
106

107 108 109
static void config_common_ue_sa(NR_UE_MAC_INST_t *mac,
                                NR_ServingCellConfigCommonSIB_t *scc,
                                int cc_idP)
110
{
111
  fapi_nr_config_request_t *cfg = &mac->phy_config.config_req;
112
  mac->phy_config.Mod_id = mac->ue_id;
113 114 115 116 117
  mac->phy_config.CC_id = cc_idP;

  LOG_D(MAC, "Entering SA UE Config Common\n");

  // carrier config
118
  NR_FrequencyInfoDL_SIB_t *frequencyInfoDL = &scc->downlinkConfigCommon.frequencyInfoDL;
119
  AssertFatal(frequencyInfoDL->frequencyBandList.list.array[0]->freqBandIndicatorNR, "Field mandatory present for DL in SIB1\n");
120
  mac->nr_band = *frequencyInfoDL->frequencyBandList.list.array[0]->freqBandIndicatorNR;
121 122 123 124 125

  int bw_index = get_supported_band_index(frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing,
                                          mac->frequency_range,
                                          frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth);
  cfg->carrier_config.dl_bandwidth = get_supported_bw_mhz(mac->frequency_range, bw_index);
126 127 128

  uint64_t dl_bw_khz = (12 * frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth) *
                       (15 << frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing);
129 130
  cfg->carrier_config.dl_frequency = (downlink_frequency[cc_idP][0]/1000) - (dl_bw_khz>>1);

131
  for (int i = 0; i < 5; i++) {
132 133 134
    if (i == frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing) {
      cfg->carrier_config.dl_grid_size[i] = frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth;
      cfg->carrier_config.dl_k0[i] = frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->offsetToCarrier;
135 136 137 138 139 140 141
    }
    else {
      cfg->carrier_config.dl_grid_size[i] = 0;
      cfg->carrier_config.dl_k0[i] = 0;
    }
  }

142
  NR_FrequencyInfoUL_SIB_t *frequencyInfoUL = &scc->uplinkConfigCommon->frequencyInfoUL;
143
  mac->p_Max = frequencyInfoUL->p_Max ? *frequencyInfoUL->p_Max : INT_MIN;
144 145 146 147 148

  bw_index = get_supported_band_index(frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing,
                                      mac->frequency_range,
                                      frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth);
  cfg->carrier_config.uplink_bandwidth = get_supported_bw_mhz(mac->frequency_range, bw_index);
149

150
  if (frequencyInfoUL->absoluteFrequencyPointA == NULL)
151 152 153 154 155
    cfg->carrier_config.uplink_frequency = cfg->carrier_config.dl_frequency;
  else
    // TODO check if corresponds to what reported in SIB1
    cfg->carrier_config.uplink_frequency = (downlink_frequency[cc_idP][0]/1000) + uplink_frequency_offset[cc_idP][0];

156 157 158 159
  for (int i = 0; i < 5; i++) {
    if (i == frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing) {
      cfg->carrier_config.ul_grid_size[i] = frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth;
      cfg->carrier_config.ul_k0[i] = frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->offsetToCarrier;
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    }
    else {
      cfg->carrier_config.ul_grid_size[i] = 0;
      cfg->carrier_config.ul_k0[i] = 0;
    }
  }

  mac->frame_type = get_frame_type(mac->nr_band, get_softmodem_params()->numerology);
  // cell config
  cfg->cell_config.phy_cell_id = mac->physCellId;
  cfg->cell_config.frame_duplex_type = mac->frame_type;

  // SSB config
  cfg->ssb_config.ss_pbch_power = scc->ss_PBCH_BlockPower;
  cfg->ssb_config.scs_common = get_softmodem_params()->numerology;

  // SSB Table config
177
  cfg->ssb_table.ssb_offset_point_a = frequencyInfoDL->offsetToPointA;
178 179 180 181
  cfg->ssb_table.ssb_period = scc->ssb_PeriodicityServingCell;
  cfg->ssb_table.ssb_subcarrier_offset = mac->ssb_subcarrier_offset;

  if (mac->frequency_range == FR1){
laurent's avatar
laurent committed
182
    cfg->ssb_table.ssb_mask_list[0].ssb_mask = ((uint32_t) scc->ssb_PositionsInBurst.inOneGroup.buf[0]) << 24;
183 184 185 186 187
    cfg->ssb_table.ssb_mask_list[1].ssb_mask = 0;
  }
  else{
    for (int i=0; i<8; i++){
      if ((scc->ssb_PositionsInBurst.groupPresence->buf[0]>>(7-i))&0x01)
luis_pereira87's avatar
luis_pereira87 committed
188
        cfg->ssb_table.ssb_mask_list[i>>2].ssb_mask |= ((uint32_t)scc->ssb_PositionsInBurst.inOneGroup.buf[0])<<(24-8*(i%4));
189 190 191 192
    }
  }

  // TDD Table Configuration
193
  if (cfg->cell_config.frame_duplex_type == TDD){
194
    set_tdd_config_nr_ue(&cfg->tdd_table_1, cfg->ssb_config.scs_common, &mac->tdd_UL_DL_ConfigurationCommon->pattern1);
francescomani's avatar
francescomani committed
195 196
    if (mac->tdd_UL_DL_ConfigurationCommon->pattern2) {
      cfg->tdd_table_2 = (fapi_nr_tdd_table_t *) malloc(sizeof(fapi_nr_tdd_table_t));
197
      set_tdd_config_nr_ue(cfg->tdd_table_2, cfg->ssb_config.scs_common, mac->tdd_UL_DL_ConfigurationCommon->pattern2);
francescomani's avatar
francescomani committed
198
    }
199 200 201 202 203
  }

  // PRACH configuration

  uint8_t nb_preambles = 64;
204 205 206
  NR_RACH_ConfigCommon_t *rach_ConfigCommon = scc->uplinkConfigCommon->initialUplinkBWP.rach_ConfigCommon->choice.setup;
  if(rach_ConfigCommon->totalNumberOfRA_Preambles != NULL)
     nb_preambles = *rach_ConfigCommon->totalNumberOfRA_Preambles;
207

208
  cfg->prach_config.prach_sequence_length = rach_ConfigCommon->prach_RootSequenceIndex.present-1;
209

210 211
  if (rach_ConfigCommon->msg1_SubcarrierSpacing)
    cfg->prach_config.prach_sub_c_spacing = *rach_ConfigCommon->msg1_SubcarrierSpacing;
212 213 214 215 216 217 218
  else {
    // If absent, the UE applies the SCS as derived from the prach-ConfigurationIndex (for 839)
    int config_index = rach_ConfigCommon->rach_ConfigGeneric.prach_ConfigurationIndex;
    const int64_t *prach_config_info_p = get_prach_config_info(mac->frequency_range, config_index, mac->frame_type);
    int format = prach_config_info_p[0];
    cfg->prach_config.prach_sub_c_spacing = format == 3 ? 5 : 4;
  }
219

220
  cfg->prach_config.restricted_set_config = rach_ConfigCommon->restrictedSetConfig;
221

222 223 224 225
  AssertFatal(rach_ConfigCommon->rach_ConfigGeneric.msg1_FDM < 4,
              "msg1 FDM identifier %ld undefined (0,1,2,3)\n", rach_ConfigCommon->rach_ConfigGeneric.msg1_FDM);
  cfg->prach_config.num_prach_fd_occasions = 1 << rach_ConfigCommon->rach_ConfigGeneric.msg1_FDM;

226 227 228

  cfg->prach_config.num_prach_fd_occasions_list = (fapi_nr_num_prach_fd_occasions_t *) malloc(cfg->prach_config.num_prach_fd_occasions*sizeof(fapi_nr_num_prach_fd_occasions_t));
  for (int i=0; i<cfg->prach_config.num_prach_fd_occasions; i++) {
229 230
    fapi_nr_num_prach_fd_occasions_t *prach_fd_occasion = &cfg->prach_config.num_prach_fd_occasions_list[i];
    prach_fd_occasion->num_prach_fd_occasions = i;
231
    if (cfg->prach_config.prach_sequence_length)
232
      prach_fd_occasion->prach_root_sequence_index = rach_ConfigCommon->prach_RootSequenceIndex.choice.l139;
233
    else
234 235 236 237 238 239 240 241
      prach_fd_occasion->prach_root_sequence_index = rach_ConfigCommon->prach_RootSequenceIndex.choice.l839;
    prach_fd_occasion->k1 = NRRIV2PRBOFFSET(scc->uplinkConfigCommon->initialUplinkBWP.genericParameters.locationAndBandwidth, MAX_BWP_SIZE) +
                                            rach_ConfigCommon->rach_ConfigGeneric.msg1_FrequencyStart +
                                            (get_N_RA_RB(cfg->prach_config.prach_sub_c_spacing, frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing ) * i);
    prach_fd_occasion->prach_zero_corr_conf = rach_ConfigCommon->rach_ConfigGeneric.zeroCorrelationZoneConfig;
    prach_fd_occasion->num_root_sequences = compute_nr_root_seq(rach_ConfigCommon,
                                                                nb_preambles, mac->frame_type, mac->frequency_range);
    //prach_fd_occasion->num_unused_root_sequences = ???
242
  }
243
  cfg->prach_config.ssb_per_rach = rach_ConfigCommon->ssb_perRACH_OccasionAndCB_PreamblesPerSSB->present-1;
244 245 246

}

247 248 249
static void config_common_ue(NR_UE_MAC_INST_t *mac,
                             NR_ServingCellConfigCommon_t *scc,
                             int cc_idP)
250
{
251
  fapi_nr_config_request_t *cfg = &mac->phy_config.config_req;
Raymond Knopp's avatar
Raymond Knopp committed
252

253
  mac->phy_config.Mod_id = mac->ue_id;
cig's avatar
cig committed
254
  mac->phy_config.CC_id = cc_idP;
255
  
256
  // carrier config
257
  LOG_D(MAC, "[UE %d] Entering UE Config Common\n", mac->ue_id);
258

259
  AssertFatal(scc->downlinkConfigCommon, "Not expecting downlinkConfigCommon to be NULL here\n");
260

261 262 263 264 265 266
  NR_FrequencyInfoDL_t *frequencyInfoDL = scc->downlinkConfigCommon->frequencyInfoDL;
  if (frequencyInfoDL) { // NeedM for inter-freq handover
    mac->nr_band = *frequencyInfoDL->frequencyBandList.list.array[0];
    mac->frame_type = get_frame_type(mac->nr_band, get_softmodem_params()->numerology);
    mac->frequency_range = mac->nr_band < 256 ? FR1 : FR2;

267 268 269 270
    int bw_index = get_supported_band_index(frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing,
                                            mac->frequency_range,
                                            frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth);
    cfg->carrier_config.dl_bandwidth = get_supported_bw_mhz(mac->frequency_range, bw_index);
271

272 273
    cfg->carrier_config.dl_frequency = from_nrarfcn(mac->nr_band,
                                                    *scc->ssbSubcarrierSpacing,
274 275 276
                                                    frequencyInfoDL->absoluteFrequencyPointA)
                                       / 1000; // freq in kHz

277 278 279 280
    for (int i = 0; i < 5; i++) {
      if (i == frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing) {
        cfg->carrier_config.dl_grid_size[i] = frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth;
        cfg->carrier_config.dl_k0[i] = frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->offsetToCarrier;
281
      } else {
282 283 284
        cfg->carrier_config.dl_grid_size[i] = 0;
        cfg->carrier_config.dl_k0[i] = 0;
      }
285
    }
286 287
  }

288 289
  if (scc->uplinkConfigCommon && scc->uplinkConfigCommon->frequencyInfoUL) {
    NR_FrequencyInfoUL_t *frequencyInfoUL = scc->uplinkConfigCommon->frequencyInfoUL;
290
    mac->p_Max = frequencyInfoUL->p_Max ? *frequencyInfoUL->p_Max : INT_MIN;
291

292 293 294 295
    int bw_index = get_supported_band_index(frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing,
                                            mac->frequency_range,
                                            frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth);
    cfg->carrier_config.uplink_bandwidth = get_supported_bw_mhz(mac->frequency_range, bw_index);
296 297 298 299 300 301 302

    long *UL_pointA = NULL;
    if (frequencyInfoUL->absoluteFrequencyPointA)
      UL_pointA = frequencyInfoUL->absoluteFrequencyPointA;
    else if (frequencyInfoDL)
      UL_pointA = &frequencyInfoDL->absoluteFrequencyPointA;

303
    if (UL_pointA)
304 305
      cfg->carrier_config.uplink_frequency = from_nrarfcn(*frequencyInfoUL->frequencyBandList->list.array[0],
                                                          *scc->ssbSubcarrierSpacing,
306 307
                                                          *UL_pointA)
                                             / 1000; // freq in kHz
308 309 310 311 312

    for (int i = 0; i < 5; i++) {
      if (i == frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing) {
        cfg->carrier_config.ul_grid_size[i] = frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->carrierBandwidth;
        cfg->carrier_config.ul_k0[i] = frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->offsetToCarrier;
313
      } else {
314 315 316
        cfg->carrier_config.ul_grid_size[i] = 0;
        cfg->carrier_config.ul_k0[i] = 0;
      }
317
    }
318
  }
319

320 321
  // cell config
  cfg->cell_config.phy_cell_id = *scc->physCellId;
322
  cfg->cell_config.frame_duplex_type = mac->frame_type;
323 324 325 326 327 328

  // SSB config
  cfg->ssb_config.ss_pbch_power = scc->ss_PBCH_BlockPower;
  cfg->ssb_config.scs_common = *scc->ssbSubcarrierSpacing;

  // SSB Table config
329
  if (frequencyInfoDL && frequencyInfoDL->absoluteFrequencySSB) {
330
    int scs_scaling = 1 << (cfg->ssb_config.scs_common);
331
    if (frequencyInfoDL->absoluteFrequencyPointA < 600000)
332
      scs_scaling = scs_scaling * 3;
333
    if (frequencyInfoDL->absoluteFrequencyPointA > 2016666)
334
      scs_scaling = scs_scaling >> 2;
335
    uint32_t absolute_diff = (*frequencyInfoDL->absoluteFrequencySSB - frequencyInfoDL->absoluteFrequencyPointA);
336
    cfg->ssb_table.ssb_offset_point_a = absolute_diff / (12 * scs_scaling) - 10;
337 338
    cfg->ssb_table.ssb_period = *scc->ssb_periodicityServingCell;
    // NSA -> take ssb offset from SCS
339
    cfg->ssb_table.ssb_subcarrier_offset = absolute_diff % (12 * scs_scaling);
340
  }
341 342 343

  switch (scc->ssb_PositionsInBurst->present) {
  case 1 :
344
    cfg->ssb_table.ssb_mask_list[0].ssb_mask = scc->ssb_PositionsInBurst->choice.shortBitmap.buf[0] << 24;
345 346 347 348 349 350 351 352 353 354
    cfg->ssb_table.ssb_mask_list[1].ssb_mask = 0;
    break;
  case 2 :
    cfg->ssb_table.ssb_mask_list[0].ssb_mask = ((uint32_t) scc->ssb_PositionsInBurst->choice.mediumBitmap.buf[0]) << 24;
    cfg->ssb_table.ssb_mask_list[1].ssb_mask = 0;
    break;
  case 3 :
    cfg->ssb_table.ssb_mask_list[0].ssb_mask = 0;
    cfg->ssb_table.ssb_mask_list[1].ssb_mask = 0;
    for (int i = 0; i < 4; i++) {
Laurent THOMAS's avatar
Laurent THOMAS committed
355 356
      cfg->ssb_table.ssb_mask_list[0].ssb_mask += (uint32_t) scc->ssb_PositionsInBurst->choice.longBitmap.buf[3 - i] << i * 8;
      cfg->ssb_table.ssb_mask_list[1].ssb_mask += (uint32_t) scc->ssb_PositionsInBurst->choice.longBitmap.buf[7 - i] << i * 8;
357 358 359 360 361 362 363 364
    }
    break;
  default:
    AssertFatal(1==0,"SSB bitmap size value %d undefined (allowed values 1,2,3) \n", scc->ssb_PositionsInBurst->present);
  }

  // TDD Table Configuration
  if (cfg->cell_config.frame_duplex_type == TDD){
365
    set_tdd_config_nr_ue(&cfg->tdd_table_1, cfg->ssb_config.scs_common, &mac->tdd_UL_DL_ConfigurationCommon->pattern1);
francescomani's avatar
francescomani committed
366 367
    if (mac->tdd_UL_DL_ConfigurationCommon->pattern2) {
      cfg->tdd_table_2 = (fapi_nr_tdd_table_t *) malloc(sizeof(fapi_nr_tdd_table_t));
368
      set_tdd_config_nr_ue(cfg->tdd_table_2, cfg->ssb_config.scs_common, mac->tdd_UL_DL_ConfigurationCommon->pattern2);
francescomani's avatar
francescomani committed
369
    }
370 371 372 373
  }

  // PRACH configuration
  uint8_t nb_preambles = 64;
374 375
  if (scc->uplinkConfigCommon && scc->uplinkConfigCommon->initialUplinkBWP
      && scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon) { // all NeedM
376

377
    NR_RACH_ConfigCommon_t *rach_ConfigCommon = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup;
378
    if (rach_ConfigCommon->totalNumberOfRA_Preambles != NULL)
379
      nb_preambles = *rach_ConfigCommon->totalNumberOfRA_Preambles;
380

381
    cfg->prach_config.prach_sequence_length = rach_ConfigCommon->prach_RootSequenceIndex.present - 1;
382

383 384 385 386 387 388 389 390 391
    if (rach_ConfigCommon->msg1_SubcarrierSpacing)
      cfg->prach_config.prach_sub_c_spacing = *rach_ConfigCommon->msg1_SubcarrierSpacing;
    else {
      // If absent, the UE applies the SCS as derived from the prach-ConfigurationIndex (for 839)
      int config_index = rach_ConfigCommon->rach_ConfigGeneric.prach_ConfigurationIndex;
      const int64_t *prach_config_info_p = get_prach_config_info(mac->frequency_range, config_index, mac->frame_type);
      int format = prach_config_info_p[0];
      cfg->prach_config.prach_sub_c_spacing = format == 3 ? 5 : 4;
    }
392

393 394
    cfg->prach_config.restricted_set_config = rach_ConfigCommon->restrictedSetConfig;

395 396 397
    AssertFatal(rach_ConfigCommon->rach_ConfigGeneric.msg1_FDM < 4,
                "msg1 FDM identifier %ld undefined (0,1,2,3)\n", rach_ConfigCommon->rach_ConfigGeneric.msg1_FDM);
    cfg->prach_config.num_prach_fd_occasions = 1 << rach_ConfigCommon->rach_ConfigGeneric.msg1_FDM;
398

399 400
    cfg->prach_config.num_prach_fd_occasions_list = (fapi_nr_num_prach_fd_occasions_t *)malloc(
        cfg->prach_config.num_prach_fd_occasions * sizeof(fapi_nr_num_prach_fd_occasions_t));
401 402 403 404 405 406 407 408 409 410
    for (int i = 0; i < cfg->prach_config.num_prach_fd_occasions; i++) {
      fapi_nr_num_prach_fd_occasions_t *prach_fd_occasion = &cfg->prach_config.num_prach_fd_occasions_list[i];
      prach_fd_occasion->num_prach_fd_occasions = i;
      if (cfg->prach_config.prach_sequence_length)
        prach_fd_occasion->prach_root_sequence_index = rach_ConfigCommon->prach_RootSequenceIndex.choice.l139;
      else
        prach_fd_occasion->prach_root_sequence_index = rach_ConfigCommon->prach_RootSequenceIndex.choice.l839;

      prach_fd_occasion->k1 = rach_ConfigCommon->rach_ConfigGeneric.msg1_FrequencyStart;
      prach_fd_occasion->prach_zero_corr_conf = rach_ConfigCommon->rach_ConfigGeneric.zeroCorrelationZoneConfig;
411 412
      prach_fd_occasion->num_root_sequences =
          compute_nr_root_seq(rach_ConfigCommon, nb_preambles, mac->frame_type, mac->frequency_range);
413

414 415
      cfg->prach_config.ssb_per_rach = rach_ConfigCommon->ssb_perRACH_OccasionAndCB_PreamblesPerSSB->present - 1;
      // prach_fd_occasion->num_unused_root_sequences = ???
416
    }
417
  }
418 419 420 421 422 423 424

  // NTN Config
  if (scc->ext2) {
    UPDATE_IE(mac->sc_info.ntn_Config_r17, scc->ext2->ntn_Config_r17, NR_NTN_Config_r17_t);
  } else {
    asn1cFreeStruc(asn_DEF_NR_NTN_Config_r17, mac->sc_info.ntn_Config_r17);
  }
Raymond Knopp's avatar
Raymond Knopp committed
425 426
}

427 428
void release_common_ss_cset(NR_BWP_PDCCH_t *pdcch)
{
429 430 431 432
  asn1cFreeStruc(asn_DEF_NR_SearchSpace, pdcch->otherSI_SS);
  asn1cFreeStruc(asn_DEF_NR_SearchSpace, pdcch->ra_SS);
  asn1cFreeStruc(asn_DEF_NR_SearchSpace, pdcch->paging_SS);
  asn1cFreeStruc(asn_DEF_NR_ControlResourceSet, pdcch->commonControlResourceSet);
433 434
}

435
static void modlist_ss(NR_SearchSpace_t *source, NR_SearchSpace_t *target)
436 437 438
{
  target->searchSpaceId = source->searchSpaceId;
  if (source->controlResourceSetId)
439
    UPDATE_IE(target->controlResourceSetId, source->controlResourceSetId, NR_ControlResourceSetId_t);
440
  if (source->monitoringSlotPeriodicityAndOffset)
441 442 443 444
    UPDATE_IE(target->monitoringSlotPeriodicityAndOffset,
              source->monitoringSlotPeriodicityAndOffset,
              struct NR_SearchSpace__monitoringSlotPeriodicityAndOffset);
  UPDATE_IE(target->duration, source->duration, long);
445
  if (source->monitoringSymbolsWithinSlot)
446
    UPDATE_IE(target->monitoringSymbolsWithinSlot, source->monitoringSymbolsWithinSlot, BIT_STRING_t);
447
  if (source->nrofCandidates)
448
    UPDATE_IE(target->nrofCandidates, source->nrofCandidates, struct NR_SearchSpace__nrofCandidates);
449
  if (source->searchSpaceType)
450
    UPDATE_IE(target->searchSpaceType, source->searchSpaceType, struct NR_SearchSpace__searchSpaceType);
451
}
452

453 454
static NR_SearchSpace_t *get_common_search_space(const NR_UE_MAC_INST_t *mac,
                                                 const struct NR_PDCCH_ConfigCommon__commonSearchSpaceList *commonSearchSpaceList,
455 456
                                                 const NR_BWP_PDCCH_t *pdcch,
                                                 const NR_SearchSpaceId_t ss_id)
457 458
{
  if (ss_id == 0)
459
    return mac->search_space_zero;
460 461 462 463

  NR_SearchSpace_t *css = NULL;
  for (int i = 0; i < commonSearchSpaceList->list.count; i++) {
    if (commonSearchSpaceList->list.array[i]->searchSpaceId == ss_id) {
464 465
      css = calloc(1, sizeof(*css));
      modlist_ss(commonSearchSpaceList->list.array[i], css);
466 467 468 469 470 471 472
      break;
    }
  }
  AssertFatal(css, "Couldn't find CSS with Id %ld\n", ss_id);
  return css;
}

473 474 475
static void configure_common_ss_coreset(const NR_UE_MAC_INST_t *mac,
                                        NR_BWP_PDCCH_t *pdcch,
                                        NR_PDCCH_ConfigCommon_t *pdcch_ConfigCommon)
476 477
{
  if (pdcch_ConfigCommon) {
478
    asn1cFreeStruc(asn_DEF_NR_SearchSpace, pdcch->otherSI_SS);
479
    if (pdcch_ConfigCommon->searchSpaceOtherSystemInformation)
480 481
      pdcch->otherSI_SS = get_common_search_space(mac,
                                                  pdcch_ConfigCommon->commonSearchSpaceList,
482 483 484
                                                  pdcch,
                                                  *pdcch_ConfigCommon->searchSpaceOtherSystemInformation);

485
    asn1cFreeStruc(asn_DEF_NR_SearchSpace, pdcch->ra_SS);
486
    if (pdcch_ConfigCommon->ra_SearchSpace) {
487
      if (pdcch->otherSI_SS && *pdcch_ConfigCommon->ra_SearchSpace == pdcch->otherSI_SS->searchSpaceId)
488 489
        pdcch->ra_SS = pdcch->otherSI_SS;
      else
490
        pdcch->ra_SS =
491
            get_common_search_space(mac, pdcch_ConfigCommon->commonSearchSpaceList, pdcch, *pdcch_ConfigCommon->ra_SearchSpace);
492 493
    }

494
    asn1cFreeStruc(asn_DEF_NR_SearchSpace, pdcch->paging_SS);
495
    if (pdcch_ConfigCommon->pagingSearchSpace) {
496
      if (pdcch->otherSI_SS && *pdcch_ConfigCommon->pagingSearchSpace == pdcch->otherSI_SS->searchSpaceId)
497
        pdcch->paging_SS = pdcch->otherSI_SS;
498
      else if (pdcch->ra_SS && *pdcch_ConfigCommon->pagingSearchSpace == pdcch->ra_SS->searchSpaceId)
499 500
        pdcch->paging_SS = pdcch->ra_SS;
      if (!pdcch->paging_SS)
501
        pdcch->paging_SS =
502
            get_common_search_space(mac, pdcch_ConfigCommon->commonSearchSpaceList, pdcch, *pdcch_ConfigCommon->pagingSearchSpace);
503 504
    }

505
    UPDATE_IE(pdcch->commonControlResourceSet, pdcch_ConfigCommon->commonControlResourceSet, NR_ControlResourceSet_t);
506 507 508
  }
}

509
static void modlist_coreset(NR_ControlResourceSet_t *source, NR_ControlResourceSet_t *target)
510 511 512
{
  target->controlResourceSetId = source->controlResourceSetId;
  target->frequencyDomainResources.size = source->frequencyDomainResources.size;
francescomani's avatar
francescomani committed
513
  if (!target->frequencyDomainResources.buf)
514 515
    target->frequencyDomainResources.buf =
        calloc(target->frequencyDomainResources.size, sizeof(*target->frequencyDomainResources.buf));
516 517 518 519 520 521 522 523 524 525
  for (int i = 0; i < source->frequencyDomainResources.size; i++)
    target->frequencyDomainResources.buf[i] = source->frequencyDomainResources.buf[i];
  target->duration = source->duration;
  target->precoderGranularity = source->precoderGranularity;
  long *shiftIndex = NULL;
  if (target->cce_REG_MappingType.present == NR_ControlResourceSet__cce_REG_MappingType_PR_interleaved)
    shiftIndex = target->cce_REG_MappingType.choice.interleaved->shiftIndex;
  if (source->cce_REG_MappingType.present == NR_ControlResourceSet__cce_REG_MappingType_PR_interleaved) {
    target->cce_REG_MappingType.present = NR_ControlResourceSet__cce_REG_MappingType_PR_interleaved;
    target->cce_REG_MappingType.choice.interleaved->reg_BundleSize = source->cce_REG_MappingType.choice.interleaved->reg_BundleSize;
526 527
    target->cce_REG_MappingType.choice.interleaved->interleaverSize =
        source->cce_REG_MappingType.choice.interleaved->interleaverSize;
528 529 530
    UPDATE_IE(target->cce_REG_MappingType.choice.interleaved->shiftIndex,
              source->cce_REG_MappingType.choice.interleaved->shiftIndex,
              long);
531 532
  } else {
    free(shiftIndex);
533 534
    target->cce_REG_MappingType = source->cce_REG_MappingType;
  }
535 536
  UPDATE_IE(target->tci_PresentInDCI, source->tci_PresentInDCI, long);
  UPDATE_IE(target->pdcch_DMRS_ScramblingID, source->pdcch_DMRS_ScramblingID, long);
537 538 539 540 541 542
  // TCI States
  if (source->tci_StatesPDCCH_ToReleaseList) {
    for (int i = 0; i < source->tci_StatesPDCCH_ToReleaseList->list.count; i++) {
      long id = *source->tci_StatesPDCCH_ToReleaseList->list.array[i];
      int j;
      for (j = 0; j < target->tci_StatesPDCCH_ToAddList->list.count; j++) {
543
        if (id == *target->tci_StatesPDCCH_ToAddList->list.array[j])
544 545 546 547 548 549 550 551 552
          break;
      }
      if (j < target->tci_StatesPDCCH_ToAddList->list.count)
        asn_sequence_del(&target->tci_StatesPDCCH_ToAddList->list, j, 1);
      else
        LOG_E(NR_MAC, "Element not present in the list, impossible to release\n");
    }
  }
  if (source->tci_StatesPDCCH_ToAddList) {
francescomani's avatar
francescomani committed
553 554 555 556 557
    if (target->tci_StatesPDCCH_ToAddList) {
      for (int i = 0; i < source->tci_StatesPDCCH_ToAddList->list.count; i++) {
        long id = *source->tci_StatesPDCCH_ToAddList->list.array[i];
        int j;
        for (j = 0; j < target->tci_StatesPDCCH_ToAddList->list.count; j++) {
558
          if (id == *target->tci_StatesPDCCH_ToAddList->list.array[j])
francescomani's avatar
francescomani committed
559 560 561
            break;
        }
        if (j == target->tci_StatesPDCCH_ToAddList->list.count)
562
          ASN_SEQUENCE_ADD(&target->tci_StatesPDCCH_ToAddList->list, source->tci_StatesPDCCH_ToAddList->list.array[i]);
francescomani's avatar
francescomani committed
563
      }
564
    } else
565 566 567
      UPDATE_IE(target->tci_StatesPDCCH_ToAddList,
                source->tci_StatesPDCCH_ToAddList,
                struct NR_ControlResourceSet__tci_StatesPDCCH_ToAddList);
568 569 570 571
  }
  // end TCI States
}

572
static void configure_ss_coreset(NR_BWP_PDCCH_t *pdcch, NR_PDCCH_Config_t *pdcch_Config)
573
{
574
  if (!pdcch_Config)
575
    return;
576
  if (pdcch_Config->controlResourceSetToAddModList) {
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
    for (int i = 0; i < pdcch_Config->controlResourceSetToAddModList->list.count; i++) {
      NR_ControlResourceSet_t *source_coreset = pdcch_Config->controlResourceSetToAddModList->list.array[i];
      NR_ControlResourceSet_t *target_coreset = NULL;
      for (int j = 0; j < pdcch->list_Coreset.count; j++) {
        if (pdcch->list_Coreset.array[j]->controlResourceSetId == source_coreset->controlResourceSetId) {
          target_coreset = pdcch->list_Coreset.array[j];
          break;
        }
      }
      if (!target_coreset) {
        target_coreset = calloc(1, sizeof(*target_coreset));
        ASN_SEQUENCE_ADD(&pdcch->list_Coreset, target_coreset);
      }
      modlist_coreset(source_coreset, target_coreset);
    }
  }
593
  if (pdcch_Config->controlResourceSetToReleaseList) {
594 595 596 597 598 599 600 601 602 603
    for (int i = 0; i < pdcch_Config->controlResourceSetToReleaseList->list.count; i++) {
      NR_ControlResourceSetId_t id = *pdcch_Config->controlResourceSetToReleaseList->list.array[i];
      for (int j = 0; j < pdcch->list_Coreset.count; j++) {
        if (id == pdcch->list_Coreset.array[j]->controlResourceSetId) {
          asn_sequence_del(&pdcch->list_Coreset, j, 1);
          break;
        }
      }
    }
  }
604
  if (pdcch_Config->searchSpacesToAddModList) {
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    for (int i = 0; i < pdcch_Config->searchSpacesToAddModList->list.count; i++) {
      NR_SearchSpace_t *source_ss = pdcch_Config->searchSpacesToAddModList->list.array[i];
      NR_SearchSpace_t *target_ss = NULL;
      for (int j = 0; j < pdcch->list_SS.count; j++) {
        if (pdcch->list_SS.array[j]->searchSpaceId == source_ss->searchSpaceId) {
          target_ss = pdcch->list_SS.array[j];
          break;
        }
      }
      if (!target_ss) {
        target_ss = calloc(1, sizeof(*target_ss));
        ASN_SEQUENCE_ADD(&pdcch->list_SS, target_ss);
      }
      modlist_ss(source_ss, target_ss);
    }
  }
621
  if (pdcch_Config->searchSpacesToReleaseList) {
622 623 624 625 626 627 628
    for (int i = 0; i < pdcch_Config->searchSpacesToReleaseList->list.count; i++) {
      NR_ControlResourceSetId_t id = *pdcch_Config->searchSpacesToReleaseList->list.array[i];
      for (int j = 0; j < pdcch->list_SS.count; j++) {
        if (id == pdcch->list_SS.array[j]->searchSpaceId) {
          asn_sequence_del(&pdcch->list_SS, j, 1);
          break;
        }
629 630
      }
    }
631 632 633
  }
}

634
static int lcid_cmp(const void *a, const void *b)
635
{
636 637 638 639 640
  long priority_a = (*((nr_lcordered_info_t**)a))->priority;
  AssertFatal(priority_a > 0 && priority_a < 17, "Invalid priority value %ld\n", priority_a);
  long priority_b = (*((nr_lcordered_info_t**)b))->priority;
  AssertFatal(priority_b > 0 && priority_b < 17, "Invalid priority value %ld\n", priority_b);
  return priority_a - priority_b;
641 642
}

643
static int nr_get_ms_bucketsizeduration(long bucketsizeduration)
Sriharsha Korada's avatar
Sriharsha Korada committed
644 645
{
  switch (bucketsizeduration) {
646 647 648 649 650 651
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms5:
      return 5;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms10:
      return 10;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms20:
      return 20;
Sriharsha Korada's avatar
Sriharsha Korada committed
652 653 654 655 656 657 658 659 660 661 662 663 664
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms50:
      return 50;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms100:
      return 100;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms150:
      return 150;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms300:
      return 300;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms500:
      return 500;
    case NR_LogicalChannelConfig__ul_SpecificParameters__bucketSizeDuration_ms1000:
      return 1000;
    default:
665
      AssertFatal(false, "Invalid bucketSizeDuration %ld\n", bucketsizeduration);
Sriharsha Korada's avatar
Sriharsha Korada committed
666 667 668
  }
}

669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
static uint32_t nr_get_pbr(long prioritizedbitrate)  // returns Bps
{
  uint32_t pbr = 0;
  switch (prioritizedbitrate) {
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps0:
      pbr = 0;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps8:
      pbr = 8;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps16:
      pbr = 16;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps32:
      pbr = 32;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps64:
      pbr = 64;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps128:
      pbr = 128;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps256:
      pbr = 256;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps512:
      pbr = 512;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps1024:
      pbr = 1024;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps2048:
      pbr = 2048;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps4096:
      pbr = 4096;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps8192:
      pbr = 8192;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps16384:
      pbr = 16384;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps32768:
      pbr = 32768;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_kBps65536:
      pbr = 65536;
      break;
    case NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_infinity:
      pbr = UINT_MAX;
      break;
    default:
      AssertFatal(false, "The proritized bit rate value is not one of the enum values\n");
  }
  uint32_t pbr_bytes =
      (prioritizedbitrate < NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_infinity) ? pbr * 1000 : pbr;
  return pbr_bytes;
}

729
static uint32_t get_lc_bucket_size(long prioritisedBitRate, long bucketSizeDuration)
730
{
731 732
  uint32_t pbr = nr_get_pbr(prioritisedBitRate);
  // if infinite pbr, the bucket is saturated by pbr
733 734 735 736 737
  int bsd = 0;
  if (prioritisedBitRate == NR_LogicalChannelConfig__ul_SpecificParameters__prioritisedBitRate_infinity)
    bsd = 1;
  else
    bsd = nr_get_ms_bucketsizeduration(bucketSizeDuration);
738

739 740
  return pbr * bsd;
}
741

742 743 744 745 746
// default configuration as per 38.331 section 9.2.1
static void set_default_logicalchannelconfig(nr_lcordered_info_t *lc_info, NR_SRB_Identity_t srb_id)
{
  lc_info->lcid = srb_id;
  lc_info->priority = srb_id == 2 ? 3 : 1;
747 748
  lc_info->pbr = UINT_MAX;
  lc_info->bucket_size = UINT_MAX;
749
}
750

751 752 753 754 755
static void nr_configure_lc_config(NR_UE_MAC_INST_t *mac,
                                   nr_lcordered_info_t *lc_info,
                                   NR_LogicalChannelConfig_t *mac_lc_config,
                                   NR_SRB_Identity_t srb_id)
{
756
  NR_LC_SCHEDULING_INFO *lc_sched_info = get_scheduling_info_from_lcid(mac, lc_info->lcid);
757 758 759
  if (srb_id > 0 && !mac_lc_config->ul_SpecificParameters) {
    // release configuration and reset to default
    set_default_logicalchannelconfig(lc_info, srb_id);
760 761
    // invalid LCGID to signal it is absent in the configuration
    lc_sched_info->LCGID = NR_INVALID_LCGID;
762
    return;
763
  }
764 765 766
  AssertFatal(mac_lc_config->ul_SpecificParameters, "UL parameters shouldn't be NULL for DRBs\n");
  struct NR_LogicalChannelConfig__ul_SpecificParameters *ul_parm = mac_lc_config->ul_SpecificParameters;
  lc_info->priority = ul_parm->priority;
767
  lc_info->sr_id = ul_parm->schedulingRequestID ? *ul_parm->schedulingRequestID : -1;
768
  lc_info->sr_DelayTimerApplied = ul_parm->logicalChannelSR_DelayTimerApplied;
769
  lc_info->lc_SRMask = ul_parm->logicalChannelSR_Mask;
770
  lc_info->pbr = nr_get_pbr(ul_parm->prioritisedBitRate);
771 772
  // if logicalChannelGroup we release LCGID and set it to invalid
  lc_sched_info->LCGID = ul_parm->logicalChannelGroup ? *ul_parm->logicalChannelGroup : NR_INVALID_LCGID;
773
  lc_info->bucket_size = get_lc_bucket_size(ul_parm->prioritisedBitRate, ul_parm->bucketSizeDuration);
774
  // setup and start Bj timer for this LC
775
  NR_timer_t *bjt = &lc_sched_info->Bj_timer;
776 777
  nr_timer_setup(bjt, UINT_MAX, 1);  // this timer never expires in principle, counter incremented by number of slots
  nr_timer_start(bjt);
778 779
}

780
static void configure_logicalChannelBearer(NR_UE_MAC_INST_t *mac,
781 782
                                           struct NR_CellGroupConfig__rlc_BearerToAddModList *rlc_toadd_list,
                                           struct NR_CellGroupConfig__rlc_BearerToReleaseList *rlc_torelease_list)
783 784 785
{
  if (rlc_torelease_list) {
    for (int i = 0; i < rlc_torelease_list->list.count; i++) {
786 787 788 789 790 791
      long id = *rlc_torelease_list->list.array[i];
      int j;
      for (j = 0; j < mac->lc_ordered_list.count; j++) {
        if (id == mac->lc_ordered_list.array[j]->lcid)
          break;
      }
792 793
      if (j < mac->lc_ordered_list.count)
        asn_sequence_del(&mac->lc_ordered_list, j, 1);
794 795
      else
        LOG_E(NR_MAC, "Element not present in the list, impossible to release\n");
796 797
    }
  }
798

799 800 801 802
  if (rlc_toadd_list) {
    for (int i = 0; i < rlc_toadd_list->list.count; i++) {
      NR_RLC_BearerConfig_t *rlc_bearer = rlc_toadd_list->list.array[i];
      int lc_identity = rlc_bearer->logicalChannelIdentity;
803 804 805 806 807 808 809 810 811
      NR_LogicalChannelConfig_t *mac_lc_config = rlc_bearer->mac_LogicalChannelConfig;
      int j;
      for (j = 0; j < mac->lc_ordered_list.count; j++) {
        if (lc_identity == mac->lc_ordered_list.array[j]->lcid)
          break;
      }
      if (j < mac->lc_ordered_list.count) {
        LOG_D(NR_MAC, "Logical channel %d is already established, Reconfiguring now\n", lc_identity);
        if (mac_lc_config != NULL) {
812 813 814 815
          NR_SRB_Identity_t srb_id = 0;
          if (rlc_bearer->servedRadioBearer->present == NR_RLC_BearerConfig__servedRadioBearer_PR_srb_Identity)
            srb_id = rlc_bearer->servedRadioBearer->choice.srb_Identity;
          nr_configure_lc_config(mac, mac->lc_ordered_list.array[j], mac_lc_config, srb_id);
816 817 818
        }
      }
      else {
819
        /* setup of new LCID*/
820 821
        nr_lcordered_info_t *lc_info = calloc(1, sizeof(*lc_info));
        lc_info->lcid = lc_identity;
822 823 824 825
        LOG_D(NR_MAC, "Establishing the logical channel %d\n", lc_identity);
        AssertFatal(rlc_bearer->servedRadioBearer, "servedRadioBearer should be present for LCID establishment\n");
        if (rlc_bearer->servedRadioBearer->present == NR_RLC_BearerConfig__servedRadioBearer_PR_srb_Identity) { /* SRB */
          NR_SRB_Identity_t srb_id = rlc_bearer->servedRadioBearer->choice.srb_Identity;
826 827 828 829
          if (mac_lc_config != NULL)
            nr_configure_lc_config(mac, lc_info, mac_lc_config, srb_id);
          else
            set_default_logicalchannelconfig(lc_info, srb_id);
830
        } else { /* DRB */
831
          AssertFatal(mac_lc_config, "When establishing a DRB, LogicalChannelConfig should be mandatorily present\n");
832
          nr_configure_lc_config(mac, lc_info, mac_lc_config, 0);
833
        }
834
        ASN_SEQUENCE_ADD(&mac->lc_ordered_list, lc_info);
francescomani's avatar
francescomani committed
835
      }
836
    }
837 838

    // reorder the logical channels as per its priority
839
    qsort(mac->lc_ordered_list.array, mac->lc_ordered_list.count, sizeof(nr_lcordered_info_t*), lcid_cmp);
840
  }
841 842
}

francescomani's avatar
francescomani committed
843
void ue_init_config_request(NR_UE_MAC_INST_t *mac, int scs)
francescomani's avatar
francescomani committed
844
{
francescomani's avatar
francescomani committed
845 846 847 848 849 850
  int slots_per_frame = nr_slots_per_frame[scs];
  LOG_I(NR_MAC, "Initializing dl and ul config_request. num_slots = %d\n", slots_per_frame);
  mac->dl_config_request = calloc(slots_per_frame, sizeof(*mac->dl_config_request));
  mac->ul_config_request = calloc(slots_per_frame, sizeof(*mac->ul_config_request));
  for (int i = 0; i < slots_per_frame; i++)
    pthread_mutex_init(&(mac->ul_config_request[i].mutex_ul_config), NULL);
851
}
francescomani's avatar
francescomani committed
852

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
static void update_mib_conf(NR_MIB_t *target, NR_MIB_t *source)
{
  target->systemFrameNumber.size = source->systemFrameNumber.size;
  target->systemFrameNumber.bits_unused = source->systemFrameNumber.bits_unused;
  if (!target->systemFrameNumber.buf)
    target->systemFrameNumber.buf = calloc(target->systemFrameNumber.size, sizeof(*target->systemFrameNumber.buf));
  for (int i = 0; i < target->systemFrameNumber.size; i++)
    target->systemFrameNumber.buf[i] = source->systemFrameNumber.buf[i];
  target->subCarrierSpacingCommon = source->subCarrierSpacingCommon;
  target->ssb_SubcarrierOffset = source->ssb_SubcarrierOffset;
  target->dmrs_TypeA_Position = source->dmrs_TypeA_Position;
  target->pdcch_ConfigSIB1 = source->pdcch_ConfigSIB1;
  target->cellBarred = source->cellBarred;
  target->intraFreqReselection = source->intraFreqReselection;
}

869 870 871
void nr_rrc_mac_config_req_mib(module_id_t module_id,
                               int cc_idP,
                               NR_MIB_t *mib,
872
                               int sched_sib)
francescomani's avatar
francescomani committed
873 874
{
  NR_UE_MAC_INST_t *mac = get_mac_inst(module_id);
875
  AssertFatal(mib, "MIB should not be NULL\n");
876 877 878
  if (!mac->mib)
    mac->mib = calloc(1, sizeof(*mac->mib));
  update_mib_conf(mac->mib, mib);
879 880
  mac->phy_config.Mod_id = module_id;
  mac->phy_config.CC_id = cc_idP;
881 882 883 884
  if (sched_sib == 1)
    mac->get_sib1 = true;
  else if (sched_sib == 2)
    mac->get_otherSI = true;
885
  nr_ue_decode_mib(mac, cc_idP);
886
}
887

888
static void setup_puschpowercontrol(NR_UE_MAC_INST_t *mac, NR_PUSCH_PowerControl_t *source, NR_PUSCH_PowerControl_t *target)
889
{
890 891
  UPDATE_IE(target->tpc_Accumulation, source->tpc_Accumulation, long);
  UPDATE_IE(target->msg3_Alpha, source->msg3_Alpha, NR_Alpha_t);
892
  if (source->p0_NominalWithoutGrant)
893
    UPDATE_IE(target->p0_NominalWithoutGrant, source->p0_NominalWithoutGrant, long);
894
  if (source->p0_AlphaSets) {
895
    UPDATE_IE(target->p0_AlphaSets, source->p0_AlphaSets, struct NR_PUSCH_PowerControl__p0_AlphaSets);
896 897 898 899 900 901 902
    if (target->p0_AlphaSets->list.array[0]->alpha) {
      mac->f_b_f_c = 0;
    }
    if (target->p0_AlphaSets->list.array[0]->p0) {
      mac->f_b_f_c = 0;
    }
  }
903 904
  UPDATE_IE(target->twoPUSCH_PC_AdjustmentStates, source->twoPUSCH_PC_AdjustmentStates, long);
  UPDATE_IE(target->deltaMCS, source->deltaMCS, long);
905
  if (source->pathlossReferenceRSToReleaseList) {
906 907 908
    RELEASE_IE_FROMLIST(source->pathlossReferenceRSToReleaseList,
                        target->pathlossReferenceRSToAddModList,
                        pusch_PathlossReferenceRS_Id);
909 910 911 912
  }
  if (source->pathlossReferenceRSToAddModList) {
    if (!target->pathlossReferenceRSToAddModList)
      target->pathlossReferenceRSToAddModList = calloc(1, sizeof(*target->pathlossReferenceRSToAddModList));
913 914 915 916
    ADDMOD_IE_FROMLIST(source->pathlossReferenceRSToAddModList,
                       target->pathlossReferenceRSToAddModList,
                       pusch_PathlossReferenceRS_Id,
                       NR_PUSCH_PathlossReferenceRS_t);
917 918
  }
  if (source->sri_PUSCH_MappingToReleaseList) {
919 920 921
    RELEASE_IE_FROMLIST(source->sri_PUSCH_MappingToReleaseList,
                        target->sri_PUSCH_MappingToAddModList,
                        sri_PUSCH_PowerControlId);
922 923
  }
  if (source->sri_PUSCH_MappingToAddModList) {
924
    LOG_E(NR_MAC, "NR_SRI_PUSCH_PowerControl not implemented, power control will not work as intended\n");
925 926
    if (!target->sri_PUSCH_MappingToAddModList)
      target->sri_PUSCH_MappingToAddModList = calloc(1, sizeof(*target->sri_PUSCH_MappingToAddModList));
927 928 929 930
    ADDMOD_IE_FROMLIST(source->sri_PUSCH_MappingToAddModList,
                       target->sri_PUSCH_MappingToAddModList,
                       sri_PUSCH_PowerControlId,
                       NR_SRI_PUSCH_PowerControl_t);
931 932 933
  }
}

934
static void setup_puschconfig(NR_UE_MAC_INST_t *mac, NR_PUSCH_Config_t *source, NR_PUSCH_Config_t *target)
935
{
936 937
  UPDATE_IE(target->dataScramblingIdentityPUSCH, source->dataScramblingIdentityPUSCH, long);
  UPDATE_IE(target->txConfig, source->txConfig, long);
938
  if (source->dmrs_UplinkForPUSCH_MappingTypeA)
939 940 941 942
    HANDLE_SETUPRELEASE_IE(target->dmrs_UplinkForPUSCH_MappingTypeA,
                           source->dmrs_UplinkForPUSCH_MappingTypeA,
                           NR_DMRS_UplinkConfig_t,
                           asn_DEF_NR_SetupRelease_DMRS_UplinkConfig);
943
  if (source->dmrs_UplinkForPUSCH_MappingTypeB)
944 945 946 947
    HANDLE_SETUPRELEASE_IE(target->dmrs_UplinkForPUSCH_MappingTypeB,
                           source->dmrs_UplinkForPUSCH_MappingTypeB,
                           NR_DMRS_UplinkConfig_t,
                           asn_DEF_NR_SetupRelease_DMRS_UplinkConfig);
948 949 950
  if (source->pusch_PowerControl) {
    if (!target->pusch_PowerControl)
      target->pusch_PowerControl = calloc(1, sizeof(*target->pusch_PowerControl));
951
    setup_puschpowercontrol(mac, source->pusch_PowerControl, target->pusch_PowerControl);
952
  }
953
  UPDATE_IE(target->frequencyHopping, source->frequencyHopping, long);
954
  if (source->frequencyHoppingOffsetLists)
955 956 957
    UPDATE_IE(target->frequencyHoppingOffsetLists,
              source->frequencyHoppingOffsetLists,
              struct NR_PUSCH_Config__frequencyHoppingOffsetLists);
958
  target->resourceAllocation = source->resourceAllocation;
959 960 961 962 963
  if (source->pusch_TimeDomainAllocationList)
    HANDLE_SETUPRELEASE_IE(target->pusch_TimeDomainAllocationList,
                           source->pusch_TimeDomainAllocationList,
                           NR_PUSCH_TimeDomainResourceAllocationList_t,
                           asn_DEF_NR_SetupRelease_PUSCH_TimeDomainResourceAllocationList);
964 965 966 967 968 969 970 971
  UPDATE_IE(target->pusch_AggregationFactor, source->pusch_AggregationFactor, long);
  UPDATE_IE(target->mcs_Table, source->mcs_Table, long);
  UPDATE_IE(target->mcs_TableTransformPrecoder, source->mcs_TableTransformPrecoder, long);
  UPDATE_IE(target->transformPrecoder, source->transformPrecoder, long);
  UPDATE_IE(target->codebookSubset, source->codebookSubset, long);
  UPDATE_IE(target->maxRank, source->maxRank, long);
  UPDATE_IE(target->rbg_Size, source->rbg_Size, long);
  UPDATE_IE(target->tp_pi2BPSK, source->tp_pi2BPSK, long);
972
  if (source->uci_OnPUSCH) {
973 974
    if (source->uci_OnPUSCH->present == NR_SetupRelease_UCI_OnPUSCH_PR_release)
      asn1cFreeStruc(asn_DEF_NR_UCI_OnPUSCH, target->uci_OnPUSCH);
975
    if (source->uci_OnPUSCH->present == NR_SetupRelease_UCI_OnPUSCH_PR_setup) {
francescomani's avatar
francescomani committed
976 977 978
      if (!target->uci_OnPUSCH) {
        target->uci_OnPUSCH = calloc(1, sizeof(*target->uci_OnPUSCH));
        target->uci_OnPUSCH->choice.setup = calloc(1, sizeof(*target->uci_OnPUSCH->choice.setup));
979
      }
francescomani's avatar
francescomani committed
980 981 982 983 984
      target->uci_OnPUSCH->choice.setup->scaling = source->uci_OnPUSCH->choice.setup->scaling;
      if (source->uci_OnPUSCH->choice.setup->betaOffsets)
        UPDATE_IE(target->uci_OnPUSCH->choice.setup->betaOffsets,
                  source->uci_OnPUSCH->choice.setup->betaOffsets,
                  struct NR_UCI_OnPUSCH__betaOffsets);
985 986 987 988
    }
  }
}

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
static void configure_csi_resourcemapping(NR_CSI_RS_ResourceMapping_t *target, NR_CSI_RS_ResourceMapping_t *source)
{
  if (target->frequencyDomainAllocation.present != source->frequencyDomainAllocation.present) {
    UPDATE_NP_IE(target->frequencyDomainAllocation,
                 source->frequencyDomainAllocation,
                 struct NR_CSI_RS_ResourceMapping__frequencyDomainAllocation);
  }
  else {
    switch (source->frequencyDomainAllocation.present) {
      case NR_CSI_RS_ResourceMapping__frequencyDomainAllocation_PR_row1:
        target->frequencyDomainAllocation.choice.row1.size = source->frequencyDomainAllocation.choice.row1.size;
        target->frequencyDomainAllocation.choice.row1.bits_unused = source->frequencyDomainAllocation.choice.row1.bits_unused;
        if (!target->frequencyDomainAllocation.choice.row1.buf)
          target->frequencyDomainAllocation.choice.row1.buf =
              calloc(target->frequencyDomainAllocation.choice.row1.size, sizeof(uint8_t));
        for (int i = 0; i < target->frequencyDomainAllocation.choice.row1.size; i++)
          target->frequencyDomainAllocation.choice.row1.buf[i] = source->frequencyDomainAllocation.choice.row1.buf[i];
        break;
      case NR_CSI_RS_ResourceMapping__frequencyDomainAllocation_PR_row2:
        target->frequencyDomainAllocation.choice.row2.size = source->frequencyDomainAllocation.choice.row2.size;
        target->frequencyDomainAllocation.choice.row2.bits_unused = source->frequencyDomainAllocation.choice.row2.bits_unused;
        if (!target->frequencyDomainAllocation.choice.row2.buf)
          target->frequencyDomainAllocation.choice.row2.buf =
              calloc(target->frequencyDomainAllocation.choice.row2.size, sizeof(uint8_t));
        for (int i = 0; i < target->frequencyDomainAllocation.choice.row2.size; i++)
          target->frequencyDomainAllocation.choice.row2.buf[i] = source->frequencyDomainAllocation.choice.row2.buf[i];
        break;
      case NR_CSI_RS_ResourceMapping__frequencyDomainAllocation_PR_row4:
        target->frequencyDomainAllocation.choice.row4.size = source->frequencyDomainAllocation.choice.row4.size;
        target->frequencyDomainAllocation.choice.row4.bits_unused = source->frequencyDomainAllocation.choice.row4.bits_unused;
        if (!target->frequencyDomainAllocation.choice.row4.buf)
          target->frequencyDomainAllocation.choice.row4.buf =
              calloc(target->frequencyDomainAllocation.choice.row4.size, sizeof(uint8_t));
        for (int i = 0; i < target->frequencyDomainAllocation.choice.row4.size; i++)
          target->frequencyDomainAllocation.choice.row4.buf[i] = source->frequencyDomainAllocation.choice.row4.buf[i];
        break;
      case NR_CSI_RS_ResourceMapping__frequencyDomainAllocation_PR_other:
        target->frequencyDomainAllocation.choice.other.size = source->frequencyDomainAllocation.choice.other.size;
        target->frequencyDomainAllocation.choice.other.bits_unused = source->frequencyDomainAllocation.choice.other.bits_unused;
        if (!target->frequencyDomainAllocation.choice.other.buf)
          target->frequencyDomainAllocation.choice.other.buf =
              calloc(target->frequencyDomainAllocation.choice.other.size, sizeof(uint8_t));
        for (int i = 0; i < target->frequencyDomainAllocation.choice.other.size; i++)
          target->frequencyDomainAllocation.choice.other.buf[i] = source->frequencyDomainAllocation.choice.other.buf[i];
        break;
      default:
        AssertFatal(false, "Invalid entry\n");
    }
  }
  target->nrofPorts = source->nrofPorts;
  target->firstOFDMSymbolInTimeDomain = source->firstOFDMSymbolInTimeDomain;
  UPDATE_IE(target->firstOFDMSymbolInTimeDomain2, source->firstOFDMSymbolInTimeDomain2, long);
  target->cdm_Type = source->cdm_Type;
  target->density = source->density;
  target->freqBand = source->freqBand;
}

static void config_zp_CSI_RS_Resource(NR_ZP_CSI_RS_Resource_t *target, NR_ZP_CSI_RS_Resource_t *source)
{
  target->zp_CSI_RS_ResourceId = source->zp_CSI_RS_ResourceId;
  configure_csi_resourcemapping(&target->resourceMapping, &source->resourceMapping);
  if (source->periodicityAndOffset)
    UPDATE_IE(target->periodicityAndOffset,
              source->periodicityAndOffset,
              NR_CSI_ResourcePeriodicityAndOffset_t);
}

1056
static void setup_pdschconfig(NR_PDSCH_Config_t *source, NR_PDSCH_Config_t *target)
1057
{
1058
  UPDATE_IE(target->dataScramblingIdentityPDSCH, source->dataScramblingIdentityPDSCH, long);
1059
  if (source->dmrs_DownlinkForPDSCH_MappingTypeA)
1060 1061 1062 1063
    HANDLE_SETUPRELEASE_IE(target->dmrs_DownlinkForPDSCH_MappingTypeA,
                           source->dmrs_DownlinkForPDSCH_MappingTypeA,
                           NR_DMRS_DownlinkConfig_t,
                           asn_DEF_NR_SetupRelease_DMRS_DownlinkConfig);
1064
  if (source->dmrs_DownlinkForPDSCH_MappingTypeB)
1065 1066 1067 1068
    HANDLE_SETUPRELEASE_IE(target->dmrs_DownlinkForPDSCH_MappingTypeB,
                           source->dmrs_DownlinkForPDSCH_MappingTypeB,
                           NR_DMRS_DownlinkConfig_t,
                           asn_DEF_NR_SetupRelease_DMRS_DownlinkConfig);
1069 1070
  // TCI States
  if (source->tci_StatesToReleaseList) {
1071 1072 1073
    RELEASE_IE_FROMLIST(source->tci_StatesToReleaseList,
                        target->tci_StatesToAddModList,
                        tci_StateId);
1074 1075 1076 1077
  }
  if (source->tci_StatesToAddModList) {
    if (!target->tci_StatesToAddModList)
      target->tci_StatesToAddModList = calloc(1, sizeof(*target->tci_StatesToAddModList));
1078 1079 1080 1081
    ADDMOD_IE_FROMLIST(source->tci_StatesToAddModList,
                       target->tci_StatesToAddModList,
                       tci_StateId,
                       NR_TCI_State_t);
1082 1083
  }
  // end TCI States
1084
  UPDATE_IE(target->vrb_ToPRB_Interleaver, source->vrb_ToPRB_Interleaver, long);
1085 1086
  target->resourceAllocation = source->resourceAllocation;
  if (source->pdsch_TimeDomainAllocationList)
1087 1088 1089 1090
    HANDLE_SETUPRELEASE_IE(target->pdsch_TimeDomainAllocationList,
                           source->pdsch_TimeDomainAllocationList,
                           NR_PDSCH_TimeDomainResourceAllocationList_t,
                           asn_DEF_NR_SetupRelease_PDSCH_TimeDomainResourceAllocationList);
1091
  UPDATE_IE(target->pdsch_AggregationFactor, source->pdsch_AggregationFactor, long);
1092 1093
  // rateMatchPattern
  if (source->rateMatchPatternToReleaseList) {
1094 1095 1096
    RELEASE_IE_FROMLIST(source->rateMatchPatternToReleaseList,
                        target->rateMatchPatternToAddModList,
                        rateMatchPatternId);
1097 1098 1099 1100
  }
  if (source->rateMatchPatternToAddModList) {
    if (!target->rateMatchPatternToAddModList)
      target->rateMatchPatternToAddModList = calloc(1, sizeof(*target->rateMatchPatternToAddModList));
1101 1102 1103 1104
    ADDMOD_IE_FROMLIST(source->rateMatchPatternToAddModList,
                       target->rateMatchPatternToAddModList,
                       rateMatchPatternId,
                       NR_RateMatchPattern_t);
1105 1106
  }
  // end rateMatchPattern
1107 1108
  UPDATE_IE(target->rateMatchPatternGroup1, source->rateMatchPatternGroup1, NR_RateMatchPatternGroup_t);
  UPDATE_IE(target->rateMatchPatternGroup2, source->rateMatchPatternGroup2, NR_RateMatchPatternGroup_t);
1109
  target->rbg_Size = source->rbg_Size;
1110 1111 1112
  UPDATE_IE(target->mcs_Table, source->mcs_Table, long);
  UPDATE_IE(target->maxNrofCodeWordsScheduledByDCI, source->maxNrofCodeWordsScheduledByDCI, long);
  UPDATE_NP_IE(target->prb_BundlingType, source->prb_BundlingType, struct NR_PDSCH_Config__prb_BundlingType);
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
  if (source->zp_CSI_RS_ResourceToAddModList) {
    if (!target->zp_CSI_RS_ResourceToAddModList)
      target->zp_CSI_RS_ResourceToAddModList = calloc(1, sizeof(*target->zp_CSI_RS_ResourceToAddModList));
    ADDMOD_IE_FROMLIST_WFUNCTION(source->zp_CSI_RS_ResourceToAddModList,
                                 target->zp_CSI_RS_ResourceToAddModList,
                                 zp_CSI_RS_ResourceId,
                                 NR_ZP_CSI_RS_Resource_t,
                                 config_zp_CSI_RS_Resource);
  }
  if (source->zp_CSI_RS_ResourceToReleaseList) {
    RELEASE_IE_FROMLIST(source->zp_CSI_RS_ResourceToReleaseList,
                        target->zp_CSI_RS_ResourceToAddModList,
                        zp_CSI_RS_ResourceId);
  }
  if (source->p_ZP_CSI_RS_ResourceSet)
    HANDLE_SETUPRELEASE_IE(target->p_ZP_CSI_RS_ResourceSet,
                           source->p_ZP_CSI_RS_ResourceSet,
                           NR_ZP_CSI_RS_ResourceSet_t,
                           asn_DEF_NR_ZP_CSI_RS_ResourceSet);
1132 1133
  AssertFatal(source->aperiodic_ZP_CSI_RS_ResourceSetsToAddModList == NULL, "Not handled\n");
  AssertFatal(source->sp_ZP_CSI_RS_ResourceSetsToAddModList == NULL, "Not handled\n");
1134 1135
}

1136
static void setup_sr_resource(NR_SchedulingRequestResourceConfig_t *target, NR_SchedulingRequestResourceConfig_t *source)
1137 1138 1139 1140
{
  target->schedulingRequestResourceId = source->schedulingRequestResourceId;
  target->schedulingRequestID = source->schedulingRequestID;
  if (source->periodicityAndOffset)
1141 1142 1143
    UPDATE_IE(target->periodicityAndOffset,
              source->periodicityAndOffset,
              struct NR_SchedulingRequestResourceConfig__periodicityAndOffset);
1144
  if (source->resource)
1145
    UPDATE_IE(target->resource, source->resource, NR_PUCCH_ResourceId_t);
1146 1147
}

1148
static void setup_pucchconfig(NR_PUCCH_Config_t *source, NR_PUCCH_Config_t *target)
1149 1150 1151 1152 1153
{
  // PUCCH-ResourceSet
  if (source->resourceSetToAddModList) {
    if (!target->resourceSetToAddModList)
      target->resourceSetToAddModList = calloc(1, sizeof(*target->resourceSetToAddModList));
1154 1155 1156 1157
    ADDMOD_IE_FROMLIST(source->resourceSetToAddModList,
                       target->resourceSetToAddModList,
                       pucch_ResourceSetId,
                       NR_PUCCH_ResourceSet_t);
1158 1159
  }
  if (source->resourceSetToReleaseList) {
1160 1161 1162
    RELEASE_IE_FROMLIST(source->resourceSetToReleaseList,
                        target->resourceSetToAddModList,
                        pucch_ResourceSetId);
1163 1164 1165 1166 1167
  }
  // PUCCH-Resource
  if (source->resourceToAddModList) {
    if (!target->resourceToAddModList)
      target->resourceToAddModList = calloc(1, sizeof(*target->resourceToAddModList));
1168 1169 1170 1171
    ADDMOD_IE_FROMLIST(source->resourceToAddModList,
                       target->resourceToAddModList,
                       pucch_ResourceId,
                       NR_PUCCH_Resource_t);
1172 1173
  }
  if (source->resourceToReleaseList) {
1174 1175 1176
    RELEASE_IE_FROMLIST(source->resourceToReleaseList,
                        target->resourceToAddModList,
                        pucch_ResourceId);
1177 1178 1179
  }
  // PUCCH-FormatConfig
  if (source->format1)
1180 1181 1182 1183
    HANDLE_SETUPRELEASE_IE(target->format1,
                           source->format1,
                           NR_PUCCH_FormatConfig_t,
                           asn_DEF_NR_SetupRelease_PUCCH_FormatConfig);
1184
  if (source->format2)
1185 1186 1187 1188
    HANDLE_SETUPRELEASE_IE(target->format2,
                           source->format2,
                           NR_PUCCH_FormatConfig_t,
                           asn_DEF_NR_SetupRelease_PUCCH_FormatConfig);
1189
  if (source->format3)
1190 1191 1192 1193
    HANDLE_SETUPRELEASE_IE(target->format3,
                           source->format3,
                           NR_PUCCH_FormatConfig_t,
                           asn_DEF_NR_SetupRelease_PUCCH_FormatConfig);
1194
  if (source->format4)
1195 1196 1197 1198
    HANDLE_SETUPRELEASE_IE(target->format4,
                           source->format4,
                           NR_PUCCH_FormatConfig_t,
                           asn_DEF_NR_SetupRelease_PUCCH_FormatConfig);
1199 1200 1201 1202
  // SchedulingRequestResourceConfig
  if (source->schedulingRequestResourceToAddModList) {
    if (!target->schedulingRequestResourceToAddModList)
      target->schedulingRequestResourceToAddModList = calloc(1, sizeof(*target->schedulingRequestResourceToAddModList));
1203 1204 1205 1206 1207
    ADDMOD_IE_FROMLIST_WFUNCTION(source->schedulingRequestResourceToAddModList,
                                 target->schedulingRequestResourceToAddModList,
                                 schedulingRequestResourceId,
                                 NR_SchedulingRequestResourceConfig_t,
                                 setup_sr_resource);
1208 1209
  }
  if (source->schedulingRequestResourceToReleaseList) {
1210 1211 1212
    RELEASE_IE_FROMLIST(source->schedulingRequestResourceToReleaseList,
                        target->schedulingRequestResourceToAddModList,
                        schedulingRequestResourceId);
1213 1214
  }

1215
  if (source->multi_CSI_PUCCH_ResourceList)
1216 1217 1218
    UPDATE_IE(target->multi_CSI_PUCCH_ResourceList,
              source->multi_CSI_PUCCH_ResourceList,
              struct NR_PUCCH_Config__multi_CSI_PUCCH_ResourceList);
1219
  if (source->dl_DataToUL_ACK)
1220
    UPDATE_IE(target->dl_DataToUL_ACK, source->dl_DataToUL_ACK, struct NR_PUCCH_Config__dl_DataToUL_ACK);
1221 1222 1223 1224
  // PUCCH-SpatialRelationInfo
  if (source->spatialRelationInfoToAddModList) {
    if (!target->spatialRelationInfoToAddModList)
      target->spatialRelationInfoToAddModList = calloc(1, sizeof(*target->spatialRelationInfoToAddModList));
1225 1226 1227 1228
    ADDMOD_IE_FROMLIST(source->spatialRelationInfoToAddModList,
                       target->spatialRelationInfoToAddModList,
                       pucch_SpatialRelationInfoId,
                       NR_PUCCH_SpatialRelationInfo_t);
1229 1230
  }
  if (source->spatialRelationInfoToReleaseList) {
1231 1232 1233
    RELEASE_IE_FROMLIST(source->spatialRelationInfoToReleaseList,
                        target->spatialRelationInfoToAddModList,
                        pucch_SpatialRelationInfoId);
1234 1235 1236 1237 1238
  }

  if (source->pucch_PowerControl) {
    if (!target->pucch_PowerControl)
      target->pucch_PowerControl = calloc(1, sizeof(*target->pucch_PowerControl));
1239 1240 1241 1242 1243
    UPDATE_IE(target->pucch_PowerControl->deltaF_PUCCH_f0, source->pucch_PowerControl->deltaF_PUCCH_f0, long);
    UPDATE_IE(target->pucch_PowerControl->deltaF_PUCCH_f1, source->pucch_PowerControl->deltaF_PUCCH_f1, long);
    UPDATE_IE(target->pucch_PowerControl->deltaF_PUCCH_f2, source->pucch_PowerControl->deltaF_PUCCH_f2, long);
    UPDATE_IE(target->pucch_PowerControl->deltaF_PUCCH_f3, source->pucch_PowerControl->deltaF_PUCCH_f3, long);
    UPDATE_IE(target->pucch_PowerControl->deltaF_PUCCH_f4, source->pucch_PowerControl->deltaF_PUCCH_f4, long);
1244
    if (source->pucch_PowerControl->p0_Set)
1245
      UPDATE_IE(target->pucch_PowerControl->p0_Set, source->pucch_PowerControl->p0_Set, struct NR_PUCCH_PowerControl__p0_Set);
1246
    if (source->pucch_PowerControl->pathlossReferenceRSs)
1247 1248 1249 1250 1251 1252
      UPDATE_IE(target->pucch_PowerControl->pathlossReferenceRSs,
                source->pucch_PowerControl->pathlossReferenceRSs,
                struct NR_PUCCH_PowerControl__pathlossReferenceRSs);
    UPDATE_IE(target->pucch_PowerControl->twoPUCCH_PC_AdjustmentStates,
              source->pucch_PowerControl->twoPUCCH_PC_AdjustmentStates,
              long);
1253 1254 1255
  }
}

1256 1257 1258 1259 1260
static void handle_aperiodic_srs_type(struct NR_SRS_ResourceSet__resourceType__aperiodic *source,
                                      struct NR_SRS_ResourceSet__resourceType__aperiodic *target)
{
  target->aperiodicSRS_ResourceTrigger = source->aperiodicSRS_ResourceTrigger;
  if (source->csi_RS)
1261 1262
    UPDATE_IE(target->csi_RS, source->csi_RS, NR_NZP_CSI_RS_ResourceId_t);
  UPDATE_IE(target->slotOffset, source->slotOffset, long);
1263
  if (source->ext1 && source->ext1->aperiodicSRS_ResourceTriggerList)
1264 1265 1266
    UPDATE_IE(target->ext1->aperiodicSRS_ResourceTriggerList,
              source->ext1->aperiodicSRS_ResourceTriggerList,
              struct NR_SRS_ResourceSet__resourceType__aperiodic__ext1__aperiodicSRS_ResourceTriggerList);
1267 1268
}

1269
static void setup_srsresourceset(NR_SRS_ResourceSet_t *target, NR_SRS_ResourceSet_t *source)
1270 1271 1272
{
  target->srs_ResourceSetId = source->srs_ResourceSetId;
  if (source->srs_ResourceIdList)
1273
    UPDATE_IE(target->srs_ResourceIdList, source->srs_ResourceIdList, struct NR_SRS_ResourceSet__srs_ResourceIdList);
1274 1275

  if (target->resourceType.present != source->resourceType.present) {
1276
    UPDATE_NP_IE(target->resourceType, source->resourceType, struct NR_SRS_ResourceSet__resourceType);
1277 1278 1279 1280 1281 1282 1283 1284
  }
  else {
    switch (source->resourceType.present) {
      case NR_SRS_ResourceSet__resourceType_PR_aperiodic:
        handle_aperiodic_srs_type(source->resourceType.choice.aperiodic, target->resourceType.choice.aperiodic);
        break;
      case NR_SRS_ResourceSet__resourceType_PR_periodic:
        if (source->resourceType.choice.periodic->associatedCSI_RS)
1285 1286 1287
          UPDATE_IE(target->resourceType.choice.periodic->associatedCSI_RS,
                    source->resourceType.choice.periodic->associatedCSI_RS,
                    NR_NZP_CSI_RS_ResourceId_t);
1288 1289 1290
        break;
      case NR_SRS_ResourceSet__resourceType_PR_semi_persistent:
        if (source->resourceType.choice.semi_persistent->associatedCSI_RS)
1291 1292 1293
          UPDATE_IE(target->resourceType.choice.semi_persistent->associatedCSI_RS,
                    source->resourceType.choice.semi_persistent->associatedCSI_RS,
                    NR_NZP_CSI_RS_ResourceId_t);
1294 1295 1296 1297
        break;
      default:
        break;
    }
1298
  }
1299
  target->usage = source->usage;
1300
  UPDATE_IE(target->alpha, source->alpha, NR_Alpha_t);
1301
  if (source->p0)
1302
    UPDATE_IE(target->p0, source->p0, long);
1303
  if (source->pathlossReferenceRS)
1304 1305
    UPDATE_IE(target->pathlossReferenceRS, source->pathlossReferenceRS, struct NR_PathlossReferenceRS_Config);
  UPDATE_IE(target->srs_PowerControlAdjustmentStates, source->srs_PowerControlAdjustmentStates, long);
1306 1307
}

1308
static void setup_srsconfig(NR_SRS_Config_t *source, NR_SRS_Config_t *target)
1309
{
1310
  UPDATE_IE(target->tpc_Accumulation, source->tpc_Accumulation, long);
1311 1312 1313 1314
  // SRS-Resource
  if (source->srs_ResourceToAddModList) {
    if (!target->srs_ResourceToAddModList)
      target->srs_ResourceToAddModList = calloc(1, sizeof(*target->srs_ResourceToAddModList));
1315 1316 1317 1318
    ADDMOD_IE_FROMLIST(source->srs_ResourceToAddModList,
                       target->srs_ResourceToAddModList,
                       srs_ResourceId,
                       NR_SRS_Resource_t);
1319 1320
  }
  if (source->srs_ResourceToReleaseList) {
1321 1322 1323
    RELEASE_IE_FROMLIST(source->srs_ResourceToReleaseList,
                        target->srs_ResourceToAddModList,
                        srs_ResourceId);
1324 1325 1326 1327 1328
  }
  // SRS-ResourceSet
  if (source->srs_ResourceSetToAddModList) {
    if (!target->srs_ResourceSetToAddModList)
      target->srs_ResourceSetToAddModList = calloc(1, sizeof(*target->srs_ResourceSetToAddModList));
1329 1330 1331 1332 1333
    ADDMOD_IE_FROMLIST_WFUNCTION(source->srs_ResourceSetToAddModList,
                                 target->srs_ResourceSetToAddModList,
                                 srs_ResourceSetId,
                                 NR_SRS_ResourceSet_t,
                                 setup_srsresourceset);
1334 1335
  }
  if (source->srs_ResourceSetToReleaseList) {
1336 1337 1338
    RELEASE_IE_FROMLIST(source->srs_ResourceSetToReleaseList,
                        target->srs_ResourceSetToAddModList,
                        srs_ResourceSetId);
1339 1340 1341
  }
}

1342
static NR_UE_DL_BWP_t *get_dl_bwp_structure(NR_UE_MAC_INST_t *mac, int bwp_id, bool setup)
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
{
  NR_UE_DL_BWP_t *bwp = NULL;
  for (int i = 0; i < mac->dl_BWPs.count; i++) {
    if (bwp_id == mac->dl_BWPs.array[i]->bwp_id) {
      bwp = mac->dl_BWPs.array[i];
      break;
    }
  }
  if (!bwp && setup) {
    bwp = calloc(1, sizeof(*bwp));
    ASN_SEQUENCE_ADD(&mac->dl_BWPs, bwp);
  }
  if (!setup) {
1356 1357
    mac->sc_info.n_dl_bwp = mac->dl_BWPs.count - 1;
    mac->sc_info.dl_bw_tbslbrm = 0;
1358
    for (int i = 0; i < mac->dl_BWPs.count; i++) {
1359 1360
      if (mac->dl_BWPs.array[i]->BWPSize > mac->sc_info.dl_bw_tbslbrm)
        mac->sc_info.dl_bw_tbslbrm = mac->dl_BWPs.array[i]->BWPSize;
1361 1362 1363 1364 1365
    }
  }
  return bwp;
}

1366
static NR_UE_UL_BWP_t *get_ul_bwp_structure(NR_UE_MAC_INST_t *mac, int bwp_id, bool setup)
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
{
  NR_UE_UL_BWP_t *bwp = NULL;
  for (int i = 0; i < mac->ul_BWPs.count; i++) {
    if (bwp_id == mac->ul_BWPs.array[i]->bwp_id) {
      bwp = mac->ul_BWPs.array[i];
      break;
    }
  }
  if (!bwp && setup) {
    bwp = calloc(1, sizeof(*bwp));
    ASN_SEQUENCE_ADD(&mac->ul_BWPs, bwp);
  }
  if (!setup) {
1380 1381
    mac->sc_info.n_ul_bwp = mac->ul_BWPs.count - 1;
    mac->sc_info.ul_bw_tbslbrm = 0;
1382
    for (int i = 0; i < mac->ul_BWPs.count; i++) {
1383 1384
      if (mac->ul_BWPs.array[i]->BWPSize > mac->sc_info.ul_bw_tbslbrm)
        mac->sc_info.ul_bw_tbslbrm = mac->ul_BWPs.array[i]->BWPSize;
1385 1386 1387 1388 1389
    }
  }
  return bwp;
}

1390
static void configure_dedicated_BWP_dl(NR_UE_MAC_INST_t *mac, int bwp_id, NR_BWP_DownlinkDedicated_t *dl_dedicated)
1391
{
1392
  if (dl_dedicated) {
1393 1394 1395
    NR_UE_DL_BWP_t *bwp = get_dl_bwp_structure(mac, bwp_id, true);
    bwp->bwp_id = bwp_id;
    NR_BWP_PDCCH_t *pdcch = &mac->config_BWP_PDCCH[bwp_id];
1396 1397 1398
    if(dl_dedicated->pdsch_Config) {
      if (dl_dedicated->pdsch_Config->present == NR_SetupRelease_PDSCH_Config_PR_release)
        asn1cFreeStruc(asn_DEF_NR_PDSCH_Config, bwp->pdsch_Config);
1399
      if (dl_dedicated->pdsch_Config->present == NR_SetupRelease_PDSCH_Config_PR_setup) {
1400 1401 1402 1403 1404
        if (!bwp->pdsch_Config)
          bwp->pdsch_Config = calloc(1, sizeof(*bwp->pdsch_Config));
        setup_pdschconfig(dl_dedicated->pdsch_Config->choice.setup, bwp->pdsch_Config);
      }
    }
1405 1406
    if (dl_dedicated->pdcch_Config) {
      if (dl_dedicated->pdcch_Config->present == NR_SetupRelease_PDCCH_Config_PR_release) {
1407 1408 1409 1410
        for (int i = pdcch->list_Coreset.count; i > 0 ; i--)
          asn_sequence_del(&pdcch->list_Coreset, i - 1, 1);
        for (int i = pdcch->list_SS.count; i > 0 ; i--)
          asn_sequence_del(&pdcch->list_SS, i - 1, 1);
1411
      }
1412 1413
      if (dl_dedicated->pdcch_Config->present == NR_SetupRelease_PDCCH_Config_PR_setup)
        configure_ss_coreset(pdcch, dl_dedicated->pdcch_Config->choice.setup);
1414
    }
1415
    AssertFatal(!dl_dedicated->sps_Config, "SPS handling not implemented\n");
1416 1417 1418
  }
}

1419
static void configure_dedicated_BWP_ul(NR_UE_MAC_INST_t *mac, int bwp_id, NR_BWP_UplinkDedicated_t *ul_dedicated)
1420
{
1421
  if (ul_dedicated) {
1422 1423
    NR_UE_UL_BWP_t *bwp = get_ul_bwp_structure(mac, bwp_id, true);
    bwp->bwp_id = bwp_id;
1424 1425 1426
    if(ul_dedicated->pucch_Config) {
      if (ul_dedicated->pucch_Config->present == NR_SetupRelease_PUCCH_Config_PR_release)
        asn1cFreeStruc(asn_DEF_NR_PUCCH_Config, bwp->pucch_Config);
1427
      if (ul_dedicated->pucch_Config->present == NR_SetupRelease_PUCCH_Config_PR_setup) {
1428 1429 1430 1431 1432
        if (!bwp->pucch_Config)
          bwp->pucch_Config = calloc(1, sizeof(*bwp->pucch_Config));
        setup_pucchconfig(ul_dedicated->pucch_Config->choice.setup, bwp->pucch_Config);
      }
    }
1433 1434 1435
    if(ul_dedicated->pusch_Config) {
      if (ul_dedicated->pusch_Config->present == NR_SetupRelease_PUSCH_Config_PR_release)
        asn1cFreeStruc(asn_DEF_NR_PUSCH_Config, bwp->pusch_Config);
1436
      if (ul_dedicated->pusch_Config->present == NR_SetupRelease_PUSCH_Config_PR_setup) {
1437 1438
        if (!bwp->pusch_Config)
          bwp->pusch_Config = calloc(1, sizeof(*bwp->pusch_Config));
1439
        setup_puschconfig(mac, ul_dedicated->pusch_Config->choice.setup, bwp->pusch_Config);
1440 1441
      }
    }
1442 1443 1444
    if(ul_dedicated->srs_Config) {
      if (ul_dedicated->srs_Config->present == NR_SetupRelease_SRS_Config_PR_release)
        asn1cFreeStruc(asn_DEF_NR_SRS_Config, bwp->srs_Config);
1445
      if (ul_dedicated->srs_Config->present == NR_SetupRelease_SRS_Config_PR_setup) {
1446 1447 1448 1449 1450 1451 1452 1453 1454
        if (!bwp->srs_Config)
          bwp->srs_Config = calloc(1, sizeof(*bwp->srs_Config));
        setup_srsconfig(ul_dedicated->srs_Config->choice.setup, bwp->srs_Config);
      }
    }
    AssertFatal(!ul_dedicated->configuredGrantConfig, "configuredGrantConfig not supported\n");
  }
}

1455
static void configure_common_BWP_dl(NR_UE_MAC_INST_t *mac, int bwp_id, NR_BWP_DownlinkCommon_t *dl_common)
1456
{
1457
  if (dl_common) {
1458 1459 1460 1461 1462 1463 1464 1465
    NR_UE_DL_BWP_t *bwp = get_dl_bwp_structure(mac, bwp_id, true);
    bwp->bwp_id = bwp_id;
    NR_BWP_t *dl_genericParameters = &dl_common->genericParameters;
    bwp->scs = dl_genericParameters->subcarrierSpacing;
    bwp->cyclicprefix = dl_genericParameters->cyclicPrefix;
    bwp->BWPSize = NRRIV2BW(dl_genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
    bwp->BWPStart = NRRIV2PRBOFFSET(dl_genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
    if (bwp_id == 0) {
1466 1467
      mac->sc_info.initial_dl_BWPSize = bwp->BWPSize;
      mac->sc_info.initial_dl_BWPStart = bwp->BWPStart;
1468 1469
    }
    if (dl_common->pdsch_ConfigCommon) {
1470
      if (dl_common->pdsch_ConfigCommon->present == NR_SetupRelease_PDSCH_ConfigCommon_PR_setup)
1471 1472 1473
        UPDATE_IE(bwp->tdaList_Common,
                  dl_common->pdsch_ConfigCommon->choice.setup->pdsch_TimeDomainAllocationList,
                  NR_PDSCH_TimeDomainResourceAllocationList_t);
1474 1475
      if (dl_common->pdsch_ConfigCommon->present == NR_SetupRelease_PDSCH_ConfigCommon_PR_release)
        asn1cFreeStruc(asn_DEF_NR_PDSCH_TimeDomainResourceAllocationList, bwp->tdaList_Common);
1476 1477 1478
    }
    NR_BWP_PDCCH_t *pdcch = &mac->config_BWP_PDCCH[bwp_id];
    if (dl_common->pdcch_ConfigCommon) {
1479
      if (dl_common->pdcch_ConfigCommon->present == NR_SetupRelease_PDCCH_ConfigCommon_PR_setup)
1480
        configure_common_ss_coreset(mac, pdcch, dl_common->pdcch_ConfigCommon->choice.setup);
1481
      if (dl_common->pdcch_ConfigCommon->present == NR_SetupRelease_PDCCH_ConfigCommon_PR_release)
1482 1483 1484 1485 1486
        release_common_ss_cset(pdcch);
    }
  }
}

1487
static void configure_common_BWP_ul(NR_UE_MAC_INST_t *mac, int bwp_id, NR_BWP_UplinkCommon_t *ul_common)
1488 1489 1490 1491 1492 1493 1494 1495 1496
{
  if (ul_common) {
    NR_UE_UL_BWP_t *bwp = get_ul_bwp_structure(mac, bwp_id, true);
    bwp->bwp_id = bwp_id;
    NR_BWP_t *ul_genericParameters = &ul_common->genericParameters;
    bwp->scs = ul_genericParameters->subcarrierSpacing;
    bwp->cyclicprefix = ul_genericParameters->cyclicPrefix;
    bwp->BWPSize = NRRIV2BW(ul_genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
    bwp->BWPStart = NRRIV2PRBOFFSET(ul_genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
1497 1498 1499 1500 1501
    // For power calculations assume the UE channel is the smallest channel that can support the BWP
    int bw_index = get_smallest_supported_bandwidth_index(bwp->scs, mac->frequency_range, bwp->BWPSize);
    bwp->channel_bandwidth = get_supported_bw_mhz(mac->frequency_range, bw_index);
    // Minumum transmission power depends on bandwidth, precalculate it here
    bwp->P_CMIN = nr_get_Pcmin(bw_index);
1502
    if (bwp_id == 0) {
1503 1504
      mac->sc_info.initial_ul_BWPSize = bwp->BWPSize;
      mac->sc_info.initial_ul_BWPStart = bwp->BWPStart;
1505 1506
    }
    if (ul_common->rach_ConfigCommon) {
1507 1508 1509 1510
      HANDLE_SETUPRELEASE_DIRECT(bwp->rach_ConfigCommon,
                                 ul_common->rach_ConfigCommon,
                                 NR_RACH_ConfigCommon_t,
                                 asn_DEF_NR_RACH_ConfigCommon);
1511 1512
    }
    if (ul_common->pucch_ConfigCommon)
1513 1514 1515 1516
      HANDLE_SETUPRELEASE_DIRECT(bwp->pucch_ConfigCommon,
                                 ul_common->pucch_ConfigCommon,
                                 NR_PUCCH_ConfigCommon_t,
                                 asn_DEF_NR_PUCCH_ConfigCommon);
1517
    if (ul_common->pusch_ConfigCommon) {
1518
      if (ul_common->pusch_ConfigCommon->present == NR_SetupRelease_PUSCH_ConfigCommon_PR_setup) {
1519 1520 1521 1522
        UPDATE_IE(bwp->tdaList_Common,
                  ul_common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList,
                  NR_PUSCH_TimeDomainResourceAllocationList_t);
        UPDATE_IE(bwp->msg3_DeltaPreamble, ul_common->pusch_ConfigCommon->choice.setup->msg3_DeltaPreamble, long);
1523
        UPDATE_IE(bwp->p0_NominalWithGrant, ul_common->pusch_ConfigCommon->choice.setup->p0_NominalWithGrant, long);
1524 1525
      }
      if (ul_common->pusch_ConfigCommon->present == NR_SetupRelease_PUSCH_ConfigCommon_PR_release) {
1526
        asn1cFreeStruc(asn_DEF_NR_PUSCH_TimeDomainResourceAllocationList, bwp->tdaList_Common);
1527 1528
        free(bwp->msg3_DeltaPreamble);
        bwp->msg3_DeltaPreamble = NULL;
1529 1530
        free(bwp->p0_NominalWithGrant);
        bwp->p0_NominalWithGrant = NULL;
1531 1532 1533 1534 1535
      }
    }
  }
}

1536
void nr_rrc_mac_config_req_reset(module_id_t module_id,
francescomani's avatar
francescomani committed
1537
                                 NR_UE_MAC_reset_cause_t cause)
francescomani's avatar
francescomani committed
1538 1539
{
  NR_UE_MAC_INST_t *mac = get_mac_inst(module_id);
1540
  fapi_nr_synch_request_t sync_req = {.target_Nid_cell = -1, .ssb_bw_scan = true};
francescomani's avatar
francescomani committed
1541 1542
  switch (cause) {
    case GO_TO_IDLE:
1543
      reset_ra(mac, true);
francescomani's avatar
francescomani committed
1544 1545 1546 1547
      release_mac_configuration(mac, cause);
      nr_ue_init_mac(mac);
      nr_ue_mac_default_configs(mac);
      // new sync but no target cell id -> -1
1548
      nr_ue_send_synch_request(mac, module_id, 0, &sync_req);
francescomani's avatar
francescomani committed
1549 1550
      break;
    case DETACH:
francescomani's avatar
francescomani committed
1551
      LOG_A(NR_MAC, "Received detach indication\n");
1552
      reset_ra(mac, true);
francescomani's avatar
francescomani committed
1553 1554 1555
      reset_mac_inst(mac);
      nr_ue_reset_sync_state(mac);
      release_mac_configuration(mac, cause);
1556
      mac->state = UE_DETACHING;
francescomani's avatar
francescomani committed
1557 1558
      break;
    case T300_EXPIRY:
1559
      reset_ra(mac, false);
francescomani's avatar
francescomani committed
1560 1561 1562 1563 1564 1565 1566 1567 1568
      reset_mac_inst(mac);
      mac->state = UE_SYNC; // still in sync but need to restart RA
      break;
    case RE_ESTABLISHMENT:
      reset_mac_inst(mac);
      nr_ue_mac_default_configs(mac);
      nr_ue_reset_sync_state(mac);
      release_mac_configuration(mac, cause);
      // new sync with old cell ID (re-establishment on the same cell)
1569 1570 1571
      sync_req.target_Nid_cell = mac->physCellId;
      sync_req.ssb_bw_scan = false;
      nr_ue_send_synch_request(mac, module_id, 0, &sync_req);
francescomani's avatar
francescomani committed
1572 1573 1574
      break;
    default:
      AssertFatal(false, "Invalid MAC reset cause %d\n", cause);
1575
  }
francescomani's avatar
francescomani committed
1576 1577
}

1578 1579
void nr_rrc_mac_config_req_sib1(module_id_t module_id,
                                int cc_idP,
1580
                                NR_SI_SchedulingInfo_t *si_SchedulingInfo,
1581 1582 1583 1584
                                NR_ServingCellConfigCommonSIB_t *scc)
{
  NR_UE_MAC_INST_t *mac = get_mac_inst(module_id);
  AssertFatal(scc, "SIB1 SCC should not be NULL\n");
1585

1586 1587
  UPDATE_IE(mac->tdd_UL_DL_ConfigurationCommon, scc->tdd_UL_DL_ConfigurationCommon, NR_TDD_UL_DL_ConfigCommon_t);
  UPDATE_IE(mac->si_SchedulingInfo, si_SchedulingInfo, NR_SI_SchedulingInfo_t);
1588

1589
  config_common_ue_sa(mac, scc, cc_idP);
1590 1591 1592 1593 1594 1595 1596 1597 1598
  configure_common_BWP_dl(mac,
                          0, // bwp-id
                          &scc->downlinkConfigCommon.initialDownlinkBWP);
  if (scc->uplinkConfigCommon)
    configure_common_BWP_ul(mac,
                            0, // bwp-id
                            &scc->uplinkConfigCommon->initialUplinkBWP);
  // set current BWP only if coming from non-connected state
  // otherwise it is just a periodically update of the SIB1 content
1599
  if (mac->state < UE_CONNECTED) {
1600 1601 1602 1603 1604 1605 1606 1607
    mac->current_DL_BWP = get_dl_bwp_structure(mac, 0, false);
    AssertFatal(mac->current_DL_BWP, "Couldn't find DL-BWP0\n");
    mac->current_UL_BWP = get_ul_bwp_structure(mac, 0, false);
    AssertFatal(mac->current_UL_BWP, "Couldn't find DL-BWP0\n");
  }

  // Setup the SSB to Rach Occasions mapping according to the config
  build_ssb_to_ro_map(mac);
francescomani's avatar
francescomani committed
1608

1609 1610 1611 1612
  if (!get_softmodem_params()->emulate_l1)
    mac->if_module->phy_config_request(&mac->phy_config);
  mac->phy_config_request_sent = true;
}
francescomani's avatar
francescomani committed
1613

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
void nr_rrc_mac_config_req_sib19_r17(module_id_t module_id,
                                     NR_SIB19_r17_t *sib19_r17)
{
  NR_UE_MAC_INST_t *mac = get_mac_inst(module_id);

  // ntn-Config-r17
  UPDATE_IE(mac->sc_info.ntn_Config_r17, sib19_r17->ntn_Config_r17, NR_NTN_Config_r17_t);

  // TODO handle other SIB19 elements
}

1625 1626 1627
static void handle_reconfiguration_with_sync(NR_UE_MAC_INST_t *mac,
                                             int cc_idP,
                                             const NR_ReconfigurationWithSync_t *reconfigurationWithSync)
1628
{
1629 1630 1631
  mac->crnti = reconfigurationWithSync->newUE_Identity;
  LOG_I(NR_MAC, "Configuring CRNTI %x\n", mac->crnti);

1632 1633
  RA_config_t *ra = &mac->ra;
  if (reconfigurationWithSync->rach_ConfigDedicated) {
1634 1635 1636
    AssertFatal(
        reconfigurationWithSync->rach_ConfigDedicated->present == NR_ReconfigurationWithSync__rach_ConfigDedicated_PR_uplink,
        "RACH on supplementaryUplink not supported\n");
1637
    UPDATE_IE(ra->rach_ConfigDedicated, reconfigurationWithSync->rach_ConfigDedicated->choice.uplink, NR_RACH_ConfigDedicated_t);
1638
  }
1639

1640 1641
  if (reconfigurationWithSync->spCellConfigCommon) {
    NR_ServingCellConfigCommon_t *scc = reconfigurationWithSync->spCellConfigCommon;
1642 1643 1644
    if (scc->physCellId)
      mac->physCellId = *scc->physCellId;
    mac->dmrs_TypeA_Position = scc->dmrs_TypeA_Position;
1645
    UPDATE_IE(mac->tdd_UL_DL_ConfigurationCommon, scc->tdd_UL_DL_ConfigurationCommon, NR_TDD_UL_DL_ConfigCommon_t);
1646
    config_common_ue(mac, scc, cc_idP);
1647 1648 1649 1650 1651 1652 1653 1654
    if (scc->downlinkConfigCommon)
      configure_common_BWP_dl(mac,
                              0, // bwp-id
                              scc->downlinkConfigCommon->initialDownlinkBWP);
    if (scc->uplinkConfigCommon)
      configure_common_BWP_ul(mac,
                              0, // bwp-id
                              scc->uplinkConfigCommon->initialUplinkBWP);
1655
  }
1656 1657

  mac->state = UE_NOT_SYNC;
1658
  ra->ra_state = nrRA_UE_IDLE;
1659 1660 1661
  nr_ue_mac_default_configs(mac);

  if (!get_softmodem_params()->emulate_l1) {
1662
    mac->synch_request.Mod_id = mac->ue_id;
1663 1664 1665 1666 1667 1668
    mac->synch_request.CC_id = cc_idP;
    mac->synch_request.synch_req.target_Nid_cell = mac->physCellId;
    mac->if_module->synch_request(&mac->synch_request);
    mac->if_module->phy_config_request(&mac->phy_config);
    mac->phy_config_request_sent = true;
  }
1669 1670
}

1671 1672
static void configure_physicalcellgroup(NR_UE_MAC_INST_t *mac,
                                        const NR_PhysicalCellGroupConfig_t *phyConfig)
1673 1674 1675 1676
{
  mac->pdsch_HARQ_ACK_Codebook = phyConfig->pdsch_HARQ_ACK_Codebook;
  mac->harq_ACK_SpatialBundlingPUCCH = phyConfig->harq_ACK_SpatialBundlingPUCCH ? true : false;
  mac->harq_ACK_SpatialBundlingPUSCH = phyConfig->harq_ACK_SpatialBundlingPUSCH ? true : false;
1677
  AssertFatal(!phyConfig->ext1 || !phyConfig->ext1->mcs_C_RNTI, "Handling of mcs-C-RNTI not implemented\n");
1678
  NR_P_Max_t *p_NR_FR1 = phyConfig->p_NR_FR1;
1679
  NR_P_Max_t *p_UE_FR1 = phyConfig->ext1 ? phyConfig->ext1->p_UE_FR1 : NULL;
1680 1681 1682
  if (p_NR_FR1 == NULL)
    mac->p_Max_alt = p_UE_FR1 == NULL ? INT_MIN : *p_UE_FR1;
  else
1683
    mac->p_Max_alt = p_UE_FR1 == NULL ? *p_NR_FR1 : (*p_UE_FR1 < *p_NR_FR1 ? *p_UE_FR1 : *p_NR_FR1);
1684 1685
}

1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
static uint32_t get_sr_DelayTimer(long logicalChannelSR_DelayTimer)
{
  uint32_t timer = 0;
  switch (logicalChannelSR_DelayTimer) {
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf20 :
      timer = 20;
      break;
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf40 :
      timer = 40;
      break;
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf64 :
      timer = 64;
      break;
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf128 :
      timer = 128;
      break;
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf512 :
      timer = 512;
      break;
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf1024 :
      timer = 1024;
      break;
    case NR_BSR_Config__logicalChannelSR_DelayTimer_sf2560 :
      timer = 2560;
      break;
    default :
      AssertFatal(false, "Invalid SR_DelayTimer %ld\n", logicalChannelSR_DelayTimer);
  }
  return timer;
}

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
static uint32_t nr_get_sf_retxBSRTimer(long retxBSR_Timer)
{
  uint32_t timer = 0;
  switch (retxBSR_Timer) {
    case NR_BSR_Config__retxBSR_Timer_sf10:
      timer = 10;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf20:
      timer = 20;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf40:
      timer = 40;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf80:
      timer = 80;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf160:
      timer = 160;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf320:
      timer = 320;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf640:
      timer = 640;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf1280:
      timer = 1280;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf2560:
      timer = 2560;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf5120:
      timer = 5120;
      break;
    case NR_BSR_Config__retxBSR_Timer_sf10240:
      timer = 10240;
      break;
    default:
      AssertFatal(false, "Invalid retxBSR_Timer %ld\n", retxBSR_Timer);
  }
  return timer;
}

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
static uint32_t nr_get_sf_periodicBSRTimer(long periodicBSR)
{
  uint32_t timer = 0;
  switch (periodicBSR) {
    case NR_BSR_Config__periodicBSR_Timer_sf1:
      timer = 1;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf5:
      timer = 5;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf10:
      timer = 10;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf16:
      timer = 16;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf20:
      timer = 20;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf32:
      timer = 32;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf40:
      timer = 40;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf64:
      timer = 64;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf80:
      timer = 80;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf128:
      timer = 128;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf160:
      timer = 160;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf320:
      timer = 320;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf640:
      timer = 640;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf1280:
      timer = 1280;
      break;
    case NR_BSR_Config__periodicBSR_Timer_sf2560:
      timer = 2560;
      break;
    case NR_BSR_Config__periodicBSR_Timer_infinity:
      timer = UINT_MAX;
    default:
      AssertFatal(false, "Invalid periodicBSR_Timer %ld\n", periodicBSR);
  }
  return timer;
}
1816

1817
static void configure_maccellgroup(NR_UE_MAC_INST_t *mac, const NR_MAC_CellGroupConfig_t *mcg)
1818 1819
{
  NR_UE_SCHEDULING_INFO *si = &mac->scheduling_info;
1820
  int scs = mac->current_UL_BWP->scs;
1821 1822 1823 1824 1825 1826
  if (mcg->drx_Config)
    LOG_E(NR_MAC, "DRX not implemented! Configuration not handled!\n");
  if (mcg->schedulingRequestConfig) {
    const NR_SchedulingRequestConfig_t *src = mcg->schedulingRequestConfig;
    if (src->schedulingRequestToReleaseList) {
      for (int i = 0; i < src->schedulingRequestToReleaseList->list.count; i++) {
1827 1828
        NR_SchedulingRequestId_t id = *src->schedulingRequestToReleaseList->list.array[i];
        memset(&si->sr_info[id], 0, sizeof(si->sr_info[id]));
1829 1830 1831 1832 1833
      }
    }
    if (src->schedulingRequestToAddModList) {
      for (int i = 0; i < src->schedulingRequestToAddModList->list.count; i++) {
        NR_SchedulingRequestToAddMod_t *sr = src->schedulingRequestToAddModList->list.array[i];
1834 1835
        nr_sr_info_t *sr_info = &si->sr_info[sr->schedulingRequestId];
        sr_info->active_SR_ID = true;
1836 1837
        // NR_SchedulingRequestToAddMod__sr_TransMax_n4	= 0 and so on
        // to obtain the value to configure we need to right shift 4 by the RRC parameter
1838
        sr_info->maxTransmissions = 4 << sr->sr_TransMax;
1839
        int target_ms = 0;
1840
        if (sr->sr_ProhibitTimer)
1841
          target_ms = 1 << *sr->sr_ProhibitTimer;
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
        if (mcg->ext4 && mcg->ext4->schedulingRequestConfig_v1700) {
          const NR_SchedulingRequestConfig_v1700_t *src_v1700 = mcg->ext4->schedulingRequestConfig_v1700;
          if (src_v1700->schedulingRequestToAddModListExt_v1700) {
            if (i < src_v1700->schedulingRequestToAddModListExt_v1700->list.count) {
              const NR_SchedulingRequestToAddModExt_v1700_t *sr_v1700 = src_v1700->schedulingRequestToAddModListExt_v1700->list.array[i];
              if (sr_v1700->sr_ProhibitTimer_v1700) {
                target_ms = 192 + 64 * *sr_v1700->sr_ProhibitTimer_v1700;
              }
            }
          }
        }
1853
        // length of slot is (1/2^scs)ms
1854
        nr_timer_setup(&sr_info->prohibitTimer, target_ms << scs, 1); // 1 slot update rate
1855 1856 1857 1858
      }
    }
  }
  if (mcg->bsr_Config) {
1859
    int subframes_per_slot = nr_slots_per_frame[scs] / 10;
1860 1861 1862 1863
    uint32_t periodic_sf = nr_get_sf_periodicBSRTimer(mcg->bsr_Config->periodicBSR_Timer);
    uint32_t target = periodic_sf < UINT_MAX ? periodic_sf * subframes_per_slot : periodic_sf;
    nr_timer_setup(&si->periodicBSR_Timer, target, 1); // 1 slot update rate
    nr_timer_start(&si->periodicBSR_Timer);
1864 1865
    uint32_t retx_sf = nr_get_sf_retxBSRTimer(mcg->bsr_Config->retxBSR_Timer);
    nr_timer_setup(&si->retxBSR_Timer, retx_sf * subframes_per_slot, 1); // 1 slot update rate
1866
    if (mcg->bsr_Config->logicalChannelSR_DelayTimer) {
1867 1868
      uint32_t dt_sf = get_sr_DelayTimer(*mcg->bsr_Config->logicalChannelSR_DelayTimer);
      nr_timer_setup(&si->sr_DelayTimer, dt_sf * subframes_per_slot, 1); // 1 slot update rate
1869
    }
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
  }
  if (mcg->tag_Config) {
    // TODO TAG not handled
    if(mcg->tag_Config->tag_ToAddModList) {
      for (int i = 0; i < mcg->tag_Config->tag_ToAddModList->list.count; i++) {
        if (mcg->tag_Config->tag_ToAddModList->list.array[i]->timeAlignmentTimer !=
            NR_TimeAlignmentTimer_infinity)
          LOG_E(NR_MAC, "TimeAlignmentTimer not handled\n");
      }
    }
  }
  if (mcg->phr_Config) {
    // TODO configuration when PHR is implemented
  }
}

1886 1887 1888 1889
static void configure_csirs_resource(NR_NZP_CSI_RS_Resource_t *target, NR_NZP_CSI_RS_Resource_t *source)
{
  configure_csi_resourcemapping(&target->resourceMapping, &source->resourceMapping);
  target->powerControlOffset = source->powerControlOffset;
1890
  UPDATE_IE(target->powerControlOffsetSS, source->powerControlOffsetSS, long);
1891 1892
  target->scramblingID = source->scramblingID;
  if (source->periodicityAndOffset)
1893
    UPDATE_IE(target->periodicityAndOffset, source->periodicityAndOffset, NR_CSI_ResourcePeriodicityAndOffset_t);
1894
  if (source->qcl_InfoPeriodicCSI_RS)
1895
    UPDATE_IE(target->qcl_InfoPeriodicCSI_RS, source->qcl_InfoPeriodicCSI_RS, NR_TCI_StateId_t);
1896 1897 1898 1899 1900
}

static void configure_csiim_resource(NR_CSI_IM_Resource_t *target, NR_CSI_IM_Resource_t *source)
{
  if (source->csi_IM_ResourceElementPattern)
1901 1902 1903
    UPDATE_IE(target->csi_IM_ResourceElementPattern,
              source->csi_IM_ResourceElementPattern,
              struct NR_CSI_IM_Resource__csi_IM_ResourceElementPattern);
1904
  if (source->freqBand)
1905
    UPDATE_IE(target->freqBand, source->freqBand, NR_CSI_FrequencyOccupation_t);
1906
  if (source->periodicityAndOffset)
1907
    UPDATE_IE(target->periodicityAndOffset, source->periodicityAndOffset, NR_CSI_ResourcePeriodicityAndOffset_t);
1908 1909
}

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
static void modify_csi_measconfig(NR_CSI_MeasConfig_t *source, NR_CSI_MeasConfig_t *target)
{
  if (source->reportTriggerSize)
    UPDATE_IE(target->reportTriggerSize, source->reportTriggerSize, long);
  if (source->semiPersistentOnPUSCH_TriggerStateList)
    HANDLE_SETUPRELEASE_IE(target->semiPersistentOnPUSCH_TriggerStateList,
                           source->semiPersistentOnPUSCH_TriggerStateList,
                           NR_CSI_SemiPersistentOnPUSCH_TriggerStateList_t,
                           asn_DEF_NR_SetupRelease_CSI_SemiPersistentOnPUSCH_TriggerStateList);
  // NZP-CSI-RS-Resources
  if (source->nzp_CSI_RS_ResourceToReleaseList) {
    RELEASE_IE_FROMLIST(source->nzp_CSI_RS_ResourceToReleaseList,
                        target->nzp_CSI_RS_ResourceToAddModList,
                        nzp_CSI_RS_ResourceId);
  }
  if (source->nzp_CSI_RS_ResourceToAddModList) {
    if (!target->nzp_CSI_RS_ResourceToAddModList)
      target->nzp_CSI_RS_ResourceToAddModList = calloc(1, sizeof(*target->nzp_CSI_RS_ResourceToAddModList));
    ADDMOD_IE_FROMLIST_WFUNCTION(source->nzp_CSI_RS_ResourceToAddModList,
                                 target->nzp_CSI_RS_ResourceToAddModList,
                                 nzp_CSI_RS_ResourceId,
                                 NR_NZP_CSI_RS_Resource_t,
                                 configure_csirs_resource);
  }
  // NZP-CSI-RS-ResourceSets
  if (source->nzp_CSI_RS_ResourceSetToReleaseList) {
    RELEASE_IE_FROMLIST(source->nzp_CSI_RS_ResourceSetToReleaseList,
                        target->nzp_CSI_RS_ResourceSetToAddModList,
                        nzp_CSI_ResourceSetId);
  }
  if (source->nzp_CSI_RS_ResourceSetToAddModList) {
    if (!target->nzp_CSI_RS_ResourceSetToAddModList)
      target->nzp_CSI_RS_ResourceSetToAddModList = calloc(1, sizeof(*target->nzp_CSI_RS_ResourceSetToAddModList));
    ADDMOD_IE_FROMLIST(source->nzp_CSI_RS_ResourceSetToAddModList,
                       target->nzp_CSI_RS_ResourceSetToAddModList,
                       nzp_CSI_ResourceSetId,
                       NR_NZP_CSI_RS_ResourceSet_t);
  }
  // CSI-IM-Resource
  if (source->csi_IM_ResourceToReleaseList) {
    RELEASE_IE_FROMLIST(source->csi_IM_ResourceToReleaseList,
                        target->csi_IM_ResourceToAddModList,
                        csi_IM_ResourceId);
  }
  if (source->csi_IM_ResourceToAddModList) {
    if (!target->csi_IM_ResourceToAddModList)
      target->csi_IM_ResourceToAddModList = calloc(1, sizeof(*target->csi_IM_ResourceToAddModList));
    ADDMOD_IE_FROMLIST_WFUNCTION(source->csi_IM_ResourceToAddModList,
                                 target->csi_IM_ResourceToAddModList,
                                 csi_IM_ResourceId,
                                 NR_CSI_IM_Resource_t,
                                 configure_csiim_resource);
  }
  // CSI-IM-ResourceSets
  if (source->csi_IM_ResourceSetToReleaseList) {
    RELEASE_IE_FROMLIST(source->csi_IM_ResourceSetToReleaseList,
                        target->csi_IM_ResourceSetToAddModList,
                        csi_IM_ResourceSetId);
  }
  if (source->csi_IM_ResourceSetToAddModList) {
    if (!target->csi_IM_ResourceSetToAddModList)
      target->csi_IM_ResourceSetToAddModList = calloc(1, sizeof(*target->csi_IM_ResourceSetToAddModList));
    ADDMOD_IE_FROMLIST(source->csi_IM_ResourceSetToAddModList,
                       target->csi_IM_ResourceSetToAddModList,
                       csi_IM_ResourceSetId,
                       NR_CSI_IM_ResourceSet_t);
  }
  // CSI-SSB-ResourceSets
  if (source->csi_SSB_ResourceSetToReleaseList) {
    RELEASE_IE_FROMLIST(source->csi_SSB_ResourceSetToReleaseList,
                        target->csi_SSB_ResourceSetToAddModList,
                        csi_SSB_ResourceSetId);
  }
  if (source->csi_SSB_ResourceSetToAddModList) {
    if (!target->csi_SSB_ResourceSetToAddModList)
      target->csi_SSB_ResourceSetToAddModList = calloc(1, sizeof(*target->csi_SSB_ResourceSetToAddModList));
    ADDMOD_IE_FROMLIST(source->csi_SSB_ResourceSetToAddModList,
                       target->csi_SSB_ResourceSetToAddModList,
                       csi_SSB_ResourceSetId,
                       NR_CSI_SSB_ResourceSet_t);
  }
  // CSI-ResourceConfigs
  if (source->csi_ResourceConfigToReleaseList) {
    RELEASE_IE_FROMLIST(source->csi_ResourceConfigToReleaseList,
                        target->csi_ResourceConfigToAddModList,
                        csi_ResourceConfigId);
  }
  if (source->csi_ResourceConfigToAddModList) {
    if (!target->csi_ResourceConfigToAddModList)
      target->csi_ResourceConfigToAddModList = calloc(1, sizeof(*target->csi_ResourceConfigToAddModList));
    ADDMOD_IE_FROMLIST(source->csi_ResourceConfigToAddModList,
                       target->csi_ResourceConfigToAddModList,
                       csi_ResourceConfigId,
                       NR_CSI_ResourceConfig_t);
  }
  // CSI-ReportConfigs
  if (source->csi_ReportConfigToReleaseList) {
    RELEASE_IE_FROMLIST(source->csi_ReportConfigToReleaseList,
                        target->csi_ReportConfigToAddModList,
                        reportConfigId);
  }
  if (source->csi_ReportConfigToAddModList) {
    if (!target->csi_ReportConfigToAddModList)
      target->csi_ReportConfigToAddModList = calloc(1, sizeof(*target->csi_ReportConfigToAddModList));
    ADDMOD_IE_FROMLIST(source->csi_ReportConfigToAddModList,
                       target->csi_ReportConfigToAddModList,
                       reportConfigId,
                       NR_CSI_ReportConfig_t);
  }
}

2021
static void configure_csiconfig(NR_UE_ServingCell_Info_t *sc_info, struct NR_SetupRelease_CSI_MeasConfig *csi_MeasConfig_sr)
2022 2023
{
  switch (csi_MeasConfig_sr->present) {
2024
    case NR_SetupRelease_CSI_MeasConfig_PR_NOTHING:
2025
      break;
2026
    case NR_SetupRelease_CSI_MeasConfig_PR_release:
2027
      asn1cFreeStruc(asn_DEF_NR_CSI_MeasConfig, sc_info->csi_MeasConfig);
2028
      asn1cFreeStruc(asn_DEF_NR_CSI_AperiodicTriggerStateList, sc_info->aperiodicTriggerStateList);
2029
      break;
2030 2031 2032
    case NR_SetupRelease_CSI_MeasConfig_PR_setup: {
      // separately handling aperiodicTriggerStateList
      // because it is set directly into sc_info structure
2033
      if (csi_MeasConfig_sr->choice.setup->aperiodicTriggerStateList)
2034
        HANDLE_SETUPRELEASE_DIRECT(sc_info->aperiodicTriggerStateList,
2035
                                   csi_MeasConfig_sr->choice.setup->aperiodicTriggerStateList,
2036 2037
                                   NR_CSI_AperiodicTriggerStateList_t,
                                   asn_DEF_NR_CSI_AperiodicTriggerStateList);
2038
      if (!sc_info->csi_MeasConfig) { // setup
2039
        UPDATE_IE(sc_info->csi_MeasConfig, csi_MeasConfig_sr->choice.setup, NR_CSI_MeasConfig_t);
2040
      } else { // modification
2041
        modify_csi_measconfig(csi_MeasConfig_sr->choice.setup, sc_info->csi_MeasConfig);
2042 2043
      }
      break;
2044
    }
2045
    default:
2046 2047 2048 2049
      AssertFatal(false, "Invalid case\n");
  }
}

2050
static void configure_servingcell_info(NR_UE_MAC_INST_t *mac, NR_ServingCellConfig_t *scd)
2051
{
2052 2053
  NR_UE_ServingCell_Info_t *sc_info = &mac->sc_info;
  if (scd->csi_MeasConfig) {
2054
    configure_csiconfig(sc_info, scd->csi_MeasConfig);
2055 2056
    compute_csi_bitlen(sc_info->csi_MeasConfig, mac->csi_report_template);
  }
2057

2058
  if (scd->supplementaryUplink)
2059
    UPDATE_IE(sc_info->supplementaryUplink, scd->supplementaryUplink, NR_UplinkConfig_t);
2060
  if (scd->crossCarrierSchedulingConfig)
2061
    UPDATE_IE(sc_info->crossCarrierSchedulingConfig, scd->crossCarrierSchedulingConfig, NR_CrossCarrierSchedulingConfig_t);
2062 2063
  if (scd->pdsch_ServingCellConfig) {
    switch (scd->pdsch_ServingCellConfig->present) {
2064
      case NR_SetupRelease_PDSCH_ServingCellConfig_PR_NOTHING:
2065
        break;
2066
      case NR_SetupRelease_PDSCH_ServingCellConfig_PR_release:
2067
        // release all configurations
2068 2069
        if (sc_info->pdsch_CGB_Transmission)
          asn1cFreeStruc(asn_DEF_NR_PDSCH_CodeBlockGroupTransmission, sc_info->pdsch_CGB_Transmission);
2070 2071 2072 2073 2074 2075 2076 2077
        if (sc_info->xOverhead_PDSCH) {
          free(sc_info->xOverhead_PDSCH);
          sc_info->xOverhead_PDSCH = NULL;
        }
        if (sc_info->maxMIMO_Layers_PDSCH) {
          free(sc_info->maxMIMO_Layers_PDSCH);
          sc_info->maxMIMO_Layers_PDSCH = NULL;
        }
2078 2079
        if (sc_info->downlinkHARQ_FeedbackDisabled_r17)
          asn1cFreeStruc(asn_DEF_NR_DownlinkHARQ_FeedbackDisabled_r17, sc_info->downlinkHARQ_FeedbackDisabled_r17);
2080
        break;
2081
      case NR_SetupRelease_PDSCH_ServingCellConfig_PR_setup: {
2082 2083
        NR_PDSCH_ServingCellConfig_t *pdsch_servingcellconfig = scd->pdsch_ServingCellConfig->choice.setup;
        if (pdsch_servingcellconfig->codeBlockGroupTransmission)
2084 2085 2086 2087
          HANDLE_SETUPRELEASE_DIRECT(sc_info->pdsch_CGB_Transmission,
                                     pdsch_servingcellconfig->codeBlockGroupTransmission,
                                     NR_PDSCH_CodeBlockGroupTransmission_t,
                                     asn_DEF_NR_PDSCH_CodeBlockGroupTransmission);
2088
        UPDATE_IE(sc_info->xOverhead_PDSCH, pdsch_servingcellconfig->xOverhead, long);
2089
        if (pdsch_servingcellconfig->ext1 && pdsch_servingcellconfig->ext1->maxMIMO_Layers)
2090
          UPDATE_IE(sc_info->maxMIMO_Layers_PDSCH, pdsch_servingcellconfig->ext1->maxMIMO_Layers, long);
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
        if (pdsch_servingcellconfig->ext3 && pdsch_servingcellconfig->ext3->downlinkHARQ_FeedbackDisabled_r17) {
          switch (pdsch_servingcellconfig->ext3->downlinkHARQ_FeedbackDisabled_r17->present) {
            case NR_SetupRelease_DownlinkHARQ_FeedbackDisabled_r17_PR_NOTHING:
              break;
            case NR_SetupRelease_DownlinkHARQ_FeedbackDisabled_r17_PR_release:
              if (sc_info->downlinkHARQ_FeedbackDisabled_r17)
                asn1cFreeStruc(asn_DEF_NR_DownlinkHARQ_FeedbackDisabled_r17, sc_info->downlinkHARQ_FeedbackDisabled_r17);
              break;
            case NR_SetupRelease_DownlinkHARQ_FeedbackDisabled_r17_PR_setup:
              if (sc_info->downlinkHARQ_FeedbackDisabled_r17 == NULL) {
                sc_info->downlinkHARQ_FeedbackDisabled_r17 = calloc(1, sizeof(*sc_info->downlinkHARQ_FeedbackDisabled_r17));
                sc_info->downlinkHARQ_FeedbackDisabled_r17->buf = calloc(4, sizeof(*sc_info->downlinkHARQ_FeedbackDisabled_r17->buf));
              }
              sc_info->downlinkHARQ_FeedbackDisabled_r17->size = pdsch_servingcellconfig->ext3->downlinkHARQ_FeedbackDisabled_r17->choice.setup.size;
              sc_info->downlinkHARQ_FeedbackDisabled_r17->bits_unused = pdsch_servingcellconfig->ext3->downlinkHARQ_FeedbackDisabled_r17->choice.setup.bits_unused;
              for (int i = 0; i < sc_info->downlinkHARQ_FeedbackDisabled_r17->size; i++)
                sc_info->downlinkHARQ_FeedbackDisabled_r17->buf[i] = pdsch_servingcellconfig->ext3->downlinkHARQ_FeedbackDisabled_r17->choice.setup.buf[i];
              break;
            default:
              AssertFatal(false, "Invalid case\n");
          }
        }
2113 2114
        break;
      }
2115
      default:
2116 2117 2118
        AssertFatal(false, "Invalid case\n");
    }
  }
2119
  if (scd->uplinkConfig && scd->uplinkConfig->pusch_ServingCellConfig) {
2120
    switch (scd->uplinkConfig->pusch_ServingCellConfig->present) {
2121
      case NR_SetupRelease_PUSCH_ServingCellConfig_PR_NOTHING:
2122
        break;
2123
      case NR_SetupRelease_PUSCH_ServingCellConfig_PR_release:
2124
        // release all configurations
2125 2126
        if (sc_info->pusch_CGB_Transmission)
          asn1cFreeStruc(asn_DEF_NR_PUSCH_CodeBlockGroupTransmission, sc_info->pusch_CGB_Transmission);
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
        if (sc_info->rateMatching_PUSCH) {
          free(sc_info->rateMatching_PUSCH);
          sc_info->rateMatching_PUSCH = NULL;
        }
        if (sc_info->xOverhead_PUSCH) {
          free(sc_info->xOverhead_PUSCH);
          sc_info->xOverhead_PUSCH = NULL;
        }
        if (sc_info->maxMIMO_Layers_PUSCH) {
          free(sc_info->maxMIMO_Layers_PUSCH);
          sc_info->maxMIMO_Layers_PUSCH = NULL;
        }
        break;
2140
      case NR_SetupRelease_PUSCH_ServingCellConfig_PR_setup: {
2141
        NR_PUSCH_ServingCellConfig_t *pusch_servingcellconfig = scd->uplinkConfig->pusch_ServingCellConfig->choice.setup;
2142 2143
        UPDATE_IE(sc_info->rateMatching_PUSCH, pusch_servingcellconfig->rateMatching, long);
        UPDATE_IE(sc_info->xOverhead_PUSCH, pusch_servingcellconfig->xOverhead, long);
2144
        if (pusch_servingcellconfig->ext1 && pusch_servingcellconfig->ext1->maxMIMO_Layers)
2145
          UPDATE_IE(sc_info->maxMIMO_Layers_PUSCH, pusch_servingcellconfig->ext1->maxMIMO_Layers, long);
2146
        if (pusch_servingcellconfig->codeBlockGroupTransmission)
2147 2148 2149 2150
          HANDLE_SETUPRELEASE_DIRECT(sc_info->pusch_CGB_Transmission,
                                     pusch_servingcellconfig->codeBlockGroupTransmission,
                                     NR_PUSCH_CodeBlockGroupTransmission_t,
                                     asn_DEF_NR_PUSCH_CodeBlockGroupTransmission);
2151 2152
        break;
      }
2153
      default:
2154 2155 2156 2157 2158
        AssertFatal(false, "Invalid case\n");
    }
  }
}

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
/// This function implements 38.331 Section 5.3.12: UE actions upon PUCCH/SRS release request
void release_PUCCH_SRS(NR_UE_MAC_INST_t *mac)
{
  // release PUCCH-CSI-Resources configured in CSI-ReportConfig
  NR_UE_ServingCell_Info_t *sc_info = &mac->sc_info;
  NR_CSI_MeasConfig_t *meas_config = sc_info->csi_MeasConfig;
  if (meas_config && meas_config->csi_ReportConfigToAddModList) {
    for (int i = 0; i < meas_config->csi_ReportConfigToAddModList->list.count; i++) {
      struct NR_CSI_ReportConfig__reportConfigType *type = &meas_config->csi_ReportConfigToAddModList->list.array[i]->reportConfigType;
      switch (type->present) {
        case NR_CSI_ReportConfig__reportConfigType_PR_periodic :
          for (int j = type->choice.periodic->pucch_CSI_ResourceList.list.count; j > 0 ; j--)
            asn_sequence_del(&type->choice.periodic->pucch_CSI_ResourceList.list, j - 1, 1);
          break;
        case NR_CSI_ReportConfig__reportConfigType_PR_semiPersistentOnPUCCH :
          for (int j = type->choice.semiPersistentOnPUCCH->pucch_CSI_ResourceList.list.count; j > 0 ; j--)
            asn_sequence_del(&type->choice.semiPersistentOnPUCCH->pucch_CSI_ResourceList.list, j - 1, 1);
          break;
        case NR_CSI_ReportConfig__reportConfigType_PR_semiPersistentOnPUSCH :
        case NR_CSI_ReportConfig__reportConfigType_PR_aperiodic :
          // no PUCCH config to release
          break;
        default :
          AssertFatal(false, "Invalid CSI report type\n");
      }
    }
  }

  for (int bwp = 0; bwp < mac->ul_BWPs.count; bwp++) {
    // release SchedulingRequestResourceConfig instances configured in PUCCH-Config
    NR_PUCCH_Config_t *pucch_Config = mac->ul_BWPs.array[bwp]->pucch_Config;
2190 2191 2192
    if (pucch_Config)
      for (int j = pucch_Config->schedulingRequestResourceToAddModList->list.count; j > 0 ; j--)
        asn_sequence_del(&pucch_Config->schedulingRequestResourceToAddModList->list, j - 1, 1);
2193 2194 2195
    // release SRS-Resource instances configured in SRS-Config
    // TODO not clear if only SRS-Resources or also the ResourceSet should be released
    NR_SRS_Config_t *srs_Config = mac->ul_BWPs.array[bwp]->srs_Config;
2196 2197 2198
    if (srs_Config)
      for (int j = srs_Config->srs_ResourceToAddModList->list.count; j > 0 ; j--)
        asn_sequence_del(&srs_Config->srs_ResourceToAddModList->list, j - 1, 1);
2199 2200 2201
  }
}

2202
void release_dl_BWP(NR_UE_MAC_INST_t *mac, int index)
2203
{
2204 2205 2206 2207
  NR_UE_DL_BWP_t *bwp = mac->dl_BWPs.array[index];
  int bwp_id = bwp->bwp_id;
  asn_sequence_del(&mac->dl_BWPs, index, 0);

2208
  free(bwp->cyclicprefix);
2209 2210
  asn1cFreeStruc(asn_DEF_NR_PDSCH_TimeDomainResourceAllocationList, bwp->tdaList_Common);
  asn1cFreeStruc(asn_DEF_NR_PDSCH_Config, bwp->pdsch_Config);
2211 2212 2213 2214
  free(bwp);

  NR_BWP_PDCCH_t *pdcch = &mac->config_BWP_PDCCH[bwp_id];
  release_common_ss_cset(pdcch);
2215 2216 2217 2218
  for (int i = pdcch->list_Coreset.count; i > 0 ; i--)
    asn_sequence_del(&pdcch->list_Coreset, i - 1, 1);
  for (int i = pdcch->list_SS.count; i > 0 ; i--)
    asn_sequence_del(&pdcch->list_SS, i - 1, 1);
2219 2220
}

2221
void release_ul_BWP(NR_UE_MAC_INST_t *mac, int index)
2222
{
2223 2224 2225
  NR_UE_UL_BWP_t *bwp = mac->ul_BWPs.array[index];
  asn_sequence_del(&mac->ul_BWPs, index, 0);

2226
  free(bwp->cyclicprefix);
2227 2228 2229 2230 2231 2232 2233
  asn1cFreeStruc(asn_DEF_NR_RACH_ConfigCommon, bwp->rach_ConfigCommon);
  asn1cFreeStruc(asn_DEF_NR_PUSCH_TimeDomainResourceAllocationList, bwp->tdaList_Common);
  asn1cFreeStruc(asn_DEF_NR_ConfiguredGrantConfig, bwp->configuredGrantConfig);
  asn1cFreeStruc(asn_DEF_NR_PUSCH_Config, bwp->pusch_Config);
  asn1cFreeStruc(asn_DEF_NR_PUCCH_Config, bwp->pucch_Config);
  asn1cFreeStruc(asn_DEF_NR_PUCCH_ConfigCommon, bwp->pucch_ConfigCommon);
  asn1cFreeStruc(asn_DEF_NR_SRS_Config, bwp->srs_Config);
2234
  free(bwp->msg3_DeltaPreamble);
2235
  bwp->msg3_DeltaPreamble = NULL;
2236 2237
  free(bwp->p0_NominalWithGrant);
  bwp->p0_NominalWithGrant = NULL;
2238 2239 2240
  free(bwp);
}

2241
static void configure_BWPs(NR_UE_MAC_INST_t *mac, NR_ServingCellConfig_t *scd)
2242
{
2243
  configure_dedicated_BWP_dl(mac, 0, scd->initialDownlinkBWP);
2244
  if (scd->downlinkBWP_ToReleaseList) {
2245 2246 2247 2248 2249 2250
    for (int i = 0; i < scd->downlinkBWP_ToReleaseList->list.count; i++) {
      for (int j = 0; j < mac->dl_BWPs.count; j++) {
        if (*scd->downlinkBWP_ToReleaseList->list.array[i] == mac->dl_BWPs.array[i]->bwp_id)
          release_dl_BWP(mac, i);
      }
    }
2251 2252 2253 2254
  }
  if (scd->downlinkBWP_ToAddModList) {
    for (int i = 0; i < scd->downlinkBWP_ToAddModList->list.count; i++) {
      NR_BWP_Downlink_t *bwp = scd->downlinkBWP_ToAddModList->list.array[i];
2255 2256
      configure_common_BWP_dl(mac, bwp->bwp_Id, bwp->bwp_Common);
      configure_dedicated_BWP_dl(mac, bwp->bwp_Id, bwp->bwp_Dedicated);
2257 2258 2259 2260 2261 2262 2263 2264
    }
  }
  if (scd->firstActiveDownlinkBWP_Id) {
    mac->current_DL_BWP = get_dl_bwp_structure(mac, *scd->firstActiveDownlinkBWP_Id, false);
    AssertFatal(mac->current_DL_BWP, "Couldn't find DL-BWP %ld\n", *scd->firstActiveDownlinkBWP_Id);
  }

  if (scd->uplinkConfig) {
2265
    configure_dedicated_BWP_ul(mac, 0, scd->uplinkConfig->initialUplinkBWP);
2266
    if (scd->uplinkConfig->uplinkBWP_ToReleaseList) {
2267 2268 2269 2270 2271 2272
      for (int i = 0; i < scd->uplinkConfig->uplinkBWP_ToReleaseList->list.count; i++) {
        for (int j = 0; j < mac->ul_BWPs.count; j++) {
          if (*scd->uplinkConfig->uplinkBWP_ToReleaseList->list.array[i] == mac->ul_BWPs.array[i]->bwp_id)
            release_ul_BWP(mac, i);
        }
      }
2273 2274 2275 2276
    }
    if (scd->uplinkConfig->uplinkBWP_ToAddModList) {
      for (int i = 0; i < scd->uplinkConfig->uplinkBWP_ToAddModList->list.count; i++) {
        NR_BWP_Uplink_t *bwp = scd->uplinkConfig->uplinkBWP_ToAddModList->list.array[i];
2277 2278
        configure_common_BWP_ul(mac, bwp->bwp_Id, bwp->bwp_Common);
        configure_dedicated_BWP_ul(mac, bwp->bwp_Id, bwp->bwp_Dedicated);
2279 2280 2281 2282
      }
    }
    if (scd->uplinkConfig->firstActiveUplinkBWP_Id) {
      mac->current_UL_BWP = get_ul_bwp_structure(mac, *scd->uplinkConfig->firstActiveUplinkBWP_Id, false);
2283
      AssertFatal(mac->current_UL_BWP, "Couldn't find UL-BWP %ld\n", *scd->uplinkConfig->firstActiveUplinkBWP_Id);
2284 2285 2286 2287
    }
  }
}

2288 2289
static void handle_mac_uecap_info(NR_UE_MAC_INST_t *mac, NR_UE_NR_Capability_t *ue_Capability)
{
2290 2291 2292 2293 2294 2295 2296 2297 2298
  if (!ue_Capability->featureSets)
    return;
  if (ue_Capability->featureSets->featureSetsDownlinkPerCC) {
    struct NR_FeatureSets__featureSetsDownlinkPerCC *fs_dlcc_list = ue_Capability->featureSets->featureSetsDownlinkPerCC;
    for (int i = 0; i < fs_dlcc_list->list.count; i++) {
      NR_FeatureSetDownlinkPerCC_t *fs_dl_cc = fs_dlcc_list->list.array[i];
      if (mac->current_DL_BWP->scs != fs_dl_cc->supportedSubcarrierSpacingDL)
        continue;
      int dl_bw_mhz = mac->phy_config.config_req.carrier_config.dl_bandwidth;
2299
      if (!supported_bw_comparison(dl_bw_mhz, &fs_dl_cc->supportedBandwidthDL, fs_dl_cc->channelBW_90mhz))
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
        continue;
      if (fs_dl_cc->maxNumberMIMO_LayersPDSCH)
        mac->uecap_maxMIMO_PDSCH_layers = 2 << *fs_dl_cc->maxNumberMIMO_LayersPDSCH;
    }
  }
  if (ue_Capability->featureSets->featureSetsUplinkPerCC) {
    struct NR_FeatureSets__featureSetsUplinkPerCC *fs_ulcc_list = ue_Capability->featureSets->featureSetsUplinkPerCC;
    for (int i = 0; i < fs_ulcc_list->list.count; i++) {
      NR_FeatureSetUplinkPerCC_t *fs_ul_cc = fs_ulcc_list->list.array[i];
      if (mac->current_UL_BWP->scs != fs_ul_cc->supportedSubcarrierSpacingUL)
        continue;
      int ul_bw_mhz = mac->phy_config.config_req.carrier_config.uplink_bandwidth;
2312
      if (!supported_bw_comparison(ul_bw_mhz, &fs_ul_cc->supportedBandwidthUL, fs_ul_cc->channelBW_90mhz))
2313 2314 2315 2316 2317
        continue;
      if (fs_ul_cc->maxNumberMIMO_LayersNonCB_PUSCH)
        mac->uecap_maxMIMO_PUSCH_layers_nocb = 1 << *fs_ul_cc->maxNumberMIMO_LayersNonCB_PUSCH;
      if (fs_ul_cc->mimo_CB_PUSCH && fs_ul_cc->mimo_CB_PUSCH->maxNumberMIMO_LayersCB_PUSCH)
        mac->uecap_maxMIMO_PUSCH_layers_cb = 1 << *fs_ul_cc->mimo_CB_PUSCH->maxNumberMIMO_LayersCB_PUSCH;
2318 2319 2320 2321
    }
  }
}

2322 2323
void nr_rrc_mac_config_req_cg(module_id_t module_id,
                              int cc_idP,
2324 2325
                              NR_CellGroupConfig_t *cell_group_config,
                              NR_UE_NR_Capability_t *ue_Capability)
2326
{
2327
  LOG_I(MAC,"[UE %d] Applying CellGroupConfig from gNodeB\n", module_id);
2328 2329
  AssertFatal(cell_group_config, "CellGroupConfig should not be NULL\n");
  NR_UE_MAC_INST_t *mac = get_mac_inst(module_id);
2330

2331 2332 2333 2334 2335
  if (cell_group_config->physicalCellGroupConfig)
    configure_physicalcellgroup(mac, cell_group_config->physicalCellGroupConfig);

  if (cell_group_config->spCellConfig) {
    NR_SpCellConfig_t *spCellConfig = cell_group_config->spCellConfig;
2336
    NR_ServingCellConfig_t *scd = spCellConfig->spCellConfigDedicated;
2337 2338 2339
    mac->servCellIndex = spCellConfig->servCellIndex ? *spCellConfig->servCellIndex : 0;
    if (spCellConfig->reconfigurationWithSync) {
      LOG_A(NR_MAC, "Received reconfigurationWithSync\n");
2340
      handle_reconfiguration_with_sync(mac, cc_idP, spCellConfig->reconfigurationWithSync);
2341
    }
2342
    if (scd) {
2343
      configure_servingcell_info(mac, scd);
2344
      configure_BWPs(mac, scd);
2345
    }
2346
  }
2347

2348 2349 2350
  if (cell_group_config->mac_CellGroupConfig)
    configure_maccellgroup(mac, cell_group_config->mac_CellGroupConfig);

2351
  configure_logicalChannelBearer(mac,
2352 2353 2354
                                 cell_group_config->rlc_BearerToAddModList,
                                 cell_group_config->rlc_BearerToReleaseList);

2355 2356 2357
  if (ue_Capability)
    handle_mac_uecap_info(mac, ue_Capability);

2358
  // Setup the SSB to Rach Occasions mapping according to the config
2359 2360 2361
  // Only if RACH is configured for current BWP
  if (mac->current_UL_BWP->rach_ConfigCommon)
    build_ssb_to_ro_map(mac);
2362

2363
  if (!mac->dl_config_request || !mac->ul_config_request)
2364
    ue_init_config_request(mac, mac->current_DL_BWP->scs);
2365
}