gNB_scheduler_RA.c 88 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 23 24 25 26
/*! \file     gNB_scheduler_RA.c
 * \brief     primitives used for random access
 * \author    Guido Casati
 * \date      2019
 * \email:    guido.casati@iis.fraunhofer.de
27 28 29
 * \version
 */

30
#include "platform_types.h"
31

cig's avatar
cig committed
32
/* MAC */
33 34 35
#include "nr_mac_gNB.h"
#include "NR_MAC_gNB/mac_proto.h"
#include "NR_MAC_COMMON/nr_mac_extern.h"
36

cig's avatar
cig committed
37 38 39
/* Utils */
#include "common/utils/LOG/log.h"
#include "common/utils/LOG/vcd_signal_dumper.h"
cig's avatar
cig committed
40
#include "common/utils/nr/nr_common.h"
41
#include "UTIL/OPT/opt.h"
cig's avatar
cig committed
42
#include "SIMULATION/TOOLS/sim.h" // for taus
43

44 45 46
/* rlc */
#include "openair2/LAYER2/nr_rlc/nr_rlc_oai_api.h"

Raymond Knopp's avatar
Raymond Knopp committed
47
#include <executables/softmodem-common.h>
cig's avatar
cig committed
48
extern RAN_CONTEXT_t RC;
cig's avatar
cig committed
49
extern const uint8_t nr_slots_per_frame[5];
50
extern uint16_t sl_ahead;
51

52
uint8_t DELTA[4]= {2,3,4,6};
53

54 55 56 57 58
#define MAX_NUMBER_OF_SSB 64		
float ssb_per_rach_occasion[8] = {0.125,0.25,0.5,1,2,4,8};

int16_t ssb_index_from_prach(module_id_t module_idP,
                             frame_t frameP,
Florian Kaltenberger's avatar
Florian Kaltenberger committed
59 60 61 62 63 64
			     sub_frame_t slotP,
			     uint16_t preamble_index,
			     uint8_t freq_index,
			     uint8_t symbol) {
  
  gNB_MAC_INST *gNB = RC.nrmac[module_idP];
65
  NR_COMMON_channels_t *cc = &gNB->common_channels[0];
66 67 68 69
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
  nfapi_nr_config_request_scf_t *cfg = &RC.nrmac[module_idP]->config[0];

  uint8_t config_index = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric.prach_ConfigurationIndex;
70
  uint8_t fdm = cfg->prach_config.num_prach_fd_occasions.value;
kn.raju's avatar
kn.raju committed
71
  
72
  uint8_t total_RApreambles = MAX_NUM_NR_PRACH_PREAMBLES;
73
  if( scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->totalNumberOfRA_Preambles != NULL)
kn.raju's avatar
kn.raju committed
74 75
    total_RApreambles = *scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->totalNumberOfRA_Preambles;	
  
76
  float  num_ssb_per_RO = ssb_per_rach_occasion[cfg->prach_config.ssb_per_rach.value];	
77
  uint16_t start_symbol_index = 0;
78
  uint8_t mu,N_dur=0,N_t_slot=0,start_symbol = 0, temp_start_symbol = 0, N_RA_slot=0;
kn.raju's avatar
kn.raju committed
79
  uint16_t format,RA_sfn_index = -1;
80
  uint8_t config_period = 1;
kn.raju's avatar
kn.raju committed
81
  uint16_t prach_occasion_id = -1;
82
  uint8_t num_active_ssb = cc->num_active_ssb;
83 84 85 86 87 88 89

  if (scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg1_SubcarrierSpacing)
    mu = *scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg1_SubcarrierSpacing;
  else
    mu = scc->downlinkConfigCommon->frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing;

  get_nr_prach_info_from_index(config_index,
90 91 92 93 94 95 96 97 98 99 100 101
			       (int)frameP,
			       (int)slotP,
			       scc->downlinkConfigCommon->frequencyInfoDL->absoluteFrequencyPointA,
			       mu,
			       cc->frame_type,
			       &format,
			       &start_symbol,
			       &N_t_slot,
			       &N_dur,
			       &RA_sfn_index,
			       &N_RA_slot,
			       &config_period);
kn.raju's avatar
kn.raju committed
102
  uint8_t index = 0,slot_index = 0;
103
  for (slot_index = 0;slot_index < N_RA_slot; slot_index++) {
104 105 106 107
    if (N_RA_slot <= 1) { //1 PRACH slot in a subframe
       if((mu == 1) || (mu == 3))
         slot_index = 1;  //For scs = 30khz and 120khz
    }
kn.raju's avatar
kn.raju committed
108 109
    for (int i=0; i< N_t_slot; i++) {
      temp_start_symbol = (start_symbol + i * N_dur + 14 * slot_index) % 14;
110 111 112 113 114 115
      if(symbol == temp_start_symbol) {
        start_symbol_index = i;
        break;
      }
    }
  }
kn.raju's avatar
kn.raju committed
116 117 118 119
  if (N_RA_slot <= 1) { //1 PRACH slot in a subframe
    if((mu == 1) || (mu == 3))
      slot_index = 0;  //For scs = 30khz and 120khz
  }
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

  //  prach_occasion_id = subframe_index * N_t_slot * N_RA_slot * fdm + N_RA_slot_index * N_t_slot * fdm + freq_index + fdm * start_symbol_index; 
  prach_occasion_id = (((frameP % (cc->max_association_period * config_period))/config_period)*cc->total_prach_occasions_per_config_period) +
                      (RA_sfn_index + slot_index) * N_t_slot * fdm + start_symbol_index * fdm + freq_index; 

  //one RO is shared by one or more SSB
  if(num_ssb_per_RO <= 1 )
    index = (int) (prach_occasion_id / (int)(1/num_ssb_per_RO)) % num_active_ssb;
  //one SSB have more than one continuous RO
  else if ( num_ssb_per_RO > 1) {
    index = (prach_occasion_id * (int)num_ssb_per_RO)% num_active_ssb ;
    for(int j = 0;j < num_ssb_per_RO;j++) {
      if(preamble_index <  (((j+1) * total_RApreambles) / num_ssb_per_RO))
        index = index + j;
    }
  }

137
  LOG_D(NR_MAC, "Frame %d, Slot %d: Prach Occasion id = %d ssb per RO = %f number of active SSB %u index = %d fdm %u symbol index %u freq_index %u total_RApreambles %u\n",
138 139
        frameP, slotP, prach_occasion_id, num_ssb_per_RO, num_active_ssb, index, fdm, start_symbol_index, freq_index, total_RApreambles);

140 141
  return index;
}
142 143


144 145 146
//Compute Total active SSBs and RO available
void find_SSB_and_RO_available(module_id_t module_idP) {

147
  gNB_MAC_INST *gNB = RC.nrmac[module_idP];
148
  NR_COMMON_channels_t *cc = &gNB->common_channels[0];
149 150 151 152
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
  nfapi_nr_config_request_scf_t *cfg = &RC.nrmac[module_idP]->config[0];

  uint8_t config_index = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric.prach_ConfigurationIndex;
153
  uint8_t mu,N_dur=0,N_t_slot=0,start_symbol=0,N_RA_slot = 0;
kn.raju's avatar
kn.raju committed
154
  uint16_t format,N_RA_sfn = 0,unused_RA_occasion,repetition = 0;
155
  uint8_t num_active_ssb = 0;
156
  uint8_t max_association_period = 1;
157

kn.raju's avatar
kn.raju committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  struct NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB *ssb_perRACH_OccasionAndCB_PreamblesPerSSB = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->ssb_perRACH_OccasionAndCB_PreamblesPerSSB;

  switch (ssb_perRACH_OccasionAndCB_PreamblesPerSSB->present){
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_oneEighth:
      cc->cb_preambles_per_ssb = 4 * (ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.oneEighth + 1);
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_oneFourth:
      cc->cb_preambles_per_ssb = 4 * (ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.oneFourth + 1);
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_oneHalf:
      cc->cb_preambles_per_ssb = 4 * (ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.oneHalf + 1);
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_one:
      cc->cb_preambles_per_ssb = 4 * (ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.one + 1);
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_two:
      cc->cb_preambles_per_ssb = 4 * (ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.two + 1);
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_four:
      cc->cb_preambles_per_ssb = ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.four;
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_eight:
      cc->cb_preambles_per_ssb = ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.eight;
      break;
    case NR_RACH_ConfigCommon__ssb_perRACH_OccasionAndCB_PreamblesPerSSB_PR_sixteen:
      cc->cb_preambles_per_ssb = ssb_perRACH_OccasionAndCB_PreamblesPerSSB->choice.sixteen;
      break;
    default:
      AssertFatal(1 == 0, "Unsupported ssb_perRACH_config %d\n", ssb_perRACH_OccasionAndCB_PreamblesPerSSB->present);
      break;
    }

190 191 192 193 194 195 196
  if (scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg1_SubcarrierSpacing)
    mu = *scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg1_SubcarrierSpacing;
  else
    mu = scc->downlinkConfigCommon->frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing;

  // prach is scheduled according to configuration index and tables 6.3.3.2.2 to 6.3.3.2.4
  get_nr_prach_occasion_info_from_index(config_index,
197 198 199 200 201 202 203 204 205 206
                                        scc->downlinkConfigCommon->frequencyInfoDL->absoluteFrequencyPointA,
                                        mu,
                                        cc->frame_type,
                                        &format,
                                        &start_symbol,
                                        &N_t_slot,
                                        &N_dur,
                                        &N_RA_slot,
                                        &N_RA_sfn,
                                        &max_association_period);
207 208

  float num_ssb_per_RO = ssb_per_rach_occasion[cfg->prach_config.ssb_per_rach.value];	
209
  uint8_t fdm = cfg->prach_config.num_prach_fd_occasions.value;
210
  uint64_t L_ssb = (((uint64_t) cfg->ssb_table.ssb_mask_list[0].ssb_mask.value)<<32) | cfg->ssb_table.ssb_mask_list[1].ssb_mask.value ;
211
  uint32_t total_RA_occasions = N_RA_sfn * N_t_slot * N_RA_slot * fdm;
212

213
  for(int i = 0;i < 64;i++) {
214
    if ((L_ssb >> (63-i)) & 0x01) { // only if the bit of L_ssb at current ssb index is 1
215
      cc->ssb_index[num_active_ssb] = i; 
216
      num_active_ssb++;
217
    }
218
  }
219

kn.raju's avatar
kn.raju committed
220
  cc->total_prach_occasions_per_config_period = total_RA_occasions;
221
  for(int i=1; (1 << (i-1)) <= max_association_period; i++) {
kn.raju's avatar
kn.raju committed
222 223
    cc->max_association_period = (1 <<(i-1));
    total_RA_occasions = total_RA_occasions * cc->max_association_period;
224
    if(total_RA_occasions >= (int) (num_active_ssb/num_ssb_per_RO)) {
225 226 227 228
      repetition = (uint16_t)((total_RA_occasions * num_ssb_per_RO )/num_active_ssb);
      break;
    }
  }
229

230 231 232
  unused_RA_occasion = total_RA_occasions - (int)((num_active_ssb * repetition)/num_ssb_per_RO);
  cc->total_prach_occasions = total_RA_occasions - unused_RA_occasion;
  cc->num_active_ssb = num_active_ssb;
kn.raju's avatar
kn.raju committed
233

234
  LOG_D(NR_MAC,
kn.raju's avatar
kn.raju committed
235 236 237 238 239 240 241
        "Total available RO %d, num of active SSB %d: unused RO = %d association_period %u N_RA_sfn %u total_prach_occasions_per_config_period %u\n",
        cc->total_prach_occasions,
        cc->num_active_ssb,
        unused_RA_occasion,
        cc->max_association_period,
        N_RA_sfn,
        cc->total_prach_occasions_per_config_period);
242 243
}		
		
244 245
void schedule_nr_prach(module_id_t module_idP, frame_t frameP, sub_frame_t slotP)
{
246 247 248
  gNB_MAC_INST *gNB = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = gNB->common_channels;
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
249
  nfapi_nr_ul_tti_request_t *UL_tti_req = &RC.nrmac[module_idP]->UL_tti_req_ahead[0][slotP];
250
  nfapi_nr_config_request_scf_t *cfg = &RC.nrmac[module_idP]->config[0];
251

252
  if (is_nr_UL_slot(scc->tdd_UL_DL_ConfigurationCommon, slotP, cc->frame_type)) {
253

254 255 256 257 258 259 260 261 262 263 264 265 266
    uint8_t config_index = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric.prach_ConfigurationIndex;
    uint8_t mu,N_dur,N_t_slot,start_symbol = 0,N_RA_slot;
    uint16_t RA_sfn_index = -1;
    uint8_t config_period = 1;
    uint16_t format;
    int slot_index = 0;
    uint16_t prach_occasion_id = -1;

    if (scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg1_SubcarrierSpacing)
      mu = *scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg1_SubcarrierSpacing;
    else
      mu = scc->downlinkConfigCommon->frequencyInfoDL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing;

francescomani's avatar
francescomani committed
267 268
    int bwp_start = NRRIV2PRBOFFSET(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    uint8_t fdm = cfg->prach_config.num_prach_fd_occasions.value;
    // prach is scheduled according to configuration index and tables 6.3.3.2.2 to 6.3.3.2.4
    if ( get_nr_prach_info_from_index(config_index,
                                      (int)frameP,
                                      (int)slotP,
                                      scc->downlinkConfigCommon->frequencyInfoDL->absoluteFrequencyPointA,
                                      mu,
                                      cc->frame_type,
                                      &format,
                                      &start_symbol,
                                      &N_t_slot,
                                      &N_dur,
                                      &RA_sfn_index,
                                      &N_RA_slot,
                                      &config_period) ) {

      uint16_t format0 = format&0xff;      // first column of format from table
      uint16_t format1 = (format>>8)&0xff; // second column of format from table

      if (N_RA_slot > 1) { //more than 1 PRACH slot in a subframe
        if (slotP%2 == 1)
          slot_index = 1;
        else
          slot_index = 0;
      }else if (N_RA_slot <= 1) { //1 PRACH slot in a subframe
        slot_index = 0;
      }
296

297 298 299 300 301 302 303 304 305
      UL_tti_req->SFN = frameP;
      UL_tti_req->Slot = slotP;
      for (int fdm_index=0; fdm_index < fdm; fdm_index++) { // one structure per frequency domain occasion
        for (int td_index=0; td_index<N_t_slot; td_index++) {

          prach_occasion_id = (((frameP % (cc->max_association_period * config_period))/config_period) * cc->total_prach_occasions_per_config_period) +
                              (RA_sfn_index + slot_index) * N_t_slot * fdm + td_index * fdm + fdm_index;

          if((prach_occasion_id < cc->total_prach_occasions) && (td_index == 0)){
306 307
            AssertFatal(UL_tti_req->n_pdus < sizeof(UL_tti_req->pdus_list) / sizeof(UL_tti_req->pdus_list[0]),
                        "Invalid UL_tti_req->n_pdus %d\n", UL_tti_req->n_pdus);
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

            UL_tti_req->pdus_list[UL_tti_req->n_pdus].pdu_type = NFAPI_NR_UL_CONFIG_PRACH_PDU_TYPE;
            UL_tti_req->pdus_list[UL_tti_req->n_pdus].pdu_size = sizeof(nfapi_nr_prach_pdu_t);
            nfapi_nr_prach_pdu_t  *prach_pdu = &UL_tti_req->pdus_list[UL_tti_req->n_pdus].prach_pdu;
            memset(prach_pdu,0,sizeof(nfapi_nr_prach_pdu_t));
            UL_tti_req->n_pdus+=1;

            // filling the prach fapi structure
            prach_pdu->phys_cell_id = *scc->physCellId;
            prach_pdu->num_prach_ocas = N_t_slot;
            prach_pdu->prach_start_symbol = start_symbol;
            prach_pdu->num_ra = fdm_index;
            prach_pdu->num_cs = get_NCS(scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric.zeroCorrelationZoneConfig,
                                        format0,
                                        scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->restrictedSetConfig);

324
            LOG_D(NR_MAC, "Frame %d, Slot %d: Prach Occasion id = %u  fdm index = %u start symbol = %u slot index = %u subframe index = %u \n",
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
                  frameP, slotP,
                  prach_occasion_id, prach_pdu->num_ra,
                  prach_pdu->prach_start_symbol,
                  slot_index, RA_sfn_index);
            // SCF PRACH PDU format field does not consider A1/B1 etc. possibilities
            // We added 9 = A1/B1 10 = A2/B2 11 A3/B3
            if (format1!=0xff) {
              switch(format0) {
                case 0xa1:
                  prach_pdu->prach_format = 11;
                  break;
                case 0xa2:
                  prach_pdu->prach_format = 12;
                  break;
                case 0xa3:
                  prach_pdu->prach_format = 13;
                  break;
              default:
                AssertFatal(1==0,"Only formats A1/B1 A2/B2 A3/B3 are valid for dual format");
              }
            }
            else{
              switch(format0) {
                case 0:
                  prach_pdu->prach_format = 0;
                  break;
                case 1:
                  prach_pdu->prach_format = 1;
                  break;
                case 2:
                  prach_pdu->prach_format = 2;
                  break;
                case 3:
                  prach_pdu->prach_format = 3;
                  break;
                case 0xa1:
                  prach_pdu->prach_format = 4;
                  break;
                case 0xa2:
                  prach_pdu->prach_format = 5;
                  break;
                case 0xa3:
                  prach_pdu->prach_format = 6;
                  break;
                case 0xb1:
                  prach_pdu->prach_format = 7;
                  break;
                case 0xb4:
                  prach_pdu->prach_format = 8;
                  break;
                case 0xc0:
                  prach_pdu->prach_format = 9;
                  break;
                case 0xc2:
                  prach_pdu->prach_format = 10;
                  break;
              default:
                AssertFatal(1==0,"Invalid PRACH format");
              }
            }
          }
386
        }
387
      }
388 389 390 391 392 393 394 395 396

      // block resources in vrb_map_UL
      const NR_RACH_ConfigGeneric_t *rach_ConfigGeneric =
          &scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric;
      const uint8_t mu_pusch =
          scc->uplinkConfigCommon->frequencyInfoUL->scs_SpecificCarrierList.list.array[0]->subcarrierSpacing;
      const int16_t N_RA_RB = get_N_RA_RB(cfg->prach_config.prach_sub_c_spacing.value, mu_pusch);
      uint16_t *vrb_map_UL = &cc->vrb_map_UL[slotP * MAX_BWP_SIZE];
      for (int i = 0; i < N_RA_RB * fdm; ++i)
francescomani's avatar
francescomani committed
397
        vrb_map_UL[bwp_start + rach_ConfigGeneric->msg1_FrequencyStart + i] |= SL_to_bitmap(start_symbol, N_t_slot*N_dur);
398 399 400 401 402 403
    }
  }
}

void nr_schedule_msg2(uint16_t rach_frame, uint16_t rach_slot,
                      uint16_t *msg2_frame, uint16_t *msg2_slot,
404
                      int mu, NR_ServingCellConfigCommon_t *scc,
francescomani's avatar
francescomani committed
405
                      frame_type_t frame_type,
406
                      uint16_t monitoring_slot_period,
407
                      uint16_t monitoring_offset,uint8_t beam_index,
408
                      uint8_t num_active_ssb,
409
                      int16_t *tdd_beam_association, int sl_ahead){
410 411 412 413 414

  // preferentially we schedule the msg2 in the mixed slot or in the last dl slot
  // if they are allowed by search space configuration
  uint8_t response_window = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric.ra_ResponseWindow;
  uint8_t slot_window;
415
  const int n_slots_frame = nr_slots_per_frame[mu];
416
  const NR_TDD_UL_DL_Pattern_t *tdd = scc->tdd_UL_DL_ConfigurationCommon ? &scc->tdd_UL_DL_ConfigurationCommon->pattern1 : NULL;
417
  // number of mixed slot or of last dl slot if there is no mixed slot
418
  uint8_t last_dl_slot_period = n_slots_frame-1;
419
  // lenght of tdd period in slots
420
  uint8_t tdd_period_slot = n_slots_frame;
421

422 423 424
  if (tdd) {
    last_dl_slot_period = tdd->nrofDownlinkSymbols == 0? (tdd->nrofDownlinkSlots-1) : tdd->nrofDownlinkSlots;
    tdd_period_slot = n_slots_frame/get_nb_periods_per_frame(tdd->dl_UL_TransmissionPeriodicity);
425
  }
426 427
  else{
    if(frame_type == TDD)
428
      AssertFatal(frame_type == FDD, "Dynamic TDD not handled yet\n");
429
  }
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459


  switch(response_window){
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl1:
      slot_window = 1;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl2:
      slot_window = 2;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl4:
      slot_window = 4;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl8:
      slot_window = 8;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl10:
      slot_window = 10;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl20:
      slot_window = 20;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl40:
      slot_window = 40;
      break;
    case NR_RACH_ConfigGeneric__ra_ResponseWindow_sl80:
      slot_window = 80;
      break;
    default:
      AssertFatal(1==0,"Invalid response window value %d\n",response_window);
  }
cig's avatar
cig committed
460
  AssertFatal(slot_window<=nr_slots_per_frame[mu],"Msg2 response window needs to be lower or equal to 10ms");
461 462

  // slot and frame limit to transmit msg2 according to response window
cig's avatar
cig committed
463
  uint8_t slot_limit = (rach_slot + slot_window)%nr_slots_per_frame[mu];
Thomas Schlichter's avatar
Thomas Schlichter committed
464
  uint16_t frame_limit = rach_frame + (rach_slot + slot_window)/nr_slots_per_frame[mu];
465

466
  // computing start of next period
laurent's avatar
laurent committed
467 468
  uint8_t start_next_period = rach_slot-(rach_slot%tdd_period_slot)+tdd_period_slot;
  int eff_slot = start_next_period + last_dl_slot_period; // initializing scheduling of slot to next mixed (or last dl) slot
Thomas Schlichter's avatar
Thomas Schlichter committed
469

470
  // we can't schedule msg2 before sl_ahead since prach
francescomani's avatar
francescomani committed
471
  while ((eff_slot-rach_slot)<=sl_ahead) {
laurent's avatar
laurent committed
472
    eff_slot += tdd_period_slot;
473
  }
Thomas Schlichter's avatar
Thomas Schlichter committed
474 475

  int FR = *scc->downlinkConfigCommon->frequencyInfoDL->frequencyBandList.list.array[0] >= 257 ? nr_FR2 : nr_FR1;
476
  if (FR==nr_FR2) {
laurent's avatar
laurent committed
477
    int num_tdd_period = (eff_slot%nr_slots_per_frame[mu])/tdd_period_slot;
478
    while((tdd_beam_association[num_tdd_period]!=-1)&&(tdd_beam_association[num_tdd_period]!=beam_index)) {
laurent's avatar
laurent committed
479 480
      eff_slot += tdd_period_slot;
      num_tdd_period = (eff_slot % nr_slots_per_frame[mu])/tdd_period_slot;
481 482 483 484 485
    }
    if(tdd_beam_association[num_tdd_period] == -1)
      tdd_beam_association[num_tdd_period] = beam_index;
  }

Thomas Schlichter's avatar
Thomas Schlichter committed
486 487 488
  *msg2_frame = rach_frame + eff_slot / nr_slots_per_frame[mu];
  *msg2_slot = eff_slot % nr_slots_per_frame[mu];

489 490
  // go to previous slot if the current scheduled slot is beyond the response window
  // and if the slot is not among the PDCCH monitored ones (38.213 10.1)
francescomani's avatar
francescomani committed
491 492 493
  while (*msg2_frame > frame_limit
         || (*msg2_frame == frame_limit && *msg2_slot > slot_limit)
         || ((*msg2_frame * nr_slots_per_frame[mu] + *msg2_slot - monitoring_offset) % monitoring_slot_period != 0)) {
francescomani's avatar
francescomani committed
494

495 496
    if((frame_type == FDD) || ((*msg2_slot%tdd_period_slot) > 0)) {
      if (*msg2_slot==0) {
Thomas Schlichter's avatar
Thomas Schlichter committed
497
        (*msg2_frame)--;
498 499 500 501
        *msg2_slot = nr_slots_per_frame[mu] - 1;
      }
      else
        (*msg2_slot)--;
francescomani's avatar
francescomani committed
502
    }
503 504 505
    else
      AssertFatal(1==0,"No available DL slot to schedule msg2 has been found");
  }
Thomas Schlichter's avatar
Thomas Schlichter committed
506 507 508

  // calculate frame number considering wrap-around
  *msg2_frame = *msg2_frame % 1024;
cig's avatar
cig committed
509
}
510

511

512 513 514 515 516
void nr_initiate_ra_proc(module_id_t module_idP,
                         int CC_id,
                         frame_t frameP,
                         sub_frame_t slotP,
                         uint16_t preamble_index,
517 518
                         uint8_t freq_index,
                         uint8_t symbol,
519 520
                         int16_t timing_offset){

521
  uint8_t ul_carrier_id = 0; // 0 for NUL 1 for SUL
522

523
  uint16_t msg2_frame, msg2_slot,monitoring_slot_period,monitoring_offset;
cig's avatar
cig committed
524 525
  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];
526
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
francescomani's avatar
francescomani committed
527
  frame_type_t frame_type = cc->frame_type;
528

529
  uint8_t total_RApreambles = MAX_NUM_NR_PRACH_PREAMBLES;
530
  uint8_t  num_ssb_per_RO = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->ssb_perRACH_OccasionAndCB_PreamblesPerSSB->present;
531
  int pr_found;
532

kn.raju's avatar
kn.raju committed
533
  if( scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->totalNumberOfRA_Preambles != NULL)
534
    total_RApreambles = *scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->totalNumberOfRA_Preambles;
535

kn.raju's avatar
kn.raju committed
536 537 538
  if(num_ssb_per_RO > 3) { /*num of ssb per RO >= 1*/
    num_ssb_per_RO -= 3;
    total_RApreambles = total_RApreambles/num_ssb_per_RO ;
539
  }
540

541
  for (int i = 0; i < NR_NB_RA_PROC_MAX; i++) {
francescomani's avatar
francescomani committed
542

543
    NR_RA_t *ra = &cc->ra[i];
francescomani's avatar
francescomani committed
544
    if (ra->state != RA_IDLE)
545
      continue;
546

francescomani's avatar
francescomani committed
547
    pr_found = 0;
rmagueta's avatar
rmagueta committed
548

francescomani's avatar
francescomani committed
549 550 551 552 553 554 555
    for(int j = 0; j < ra->preambles.num_preambles; j++) {
      //check if the preamble received correspond to one of the listed or configured preambles
      if (preamble_index == ra->preambles.preamble_list[j]) {
        if (ra->rnti == 0 && get_softmodem_params()->nsa)
          continue;
        pr_found=1;
        break;
556
      }
francescomani's avatar
francescomani committed
557 558 559 560
    }
    if (pr_found == 0) {
       continue;
    }
561

francescomani's avatar
francescomani committed
562
    uint16_t ra_rnti;
563

francescomani's avatar
francescomani committed
564 565 566 567 568 569 570 571
    // ra_rnti from 5.1.3 in 38.321
    // FK: in case of long PRACH the phone seems to expect the subframe number instead of the slot number here.
    if (scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->prach_RootSequenceIndex.present
        == NR_RACH_ConfigCommon__prach_RootSequenceIndex_PR_l839)
      ra_rnti = 1 + symbol + (9 /*slotP*/ * 14) + (freq_index * 14 * 80) + (ul_carrier_id * 14 * 80 * 8);
    else
      ra_rnti = 1 + symbol + (slotP * 14) + (freq_index * 14 * 80) + (ul_carrier_id * 14 * 80 * 8);

572 573
    // Configure RA BWP
    configure_UE_BWP(nr_mac, scc, NULL, ra, NULL);
574

francescomani's avatar
francescomani committed
575
    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_INITIATE_RA_PROC, 1);
576

francescomani's avatar
francescomani committed
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    LOG_D(NR_MAC,
          "[gNB %d][RAPROC] CC_id %d Frame %d, Slot %d  Initiating RA procedure for preamble index %d\n",
          module_idP,
          CC_id,
          frameP,
          slotP,
          preamble_index);

    uint8_t beam_index = ssb_index_from_prach(module_idP, frameP, slotP, preamble_index, freq_index, symbol);

    // the UE sent a RACH either for starting RA procedure or RA procedure failed and UE retries
    if (ra->cfra) {
      // if the preamble received correspond to one of the listed
      if (!(preamble_index == ra->preambles.preamble_list[beam_index])) {
        LOG_E(
            NR_MAC,
            "[gNB %d][RAPROC] FAILURE: preamble %d does not correspond to any of the ones in rach_ConfigDedicated\n",
594 595
            module_idP,
            preamble_index);
francescomani's avatar
francescomani committed
596
        continue; // if the PRACH preamble does not correspond to any of the ones sent through RRC abort RA proc
Francesco Mani's avatar
Francesco Mani committed
597
      }
francescomani's avatar
francescomani committed
598 599 600 601 602
    }
    LOG_D(NR_MAC, "Frame %d, Slot %d: Activating RA process \n", frameP, slotP);
    ra->state = Msg2;
    ra->timing_offset = timing_offset;
    ra->preamble_slot = slotP;
603

francescomani's avatar
francescomani committed
604 605 606 607 608 609 610
    // retrieving ra pdcch monitoring period and offset
    find_monitoring_periodicity_offset_common(ra->ra_ss, &monitoring_slot_period, &monitoring_offset);

    nr_schedule_msg2(frameP,
                     slotP,
                     &msg2_frame,
                     &msg2_slot,
611
                     ra->DL_BWP.scs,
francescomani's avatar
francescomani committed
612 613 614 615 616 617 618
                     scc,
                     frame_type,
                     monitoring_slot_period,
                     monitoring_offset,
                     beam_index,
                     cc->num_active_ssb,
                     nr_mac->tdd_beam_association,
619
                     nr_mac->if_inst->sl_ahead);
francescomani's avatar
francescomani committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

    ra->Msg2_frame = msg2_frame;
    ra->Msg2_slot = msg2_slot;

    LOG_D(NR_MAC, "%s() Msg2[%04d%d] SFN/SF:%04d%d\n", __FUNCTION__, ra->Msg2_frame, ra->Msg2_slot, frameP, slotP);

    int loop = 0;
    if (ra->rnti == 0) { // This condition allows for the usage of a preconfigured rnti for the CFRA
      do {
        ra->rnti = (taus() % 65518) + 1;
        loop++;
      } while (loop != 100
               && !((find_nr_UE(&nr_mac->UE_info, ra->rnti) == NULL) && (find_nr_RA_id(module_idP, CC_id, ra->rnti) == -1)
                    && ra->rnti >= 1 && ra->rnti <= 65519));
      if (loop == 100) {
        LOG_E(NR_MAC, "%s:%d:%s: [RAPROC] initialisation random access aborted\n", __FILE__, __LINE__, __FUNCTION__);
        abort();
637
      }
cig's avatar
cig committed
638
    }
639

francescomani's avatar
francescomani committed
640 641
    ra->RA_rnti = ra_rnti;
    ra->preamble_index = preamble_index;
francescomani's avatar
francescomani committed
642
    ra->beam_id = cc->ssb_index[beam_index];
francescomani's avatar
francescomani committed
643 644 645 646 647 648 649 650 651 652

    LOG_I(NR_MAC,
          "[gNB %d][RAPROC] CC_id %d Frame %d Activating Msg2 generation in frame %d, slot %d using RA rnti %x SSB, new rnti %04x "
          "index %u RA index %d\n",
          module_idP,
          CC_id,
          frameP,
          ra->Msg2_frame,
          ra->Msg2_slot,
          ra->RA_rnti,
francescomani's avatar
francescomani committed
653
          ra->rnti,
francescomani's avatar
francescomani committed
654 655
          cc->ssb_index[beam_index],
          i);
656

francescomani's avatar
francescomani committed
657
    return;
658
  }
659
  LOG_E(NR_MAC, "[gNB %d][RAPROC] FAILURE: CC_id %d Frame %d initiating RA procedure for preamble index %d\n", module_idP, CC_id, frameP, preamble_index);
660

cig's avatar
cig committed
661
  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_INITIATE_RA_PROC, 0);
662 663
}

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
void nr_schedule_RA(module_id_t module_idP, frame_t frameP, sub_frame_t slotP) {

  gNB_MAC_INST *mac = RC.nrmac[module_idP];

  start_meas(&mac->schedule_ra);
  for (int CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {
    NR_COMMON_channels_t *cc = &mac->common_channels[CC_id];
    for (int i = 0; i < NR_NB_RA_PROC_MAX; i++) {
      NR_RA_t *ra = &cc->ra[i];
      LOG_D(NR_MAC, "RA[state:%d]\n", ra->state);
      switch (ra->state) {
        case Msg2:
          nr_generate_Msg2(module_idP, CC_id, frameP, slotP, ra);
          break;
        case Msg3_retransmission:
          nr_generate_Msg3_retransmission(module_idP, CC_id, frameP, slotP, ra);
          break;
        case Msg4:
          nr_generate_Msg4(module_idP, CC_id, frameP, slotP, ra);
          break;
        case WAIT_Msg4_ACK:
          nr_check_Msg4_Ack(module_idP, CC_id, frameP, slotP, ra);
          break;
        default:
          break;
689 690
      }
    }
cig's avatar
cig committed
691
  }
692 693 694 695 696 697 698 699 700
  stop_meas(&mac->schedule_ra);
}


void nr_generate_Msg3_retransmission(module_id_t module_idP, int CC_id, frame_t frame, sub_frame_t slot, NR_RA_t *ra) {

  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
francescomani's avatar
francescomani committed
701
  NR_UE_UL_BWP_t *ul_bwp = &ra->UL_BWP;
702

francescomani's avatar
francescomani committed
703 704
  NR_PUSCH_TimeDomainResourceAllocationList_t *pusch_TimeDomainAllocationList = ul_bwp->tdaList;
  int mu = ul_bwp->scs;
705 706 707 708 709 710 711 712
  uint8_t K2 = *pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->k2;
  const int sched_frame = frame + (slot + K2 >= nr_slots_per_frame[mu]);
  const int sched_slot = (slot + K2) % nr_slots_per_frame[mu];

  if (is_xlsch_in_slot(RC.nrmac[module_idP]->ulsch_slot_bitmap[sched_slot / 64], sched_slot)) {
    // beam association for FR2
    int16_t *tdd_beam_association = nr_mac->tdd_beam_association;
    if (*scc->downlinkConfigCommon->frequencyInfoDL->frequencyBandList.list.array[0] >= 257) {
713
      // FR2
714
      const int n_slots_frame = nr_slots_per_frame[mu];
715
      const NR_TDD_UL_DL_Pattern_t *tdd = scc->tdd_UL_DL_ConfigurationCommon ? &scc->tdd_UL_DL_ConfigurationCommon->pattern1 : NULL;
716 717
      AssertFatal(tdd,"Dynamic TDD not handled yet\n");
      uint8_t tdd_period_slot = n_slots_frame/get_nb_periods_per_frame(tdd->dl_UL_TransmissionPeriodicity);
718
      int num_tdd_period = sched_slot/tdd_period_slot;
719

720 721 722 723 724 725 726
      if((tdd_beam_association[num_tdd_period]!=-1)&&(tdd_beam_association[num_tdd_period]!=ra->beam_id))
        return; // can't schedule retransmission in this slot
      else
        tdd_beam_association[num_tdd_period] = ra->beam_id;
    }

    int fh = 0;
727
    int startSymbolAndLength = pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->startSymbolAndLength;
728 729
    int StartSymbolIndex, NrOfSymbols;
    SLIV2SL(startSymbolAndLength, &StartSymbolIndex, &NrOfSymbols);
730
    int mappingtype = pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->mappingType;
731

732
    uint16_t *vrb_map_UL = &RC.nrmac[module_idP]->common_channels[CC_id].vrb_map_UL[sched_slot * MAX_BWP_SIZE];
733

734 735 736
    const int BWPSize = NRRIV2BW(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
    const int BWPStart = NRRIV2PRBOFFSET(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);

737
    int rbStart = 0;
738
    for (int i = 0; (i < ra->msg3_nb_rb) && (rbStart <= (BWPSize - ra->msg3_nb_rb)); i++) {
739
      if (vrb_map_UL[rbStart + BWPStart + i]&SL_to_bitmap(StartSymbolIndex, NrOfSymbols)) {
740 741
        rbStart += i;
        i = 0;
742 743
      }
    }
744
    if (rbStart > (BWPSize - ra->msg3_nb_rb)) {
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
      // cannot find free vrb_map for msg3 retransmission in this slot
      return;
    }

    LOG_I(NR_MAC, "[gNB %d][RAPROC] Frame %d, Slot %d : CC_id %d Scheduling retransmission of Msg3 in (%d,%d)\n",
          module_idP, frame, slot, CC_id, sched_frame, sched_slot);

    nfapi_nr_ul_tti_request_t *future_ul_tti_req = &RC.nrmac[module_idP]->UL_tti_req_ahead[CC_id][sched_slot];
    AssertFatal(future_ul_tti_req->SFN == sched_frame
                && future_ul_tti_req->Slot == sched_slot,
                "future UL_tti_req's frame.slot %d.%d does not match PUSCH %d.%d\n",
                future_ul_tti_req->SFN,
                future_ul_tti_req->Slot,
                sched_frame,
                sched_slot);
760 761 762
    AssertFatal(future_ul_tti_req->n_pdus <
                sizeof(future_ul_tti_req->pdus_list) / sizeof(future_ul_tti_req->pdus_list[0]),
                "Invalid future_ul_tti_req->n_pdus %d\n", future_ul_tti_req->n_pdus);
763 764 765 766 767 768
    future_ul_tti_req->pdus_list[future_ul_tti_req->n_pdus].pdu_type = NFAPI_NR_UL_CONFIG_PUSCH_PDU_TYPE;
    future_ul_tti_req->pdus_list[future_ul_tti_req->n_pdus].pdu_size = sizeof(nfapi_nr_pusch_pdu_t);
    nfapi_nr_pusch_pdu_t *pusch_pdu = &future_ul_tti_req->pdus_list[future_ul_tti_req->n_pdus].pusch_pdu;
    memset(pusch_pdu, 0, sizeof(nfapi_nr_pusch_pdu_t));

    fill_msg3_pusch_pdu(pusch_pdu, scc,
769
                        ra->msg3_round,
770
                        startSymbolAndLength,
771
                        ra->rnti, mu,
772
                        BWPSize, BWPStart,
773 774 775 776 777 778
                        mappingtype, fh,
                        rbStart, ra->msg3_nb_rb);
    future_ul_tti_req->n_pdus += 1;

    // generation of DCI 0_0 to schedule msg3 retransmission
    NR_SearchSpace_t *ss = ra->ra_ss;
779
    NR_ControlResourceSet_t *coreset = ra->coreset;
780 781 782 783 784
    AssertFatal(coreset!=NULL,"Coreset cannot be null for RA-Msg3 retransmission\n");

    nfapi_nr_ul_dci_request_t *ul_dci_req = &nr_mac->UL_dci_req[CC_id];

    const int coresetid = coreset->controlResourceSetId;
785
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_rel15 = nr_mac->pdcch_pdu_idx[CC_id][coresetid];
786 787 788 789 790 791 792
    if (!pdcch_pdu_rel15) {
      nfapi_nr_ul_dci_request_pdus_t *ul_dci_request_pdu = &ul_dci_req->ul_dci_pdu_list[ul_dci_req->numPdus];
      memset(ul_dci_request_pdu, 0, sizeof(nfapi_nr_ul_dci_request_pdus_t));
      ul_dci_request_pdu->PDUType = NFAPI_NR_DL_TTI_PDCCH_PDU_TYPE;
      ul_dci_request_pdu->PDUSize = (uint8_t)(2+sizeof(nfapi_nr_dl_tti_pdcch_pdu));
      pdcch_pdu_rel15 = &ul_dci_request_pdu->pdcch_pdu.pdcch_pdu_rel15;
      ul_dci_req->numPdus += 1;
793
      nr_configure_pdcch(pdcch_pdu_rel15, coreset, false, &ra->sched_pdcch);
794
      nr_mac->pdcch_pdu_idx[CC_id][coresetid] = pdcch_pdu_rel15;
795 796 797
    }

    uint8_t aggregation_level;
798 799 800 801 802 803 804
    int CCEIndex = get_cce_index(nr_mac,
                                 CC_id, slot, 0,
                                 &aggregation_level,
                                 ss,
                                 coreset,
                                 &ra->sched_pdcch,
                                 true);
805
    if (CCEIndex < 0) {
806
      LOG_E(NR_MAC, "%s(): cannot find free CCE for RA RNTI 0x%04x!\n", __func__, ra->rnti);
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
      return;
    }

    // Fill PDCCH DL DCI PDU
    nfapi_nr_dl_dci_pdu_t *dci_pdu = &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci];
    pdcch_pdu_rel15->numDlDci++;
    dci_pdu->RNTI = ra->rnti;
    dci_pdu->ScramblingId = *scc->physCellId;
    dci_pdu->ScramblingRNTI = 0;
    dci_pdu->AggregationLevel = aggregation_level;
    dci_pdu->CceIndex = CCEIndex;
    dci_pdu->beta_PDCCH_1_0 = 0;
    dci_pdu->powerControlOffsetSS = 1;

    dci_pdu_rel15_t uldci_payload;
    memset(&uldci_payload, 0, sizeof(uldci_payload));

824 825
    const NR_SIB1_t *sib1 = cc->sib1 ? cc->sib1->message.choice.c1->choice.systemInformationBlockType1 : NULL;
    config_uldci(sib1,
826 827 828
                 scc,
                 pusch_pdu,
                 &uldci_payload,
829
                 NULL,
830 831
                 ra->Msg3_tda_id,
                 ra->msg3_TPC,
832
                 1, // Not toggling NDI in msg3 retransmissions
833
                 &ra->UL_BWP);
834 835 836

    fill_dci_pdu_rel15(scc,
                       ra->CellGroup,
837
                       &ra->DL_BWP,
838 839 840 841 842
                       dci_pdu,
                       &uldci_payload,
                       NR_UL_DCI_FORMAT_0_0,
                       NR_RNTI_TC,
                       pusch_pdu->bwp_size,
francescomani's avatar
francescomani committed
843
                       ul_bwp->bwp_id,
844
                       coreset,
845
                       nr_mac->cset0_bwp_size);
846 847

    // Mark the corresponding RBs as used
848 849 850

    fill_pdcch_vrb_map(nr_mac,
                       CC_id,
851
                       &ra->sched_pdcch,
852 853 854
                       CCEIndex,
                       aggregation_level);

855
    for (int rb = 0; rb < ra->msg3_nb_rb; rb++) {
856
      vrb_map_UL[rbStart + BWPStart + rb] |= SL_to_bitmap(StartSymbolIndex, NrOfSymbols);
857 858 859 860
    }

    // reset state to wait msg3
    ra->state = WAIT_Msg3;
francescomani's avatar
francescomani committed
861 862
    ra->Msg3_frame = sched_frame;
    ra->Msg3_slot = sched_slot;
863

cig's avatar
cig committed
864
  }
865
}
866

867 868 869
void nr_get_Msg3alloc(module_id_t module_id,
                      int CC_id,
                      NR_ServingCellConfigCommon_t *scc,
870 871
                      sub_frame_t current_slot,
                      frame_t current_frame,
872 873
                      NR_RA_t *ra,
                      int16_t *tdd_beam_association) {
874

875 876
  // msg3 is scheduled in mixed slot in the following TDD period

877
  uint16_t msg3_nb_rb = 8; // sdu has 6 or 8 bytes
francescomani's avatar
francescomani committed
878
  frame_type_t frame_type = RC.nrmac[module_id]->common_channels->frame_type;
879

francescomani's avatar
francescomani committed
880
  NR_UE_UL_BWP_t *ul_bwp = &ra->UL_BWP;
881

francescomani's avatar
francescomani committed
882
  int mu = ul_bwp->scs;
883 884 885
  int StartSymbolIndex = 0;
  int NrOfSymbols = 0;
  int startSymbolAndLength = 0;
francescomani's avatar
francescomani committed
886
  int abs_slot = 0;
Raymond Knopp's avatar
Raymond Knopp committed
887
  int Msg3maxsymb = 14, Msg3start = 0;
888 889
  ra->Msg3_tda_id = 16; // initialization to a value above limit

francescomani's avatar
francescomani committed
890
  NR_PUSCH_TimeDomainResourceAllocationList_t *pusch_TimeDomainAllocationList = ul_bwp->tdaList;
891

892 893
  const NR_TDD_UL_DL_Pattern_t *tdd = scc->tdd_UL_DL_ConfigurationCommon ? &scc->tdd_UL_DL_ConfigurationCommon->pattern1 : NULL;
  const int n_slots_frame = nr_slots_per_frame[mu];
894
  uint8_t k2 = 0;
895
  if (frame_type == TDD) {
896
    int msg3_slot = get_first_ul_slot(tdd->nrofDownlinkSlots, tdd->nrofDownlinkSymbols, tdd->nrofUplinkSymbols);
897 898 899 900 901 902 903
    if (tdd->nrofUplinkSymbols != 0) {
      if (tdd->nrofUplinkSymbols < 3)
        msg3_slot++; // we can't trasmit msg3 in mixed slot if there are less than 3 symbols
      else {
        Msg3maxsymb = tdd->nrofUplinkSymbols;
        Msg3start = 14 - tdd->nrofUplinkSymbols;
      }
Raymond Knopp's avatar
Raymond Knopp committed
904
    }
905 906
    const int nb_periods_per_frame = get_nb_periods_per_frame(tdd->dl_UL_TransmissionPeriodicity);
    const int nb_slots_per_period = ((1<<mu)*10)/nb_periods_per_frame;
907
    for (int i=0; i<pusch_TimeDomainAllocationList->list.count; i++) {
908 909
      startSymbolAndLength = pusch_TimeDomainAllocationList->list.array[i]->startSymbolAndLength;
      SLIV2SL(startSymbolAndLength, &StartSymbolIndex, &NrOfSymbols);
910
      k2 = *pusch_TimeDomainAllocationList->list.array[i]->k2;
Raymond Knopp's avatar
Raymond Knopp committed
911 912
      LOG_D(NR_MAC,"Checking Msg3 TDA %d for Msg3_slot %d Msg3_start %d Msg3_nsymb %d: k2 %d, sliv %d,S %d L %d\n",
            i, msg3_slot, Msg3start, Msg3maxsymb, (int)k2, (int)pusch_TimeDomainAllocationList->list.array[i]->startSymbolAndLength, StartSymbolIndex, NrOfSymbols);
913
      // we want to transmit in the uplink symbols of mixed slot or the first uplink slot
francescomani's avatar
francescomani committed
914 915
      abs_slot = (current_slot + k2 + DELTA[mu]);
      int temp_slot = abs_slot % nr_slots_per_frame[mu]; // msg3 slot according to 8.3 in 38.213
916
      if ((temp_slot % nb_slots_per_period) == msg3_slot &&
Raymond Knopp's avatar
Raymond Knopp committed
917 918 919
          is_xlsch_in_slot(RC.nrmac[module_id]->ulsch_slot_bitmap[temp_slot / 64], temp_slot) &&
          StartSymbolIndex == Msg3start &&
          NrOfSymbols <= Msg3maxsymb) {
920 921 922 923 924
        ra->Msg3_tda_id = i;
        ra->msg3_startsymb = StartSymbolIndex;
        ra->msg3_nrsymb = NrOfSymbols;
        ra->Msg3_slot = temp_slot;
        break;
925
      }
926
    }
927
    AssertFatal(ra->Msg3_tda_id < 16, "Couldn't find an appropriate TD allocation for Msg3\n");
928
  }
929 930 931
  else {
    ra->Msg3_tda_id = 0;
    k2 = *pusch_TimeDomainAllocationList->list.array[0]->k2;
francescomani's avatar
francescomani committed
932 933
    abs_slot = current_slot + k2 + DELTA[mu]; // msg3 slot according to 8.3 in 38.213
    ra->Msg3_slot = abs_slot % nr_slots_per_frame[mu];
934
  }
935

936
  AssertFatal(ra->Msg3_tda_id<16,"Unable to find Msg3 time domain allocation in list\n");
937

francescomani's avatar
francescomani committed
938
  if (n_slots_frame > abs_slot)
939 940
    ra->Msg3_frame = current_frame;
  else
francescomani's avatar
francescomani committed
941
    ra->Msg3_frame = (current_frame + (abs_slot / n_slots_frame)) % 1024;
942

943 944
  // beam association for FR2
  if (*scc->downlinkConfigCommon->frequencyInfoDL->frequencyBandList.list.array[0] >= 257) {
945 946
    AssertFatal(tdd,"Dynamic TDD not handled yet\n");
    uint8_t tdd_period_slot = n_slots_frame/get_nb_periods_per_frame(tdd->dl_UL_TransmissionPeriodicity);
947 948 949 950 951 952 953
    int num_tdd_period = ra->Msg3_slot/tdd_period_slot;
    if((tdd_beam_association[num_tdd_period]!=-1)&&(tdd_beam_association[num_tdd_period]!=ra->beam_id))
      AssertFatal(1==0,"Cannot schedule MSG3\n");
    else
      tdd_beam_association[num_tdd_period] = ra->beam_id;
  }

954
  LOG_I(NR_MAC, "[RAPROC] Msg3 slot %d: current slot %u Msg3 frame %u k2 %u Msg3_tda_id %u\n", ra->Msg3_slot, current_slot, ra->Msg3_frame, k2,ra->Msg3_tda_id);
955
  uint16_t *vrb_map_UL =
cig's avatar
cig committed
956
      &RC.nrmac[module_id]->common_channels[CC_id].vrb_map_UL[ra->Msg3_slot * MAX_BWP_SIZE];
957 958 959 960

  int bwpSize = NRRIV2BW(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
  int bwpStart = NRRIV2PRBOFFSET(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);

francescomani's avatar
francescomani committed
961 962 963
  if (bwpSize != ul_bwp->BWPSize || bwpStart != ul_bwp->BWPStart) {
    int act_bwp_start = ul_bwp->BWPStart;
    int act_bwp_size  = ul_bwp->BWPSize;
964
    if (!((bwpStart >= act_bwp_start) && ((bwpStart+bwpSize) <= (act_bwp_start+act_bwp_size))))
965 966
      bwpStart = act_bwp_start;
  }
rmagueta's avatar
rmagueta committed
967

968
  /* search msg3_nb_rb free RBs */
969 970
  int rbSize = 0;
  int rbStart = 0;
rmagueta's avatar
rmagueta committed
971
  while (rbSize < msg3_nb_rb) {
972 973
    rbStart += rbSize; /* last iteration rbSize was not enough, skip it */
    rbSize = 0;
974
    while (rbStart < bwpSize &&
975
           (vrb_map_UL[rbStart + bwpStart]&SL_to_bitmap(StartSymbolIndex, NrOfSymbols)))
976
      rbStart++;
rmagueta's avatar
rmagueta committed
977
    AssertFatal(rbStart < bwpSize - msg3_nb_rb, "no space to allocate Msg 3 for RA!\n");
978
    while (rbStart + rbSize < bwpSize
979
           && !(vrb_map_UL[rbStart + bwpStart + rbSize]&SL_to_bitmap(StartSymbolIndex, NrOfSymbols))
rmagueta's avatar
rmagueta committed
980
           && rbSize < msg3_nb_rb)
981
      rbSize++;
982
  }
rmagueta's avatar
rmagueta committed
983
  ra->msg3_nb_rb = msg3_nb_rb;
984
  ra->msg3_first_rb = rbStart;
985
  ra->msg3_bwp_start = bwpStart;
986 987
}

988 989 990

void fill_msg3_pusch_pdu(nfapi_nr_pusch_pdu_t *pusch_pdu,
                         NR_ServingCellConfigCommon_t *scc,
991
                         int round,
992 993 994 995 996 997 998
                         int startSymbolAndLength,
                         rnti_t rnti, int scs,
                         int bwp_size, int bwp_start,
                         int mappingtype, int fh,
                         int msg3_first_rb, int msg3_nb_rb) {

  int start_symbol_index,nr_of_symbols;
999

1000
  SLIV2SL(startSymbolAndLength, &start_symbol_index, &nr_of_symbols);
1001
  int mcsindex = -1; // init value
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

  pusch_pdu->pdu_bit_map = PUSCH_PDU_BITMAP_PUSCH_DATA;
  pusch_pdu->rnti = rnti;
  pusch_pdu->handle = 0;
  pusch_pdu->bwp_start = bwp_start;
  pusch_pdu->bwp_size = bwp_size;
  pusch_pdu->subcarrier_spacing = scs;
  pusch_pdu->cyclic_prefix = 0;
  pusch_pdu->mcs_table = 0;
  if (scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->msg3_transformPrecoder == NULL)
    pusch_pdu->transform_precoding = 1;
  else
    pusch_pdu->transform_precoding = 0;
  pusch_pdu->data_scrambling_id = *scc->physCellId;
  pusch_pdu->nrOfLayers = 1;
  pusch_pdu->ul_dmrs_symb_pos = get_l_prime(nr_of_symbols,mappingtype,pusch_dmrs_pos2,pusch_len1,start_symbol_index, scc->dmrs_TypeA_Position);
1018
  LOG_D(NR_MAC, "MSG3 start_sym:%d NR Symb:%d mappingtype:%d, ul_dmrs_symb_pos:%x\n", start_symbol_index, nr_of_symbols, mappingtype, pusch_pdu->ul_dmrs_symb_pos);
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  pusch_pdu->dmrs_config_type = 0;
  pusch_pdu->ul_dmrs_scrambling_id = *scc->physCellId; //If provided and the PUSCH is not a msg3 PUSCH, otherwise, L2 should set this to physical cell id.
  pusch_pdu->scid = 0; //DMRS sequence initialization [TS38.211, sec 6.4.1.1.1]. Should match what is sent in DCI 0_1, otherwise set to 0.
  pusch_pdu->dmrs_ports = 1;  // 6.2.2 in 38.214 only port 0 to be used
  pusch_pdu->num_dmrs_cdm_grps_no_data = 2;  // no data in dmrs symbols as in 6.2.2 in 38.214
  pusch_pdu->resource_alloc = 1; //type 1
  pusch_pdu->rb_start = msg3_first_rb;
  if (msg3_nb_rb > pusch_pdu->bwp_size)
    AssertFatal(1==0,"MSG3 allocated number of RBs exceed the BWP size\n");
  else
    pusch_pdu->rb_size = msg3_nb_rb;
  pusch_pdu->vrb_to_prb_mapping = 0;

  pusch_pdu->frequency_hopping = fh;
1033 1034 1035 1036
  //pusch_pdu->tx_direct_current_location;
  //The uplink Tx Direct Current location for the carrier. Only values in the value range of this field between 0 and 3299,
  //which indicate the subcarrier index within the carrier corresponding 1o the numerology of the corresponding uplink BWP and value 3300,
  //which indicates "Outside the carrier" and value 3301, which indicates "Undetermined position within the carrier" are used. [TS38.331, UplinkTxDirectCurrentBWP IE]
1037 1038 1039 1040 1041
  pusch_pdu->uplink_frequency_shift_7p5khz = 0;
  //Resource Allocation in time domain
  pusch_pdu->start_symbol_index = start_symbol_index;
  pusch_pdu->nr_of_symbols = nr_of_symbols;
  //Optional Data only included if indicated in pduBitmap
1042
  pusch_pdu->pusch_data.rv_index = nr_rv_round_map[round%4];
1043
  pusch_pdu->pusch_data.harq_process_id = 0;
1044
  pusch_pdu->pusch_data.new_data_indicator = (round == 0) ? 1 : 0;;
1045
  pusch_pdu->pusch_data.num_cb = 0;
francescomani's avatar
francescomani committed
1046 1047 1048
  int num_dmrs_symb = 0;
  for(int i = start_symbol_index; i < start_symbol_index+nr_of_symbols; i++)
    num_dmrs_symb += (pusch_pdu->ul_dmrs_symb_pos >> i) & 1;
1049 1050 1051
  int TBS = 0;
  while(TBS<7) {  // TBS for msg3 is 7 bytes (except for RRCResumeRequest1 currently not implemented)
    mcsindex++;
1052
    AssertFatal(mcsindex<28,"Exceeding MCS limit for Msg3\n");
francescomani's avatar
francescomani committed
1053 1054
    int R = nr_get_code_rate_ul(mcsindex,pusch_pdu->mcs_table);
    pusch_pdu->target_code_rate = R;
1055 1056
    pusch_pdu->qam_mod_order = nr_get_Qm_ul(mcsindex,pusch_pdu->mcs_table);
    TBS = nr_compute_tbs(pusch_pdu->qam_mod_order,
1057
                         R,
1058 1059 1060 1061 1062 1063 1064 1065 1066
                         pusch_pdu->rb_size,
                         pusch_pdu->nr_of_symbols,
                         num_dmrs_symb*12, // nb dmrs set for no data in dmrs symbol
                         0, //nb_rb_oh
                         0, // to verify tb scaling
                         pusch_pdu->nrOfLayers)>>3;

    pusch_pdu->mcs_index = mcsindex;
    pusch_pdu->pusch_data.tb_size = TBS;
1067
    pusch_pdu->maintenance_parms_v3.ldpcBaseGraph = get_BG(TBS<<3,R);
1068
  }
1069 1070
}

1071 1072
void nr_add_msg3(module_id_t module_idP, int CC_id, frame_t frameP, sub_frame_t slotP, NR_RA_t *ra, uint8_t *RAR_pdu)
{
1073 1074 1075
  gNB_MAC_INST *mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &mac->common_channels[CC_id];
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
francescomani's avatar
francescomani committed
1076
  NR_UE_UL_BWP_t *ul_bwp = &ra->UL_BWP;
cig's avatar
cig committed
1077

1078
  if (ra->state == RA_IDLE) {
1079
    LOG_W(NR_MAC,"RA is not active for RA %X. skipping msg3 scheduling\n", ra->rnti);
1080 1081
    return;
  }
cig's avatar
cig committed
1082

luis_pereira87's avatar
luis_pereira87 committed
1083
  const uint16_t mask = SL_to_bitmap(ra->msg3_startsymb, ra->msg3_nrsymb);
1084
  uint16_t *vrb_map_UL = &RC.nrmac[module_idP]->common_channels[CC_id].vrb_map_UL[ra->Msg3_slot * MAX_BWP_SIZE];
1085
  for (int i = 0; i < ra->msg3_nb_rb; ++i) {
1086
    AssertFatal(!(vrb_map_UL[i + ra->msg3_first_rb + ra->msg3_bwp_start] & mask),
1087 1088 1089 1090
                "RB %d in %4d.%2d is already taken, cannot allocate Msg3!\n",
                i + ra->msg3_first_rb,
                ra->Msg3_frame,
                ra->Msg3_slot);
1091
    vrb_map_UL[i + ra->msg3_first_rb + ra->msg3_bwp_start] |= mask;
1092 1093
  }

1094
  LOG_D(NR_MAC, "[gNB %d][RAPROC] Frame %d, Slot %d : CC_id %d RA is active, Msg3 in (%d,%d)\n", module_idP, frameP, slotP, CC_id, ra->Msg3_frame, ra->Msg3_slot);
1095

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  nfapi_nr_ul_tti_request_t *future_ul_tti_req = &RC.nrmac[module_idP]->UL_tti_req_ahead[CC_id][ra->Msg3_slot];
  AssertFatal(future_ul_tti_req->SFN == ra->Msg3_frame
              && future_ul_tti_req->Slot == ra->Msg3_slot,
              "future UL_tti_req's frame.slot %d.%d does not match PUSCH %d.%d\n",
              future_ul_tti_req->SFN,
              future_ul_tti_req->Slot,
              ra->Msg3_frame,
              ra->Msg3_slot);
  future_ul_tti_req->pdus_list[future_ul_tti_req->n_pdus].pdu_type = NFAPI_NR_UL_CONFIG_PUSCH_PDU_TYPE;
  future_ul_tti_req->pdus_list[future_ul_tti_req->n_pdus].pdu_size = sizeof(nfapi_nr_pusch_pdu_t);
  nfapi_nr_pusch_pdu_t *pusch_pdu = &future_ul_tti_req->pdus_list[future_ul_tti_req->n_pdus].pusch_pdu;
cig's avatar
cig committed
1107
  memset(pusch_pdu, 0, sizeof(nfapi_nr_pusch_pdu_t));
1108

francescomani's avatar
francescomani committed
1109 1110 1111 1112 1113
  const int ibwp_size  = NRRIV2BW(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
  const int scs = ul_bwp->scs;
  const int fh = (ul_bwp->pusch_Config && ul_bwp->pusch_Config->frequencyHopping) ? 1 : 0;
  const int startSymbolAndLength = ul_bwp->tdaList->list.array[ra->Msg3_tda_id]->startSymbolAndLength;
  const int mappingtype = ul_bwp->tdaList->list.array[ra->Msg3_tda_id]->mappingType;
1114

1115
  LOG_D(NR_MAC, "Frame %d, Slot %d Adding Msg3 UL Config Request for (%d,%d) : (%d,%d,%d) for rnti: %d\n",
cig's avatar
cig committed
1116 1117 1118 1119 1120 1121 1122 1123 1124
    frameP,
    slotP,
    ra->Msg3_frame,
    ra->Msg3_slot,
    ra->msg3_nb_rb,
    ra->msg3_first_rb,
    ra->msg3_round,
    ra->rnti);

1125
  fill_msg3_pusch_pdu(pusch_pdu,scc,
1126
                      ra->msg3_round,
1127 1128
                      startSymbolAndLength,
                      ra->rnti, scs,
1129
                      ibwp_size, ra->msg3_bwp_start,
1130 1131 1132
                      mappingtype, fh,
                      ra->msg3_first_rb, ra->msg3_nb_rb);
  future_ul_tti_req->n_pdus += 1;
1133 1134

  // calling function to fill rar message
1135
  nr_fill_rar(module_idP, ra, RAR_pdu, pusch_pdu);
cig's avatar
cig committed
1136 1137
}

francescomani's avatar
francescomani committed
1138
void nr_generate_Msg2(module_id_t module_idP, int CC_id, frame_t frameP, sub_frame_t slotP, NR_RA_t *ra) {
cig's avatar
cig committed
1139

rmagueta's avatar
rmagueta committed
1140 1141
  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];
francescomani's avatar
francescomani committed
1142
  NR_UE_DL_BWP_t *dl_bwp = &ra->DL_BWP;
1143

rmagueta's avatar
rmagueta committed
1144
  if ((ra->Msg2_frame == frameP) && (ra->Msg2_slot == slotP)) {
1145

1146
    int mcsIndex = -1;  // initialization value
1147
    int rbStart = 0;
1148
    int rbSize = 8;
cig's avatar
cig committed
1149

rmagueta's avatar
rmagueta committed
1150
    NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
1151
    NR_SearchSpace_t *ss = ra->ra_ss;
1152

rmagueta's avatar
rmagueta committed
1153 1154 1155 1156
    long BWPStart = 0;
    long BWPSize = 0;
    NR_Type0_PDCCH_CSS_config_t *type0_PDCCH_CSS_config = NULL;
    if(*ss->controlResourceSetId!=0) {
francescomani's avatar
francescomani committed
1157
      BWPStart = dl_bwp->BWPStart;
rmagueta's avatar
rmagueta committed
1158 1159 1160 1161 1162 1163
      BWPSize  = NRRIV2BW(scc->downlinkConfigCommon->initialDownlinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
    } else {
      type0_PDCCH_CSS_config = &nr_mac->type0_PDCCH_CSS_config[ra->beam_id];
      BWPStart = type0_PDCCH_CSS_config->cset_start_rb;
      BWPSize = type0_PDCCH_CSS_config->num_rbs;
    }
1164

1165
    // Calculate number of symbols
francescomani's avatar
francescomani committed
1166
    int time_domain_assignment = get_dl_tda(nr_mac, scc, slotP);
francescomani's avatar
francescomani committed
1167 1168
    NR_tda_info_t tda_info = nr_get_pdsch_tda_info(dl_bwp,
                                                   time_domain_assignment);
1169

francescomani's avatar
francescomani committed
1170
    NR_ControlResourceSet_t *coreset = ra->coreset;
1171 1172

    AssertFatal(coreset!=NULL,"Coreset cannot be null for RA-Msg2\n");
cig's avatar
cig committed
1173

1174
    uint16_t *vrb_map = cc[CC_id].vrb_map;
1175
    for (int i = 0; (i < rbSize) && (rbStart <= (BWPSize - rbSize)); i++) {
francescomani's avatar
francescomani committed
1176
      if (vrb_map[BWPStart + rbStart + i]&SL_to_bitmap(tda_info.startSymbolIndex, tda_info.nrOfSymbols)) {
1177 1178 1179 1180
        rbStart += i;
        i = 0;
      }
    }
rmagueta's avatar
rmagueta committed
1181

1182
    if (rbStart > (BWPSize - rbSize)) {
rmagueta's avatar
rmagueta committed
1183
      LOG_E(NR_MAC, "%s(): cannot find free vrb_map for RA RNTI %04x!\n", __func__, ra->RA_rnti);
1184 1185 1186
      return;
    }

1187
    // Checking if the DCI allocation is feasible in current subframe
cig's avatar
cig committed
1188
    nfapi_nr_dl_tti_request_body_t *dl_req = &nr_mac->DL_req[CC_id].dl_tti_request_body;
1189
    if (dl_req->nPDUs > NFAPI_NR_MAX_DL_TTI_PDUS - 2) {
1190
      LOG_I(NR_MAC, "[RAPROC] Subframe %d: FAPI DL structure is full, skip scheduling UE %d\n", slotP, ra->RA_rnti);
1191 1192 1193
      return;
    }

rmagueta's avatar
rmagueta committed
1194
    uint8_t aggregation_level;
1195 1196 1197 1198 1199 1200 1201
    int CCEIndex = get_cce_index(nr_mac,
                                 CC_id, slotP, 0,
                                 &aggregation_level,
                                 ss,
                                 coreset,
                                 &ra->sched_pdcch,
                                 true);
1202

1203
    if (CCEIndex < 0) {
1204
      LOG_E(NR_MAC, "%s(): cannot find free CCE for RA RNTI 0x%04x!\n", __func__, ra->rnti);
1205 1206 1207
      return;
    }

francescomani's avatar
francescomani committed
1208
    LOG_D(NR_MAC,"Msg2 startSymbolIndex.nrOfSymbols %d.%d\n",tda_info.startSymbolIndex,tda_info.nrOfSymbols);
rmagueta's avatar
rmagueta committed
1209

rmagueta's avatar
rmagueta committed
1210 1211
    // look up the PDCCH PDU for this CC, BWP, and CORESET. If it does not exist, create it. This is especially
    // important if we have multiple RAs, and the DLSCH has to reuse them, so we need to mark them
1212
    const int coresetid = coreset->controlResourceSetId;
1213
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_rel15 = nr_mac->pdcch_pdu_idx[CC_id][coresetid];
1214 1215 1216 1217 1218 1219 1220
    if (!pdcch_pdu_rel15) {
      nfapi_nr_dl_tti_request_pdu_t *dl_tti_pdcch_pdu = &dl_req->dl_tti_pdu_list[dl_req->nPDUs];
      memset(dl_tti_pdcch_pdu, 0, sizeof(nfapi_nr_dl_tti_request_pdu_t));
      dl_tti_pdcch_pdu->PDUType = NFAPI_NR_DL_TTI_PDCCH_PDU_TYPE;
      dl_tti_pdcch_pdu->PDUSize = (uint8_t)(2 + sizeof(nfapi_nr_dl_tti_pdcch_pdu));
      dl_req->nPDUs += 1;
      pdcch_pdu_rel15 = &dl_tti_pdcch_pdu->pdcch_pdu.pdcch_pdu_rel15;
1221
      nr_configure_pdcch(pdcch_pdu_rel15, coreset, false, &ra->sched_pdcch);
1222
      nr_mac->pdcch_pdu_idx[CC_id][coresetid] = pdcch_pdu_rel15;
1223
    }
cig's avatar
cig committed
1224

1225
    nfapi_nr_dl_tti_request_pdu_t *dl_tti_pdsch_pdu = &dl_req->dl_tti_pdu_list[dl_req->nPDUs];
cig's avatar
cig committed
1226 1227 1228
    memset((void *)dl_tti_pdsch_pdu,0,sizeof(nfapi_nr_dl_tti_request_pdu_t));
    dl_tti_pdsch_pdu->PDUType = NFAPI_NR_DL_TTI_PDSCH_PDU_TYPE;
    dl_tti_pdsch_pdu->PDUSize = (uint8_t)(2+sizeof(nfapi_nr_dl_tti_pdsch_pdu));
1229
    dl_req->nPDUs+=1;
cig's avatar
cig committed
1230
    nfapi_nr_dl_tti_pdsch_pdu_rel15_t *pdsch_pdu_rel15 = &dl_tti_pdsch_pdu->pdsch_pdu.pdsch_pdu_rel15;
1231

1232
    LOG_A(NR_MAC,"[gNB %d][RAPROC] CC_id %d Frame %d, slotP %d: Generating RA-Msg2 DCI, rnti 0x%x, state %d, CoreSetType %d\n",
Eurecom's avatar
Eurecom committed
1233
          module_idP, CC_id, frameP, slotP, ra->RA_rnti, ra->state,pdcch_pdu_rel15->CoreSetType);
cig's avatar
cig committed
1234

rmagueta's avatar
rmagueta committed
1235 1236
    // SCF222: PDU index incremented for each PDSCH PDU sent in TX control message. This is used to associate control
    // information to data and is reset every slot.
1237
    const int pduindex = nr_mac->pdu_index[CC_id]++;
francescomani's avatar
francescomani committed
1238
    uint8_t mcsTableIdx = dl_bwp->mcsTableIdx;
1239

francescomani's avatar
francescomani committed
1240 1241 1242 1243
   NR_pdsch_dmrs_t dmrs_parms = get_dl_dmrs_params(scc,
                                                   dl_bwp,
                                                   &tda_info,
                                                   1);
1244

rmagueta's avatar
rmagueta committed
1245 1246
    pdsch_pdu_rel15->pduBitmap = 0;
    pdsch_pdu_rel15->rnti = ra->RA_rnti;
1247
    pdsch_pdu_rel15->pduIndex = pduindex;
1248 1249
    pdsch_pdu_rel15->BWPSize  = BWPSize;
    pdsch_pdu_rel15->BWPStart = BWPStart;
francescomani's avatar
francescomani committed
1250
    pdsch_pdu_rel15->SubcarrierSpacing = dl_bwp->scs;
cig's avatar
cig committed
1251 1252
    pdsch_pdu_rel15->CyclicPrefix = 0;
    pdsch_pdu_rel15->NrOfCodewords = 1;
rmagueta's avatar
rmagueta committed
1253
    pdsch_pdu_rel15->mcsTable[0] = mcsTableIdx;
cig's avatar
cig committed
1254 1255 1256 1257 1258
    pdsch_pdu_rel15->rvIndex[0] = 0;
    pdsch_pdu_rel15->dataScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->nrOfLayers = 1;
    pdsch_pdu_rel15->transmissionScheme = 0;
    pdsch_pdu_rel15->refPoint = 0;
francescomani's avatar
francescomani committed
1259
    pdsch_pdu_rel15->dmrsConfigType = dmrs_parms.dmrsConfigType;
cig's avatar
cig committed
1260 1261
    pdsch_pdu_rel15->dlDmrsScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->SCID = 0;
francescomani's avatar
francescomani committed
1262
    pdsch_pdu_rel15->numDmrsCdmGrpsNoData = dmrs_parms.numDmrsCdmGrpsNoData;
cig's avatar
cig committed
1263 1264
    pdsch_pdu_rel15->dmrsPorts = 1;
    pdsch_pdu_rel15->resourceAlloc = 1;
1265 1266
    pdsch_pdu_rel15->rbStart = rbStart;
    pdsch_pdu_rel15->rbSize = rbSize;
rmagueta's avatar
rmagueta committed
1267
    pdsch_pdu_rel15->VRBtoPRBMapping = 0;
francescomani's avatar
francescomani committed
1268 1269 1270
    pdsch_pdu_rel15->StartSymbolIndex = tda_info.startSymbolIndex;
    pdsch_pdu_rel15->NrOfSymbols = tda_info.nrOfSymbols;
    pdsch_pdu_rel15->dlDmrsSymbPos = dmrs_parms.dl_dmrs_symb_pos;
cig's avatar
cig committed
1271

rmagueta's avatar
rmagueta committed
1272
    uint8_t tb_scaling = 0;
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    int R, Qm;
    uint32_t TBS=0;

    while(TBS<9) {  // min TBS for RAR is 9 bytes
      mcsIndex++;
      R = nr_get_code_rate_dl(mcsIndex, mcsTableIdx);
      Qm = nr_get_Qm_dl(mcsIndex, mcsTableIdx);
      TBS = nr_compute_tbs(Qm,
                           R,
                           rbSize,
francescomani's avatar
francescomani committed
1283 1284
                           tda_info.nrOfSymbols,
                           dmrs_parms.N_PRB_DMRS*dmrs_parms.N_DMRS_SLOT,
1285 1286 1287 1288 1289 1290 1291 1292 1293
                           0, // overhead
                           tb_scaling,  // tb scaling
		           1)>>3;  // layers

      pdsch_pdu_rel15->targetCodeRate[0] = R;
      pdsch_pdu_rel15->qamModOrder[0] = Qm;
      pdsch_pdu_rel15->mcsIndex[0] = mcsIndex;
      pdsch_pdu_rel15->TBSize[0] = TBS;
    }
cig's avatar
cig committed
1294

1295
    int scc_bwpsize = NRRIV2BW(scc->downlinkConfigCommon->initialDownlinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
francescomani's avatar
francescomani committed
1296
    int bw_tbslbrm = get_dlbw_tbslbrm(scc_bwpsize, ra->CellGroup);
1297 1298 1299
    pdsch_pdu_rel15->maintenance_parms_v3.tbSizeLbrmBytes = nr_compute_tbslbrm(mcsTableIdx,
                                                                               bw_tbslbrm,
                                                                               1);
1300
    pdsch_pdu_rel15->maintenance_parms_v3.ldpcBaseGraph = get_BG(TBS<<3,R);
1301

rmagueta's avatar
rmagueta committed
1302
    // Fill PDCCH DL DCI PDU
1303 1304
    nfapi_nr_dl_dci_pdu_t *dci_pdu = &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci];
    pdcch_pdu_rel15->numDlDci++;
rmagueta's avatar
rmagueta committed
1305
    dci_pdu->RNTI = ra->RA_rnti;
1306 1307 1308 1309 1310 1311 1312 1313 1314
    dci_pdu->ScramblingId = *scc->physCellId;
    dci_pdu->ScramblingRNTI = 0;
    dci_pdu->AggregationLevel = aggregation_level;
    dci_pdu->CceIndex = CCEIndex;
    dci_pdu->beta_PDCCH_1_0 = 0;
    dci_pdu->powerControlOffsetSS = 1;

    dci_pdu_rel15_t dci_payload;
    dci_payload.frequency_domain_assignment.val = PRBalloc_to_locationandbandwidth0(pdsch_pdu_rel15->rbSize,
rmagueta's avatar
rmagueta committed
1315
                                                                                    pdsch_pdu_rel15->rbStart,
rmagueta's avatar
rmagueta committed
1316
                                                                                    BWPSize);
1317

rmagueta's avatar
rmagueta committed
1318
    LOG_D(NR_MAC,"Msg2 rbSize.rbStart.BWPsize %d.%d.%ld\n",pdsch_pdu_rel15->rbSize,
1319
          pdsch_pdu_rel15->rbStart,
rmagueta's avatar
rmagueta committed
1320
          BWPSize);
rmagueta's avatar
rmagueta committed
1321

1322 1323 1324
    dci_payload.time_domain_assignment.val = time_domain_assignment;
    dci_payload.vrb_to_prb_mapping.val = 0;
    dci_payload.mcs = pdsch_pdu_rel15->mcsIndex[0];
rmagueta's avatar
rmagueta committed
1325
    dci_payload.tb_scaling = tb_scaling;
1326

Abhijith's avatar
Abhijith committed
1327
    LOG_D(NR_MAC,
rmagueta's avatar
rmagueta committed
1328
          "[RAPROC] DCI type 1 payload: freq_alloc %d (%d,%d,%ld), time_alloc %d, vrb to prb %d, mcs %d tb_scaling %d \n",
1329
          dci_payload.frequency_domain_assignment.val,
1330 1331
          pdsch_pdu_rel15->rbStart,
          pdsch_pdu_rel15->rbSize,
rmagueta's avatar
rmagueta committed
1332
          BWPSize,
1333 1334 1335 1336
          dci_payload.time_domain_assignment.val,
          dci_payload.vrb_to_prb_mapping.val,
          dci_payload.mcs,
          dci_payload.tb_scaling);
cig's avatar
cig committed
1337

Abhijith's avatar
Abhijith committed
1338
    LOG_D(NR_MAC,
rmagueta's avatar
rmagueta committed
1339
          "[RAPROC] DCI params: rnti 0x%x, rnti_type %d, dci_format %d coreset params: FreqDomainResource %llx, start_symbol %d  n_symb %d\n",
1340
          pdcch_pdu_rel15->dci_pdu[0].RNTI,
rmagueta's avatar
rmagueta committed
1341 1342
          NR_RNTI_RA,
          NR_DL_DCI_FORMAT_1_0,
1343
          *(unsigned long long *)pdcch_pdu_rel15->FreqDomainResource,
1344 1345
          pdcch_pdu_rel15->StartSymbolIndex,
          pdcch_pdu_rel15->DurationSymbols);
cig's avatar
cig committed
1346

1347
    fill_dci_pdu_rel15(scc,
1348
                       ra->CellGroup,
francescomani's avatar
francescomani committed
1349
                       dl_bwp,
rmagueta's avatar
rmagueta committed
1350
                       &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci - 1],
1351
                       &dci_payload,
rmagueta's avatar
rmagueta committed
1352 1353
                       NR_DL_DCI_FORMAT_1_0,
                       NR_RNTI_RA,
rmagueta's avatar
rmagueta committed
1354
                       BWPSize,
francescomani's avatar
francescomani committed
1355
                       dl_bwp->bwp_id,
1356
                       coreset,
1357
                       nr_mac->cset0_bwp_size);
cig's avatar
cig committed
1358 1359

    // DL TX request
1360
    nfapi_nr_pdu_t *tx_req = &nr_mac->TX_req[CC_id].pdu_list[nr_mac->TX_req[CC_id].Number_of_PDUs];
rmagueta's avatar
rmagueta committed
1361 1362

    // Program UL processing for Msg3
francescomani's avatar
francescomani committed
1363
    nr_get_Msg3alloc(module_idP, CC_id, scc, slotP, frameP, ra, nr_mac->tdd_beam_association);
rmagueta's avatar
rmagueta committed
1364 1365
    nr_add_msg3(module_idP, CC_id, frameP, slotP, ra, (uint8_t *) &tx_req->TLVs[0].value.direct[0]);

1366
    if(ra->cfra) {
1367
      LOG_D(NR_MAC, "Frame %d, Subframe %d: Setting RA-Msg3 reception (CFRA) for SFN.Slot %d.%d\n", frameP, slotP, ra->Msg3_frame, ra->Msg3_slot);
1368
    }
1369
    else LOG_D(NR_MAC, "Frame %d, Subframe %d: Setting RA-Msg3 reception (CBRA) for SFN.Slot %d.%d\n", frameP, slotP, ra->Msg3_frame, ra->Msg3_slot);
rmagueta's avatar
rmagueta committed
1370 1371 1372 1373

    T(T_GNB_MAC_DL_RAR_PDU_WITH_DATA, T_INT(module_idP), T_INT(CC_id), T_INT(ra->RA_rnti), T_INT(frameP),
      T_INT(slotP), T_INT(0), T_BUFFER(&tx_req->TLVs[0].value.direct[0], tx_req->TLVs[0].length));

cig's avatar
cig committed
1374
    tx_req->PDU_length = pdsch_pdu_rel15->TBSize[0];
1375
    tx_req->PDU_index = pduindex;
cig's avatar
cig committed
1376
    tx_req->num_TLV = 1;
1377
    tx_req->TLVs[0].length = tx_req->PDU_length + 2;
cig's avatar
cig committed
1378 1379 1380
    nr_mac->TX_req[CC_id].SFN = frameP;
    nr_mac->TX_req[CC_id].Number_of_PDUs++;
    nr_mac->TX_req[CC_id].Slot = slotP;
1381

1382
    // Mark the corresponding symbols RBs as used
1383 1384
    fill_pdcch_vrb_map(nr_mac,
                       CC_id,
1385
                       &ra->sched_pdcch,
1386 1387
                       CCEIndex,
                       aggregation_level);
1388
    for (int rb = 0; rb < rbSize; rb++) {
francescomani's avatar
francescomani committed
1389
      vrb_map[BWPStart + rb + rbStart] |= SL_to_bitmap(tda_info.startSymbolIndex, tda_info.nrOfSymbols);
rmagueta's avatar
rmagueta committed
1390
    }
rmagueta's avatar
rmagueta committed
1391 1392

    ra->state = WAIT_Msg3;
Laurent THOMAS's avatar
Laurent THOMAS committed
1393
    LOG_W(NR_MAC,"[gNB %d][RAPROC] Frame %d, Subframe %d: rnti %04x RA state %d\n", module_idP, frameP, slotP, ra->rnti, ra->state);
cig's avatar
cig committed
1394
  }
1395 1396
}

1397
void nr_generate_Msg4(module_id_t module_idP, int CC_id, frame_t frameP, sub_frame_t slotP, NR_RA_t *ra) {
1398 1399 1400

  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];
francescomani's avatar
francescomani committed
1401
  NR_UE_DL_BWP_t *dl_bwp = &ra->DL_BWP;
1402

1403 1404 1405
  // if it is a DL slot, if the RA is in MSG4 state
  if (is_xlsch_in_slot(nr_mac->dlsch_slot_bitmap[slotP / 64], slotP) &&
      ra->state == Msg4) {
1406

1407 1408 1409
    NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
    NR_SearchSpace_t *ss = ra->ra_ss;

francescomani's avatar
francescomani committed
1410
    NR_ControlResourceSet_t *coreset = ra->coreset;
1411
    AssertFatal(coreset!=NULL,"Coreset cannot be null for RA-Msg4\n");
1412

1413 1414
    uint16_t mac_sdu_length = 0;

1415
    // If UE is known by the network, C-RNTI to be used instead of TC-RNTI
1416
    rnti_t tc_rnti = ra->rnti;
1417
    if (ra->msg3_dcch_dtch) {
1418 1419 1420
      ra->rnti = ra->crnti;
    }

1421
    NR_UE_info_t *UE = find_nr_UE(&nr_mac->UE_info, ra->rnti);
Laurent THOMAS's avatar
Laurent THOMAS committed
1422
    if (!UE) {
1423
      LOG_E(NR_MAC, "want to generate Msg4, but rnti %04x not in the table\n", ra->rnti);
1424
      return;
Laurent THOMAS's avatar
Laurent THOMAS committed
1425 1426
    }

1427 1428 1429 1430
    NR_UE_sched_ctrl_t *sched_ctrl = &UE->UE_sched_ctrl;
    /* get the PID of a HARQ process awaiting retrnasmission, or -1 otherwise */
    int current_harq_pid = sched_ctrl->retrans_dl_harq.head;

1431
    logical_chan_id_t lcid = DL_SCH_LCID_CCCH;
1432
    if (ra->msg3_dcch_dtch == false && current_harq_pid < 0) {
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
      // Check for data on SRB0 (RRCSetup)
      mac_rlc_status_resp_t srb_status = mac_rlc_status_ind(module_idP, ra->rnti, module_idP, frameP, slotP, ENB_FLAG_YES, MBMS_FLAG_NO, lcid, 0, 0);

      if (srb_status.bytes_in_buffer == 0) {
        lcid = DL_SCH_LCID_DCCH;
        // Check for data on SRB1 (RRCReestablishment)
        srb_status = mac_rlc_status_ind(module_idP, ra->rnti, module_idP, frameP, slotP, ENB_FLAG_YES, MBMS_FLAG_NO, lcid, 0, 0);
      }

      // Need to wait until data for Msg4 is ready
      if (srb_status.bytes_in_buffer == 0)
        return;
      LOG_I(NR_MAC, "(%4d.%2d) SRB%d has %d bytes\n", frameP, slotP, lcid, srb_status.bytes_in_buffer);
      mac_sdu_length = srb_status.bytes_in_buffer;
1447 1448
    }

rmagueta's avatar
rmagueta committed
1449 1450 1451 1452
    long BWPStart = 0;
    long BWPSize = 0;
    NR_Type0_PDCCH_CSS_config_t *type0_PDCCH_CSS_config = NULL;
    if(*ss->controlResourceSetId!=0) {
francescomani's avatar
francescomani committed
1453 1454
      BWPStart = dl_bwp->BWPStart;
      BWPSize  = dl_bwp->BWPSize;
rmagueta's avatar
rmagueta committed
1455 1456 1457 1458 1459
    } else {
      type0_PDCCH_CSS_config = &nr_mac->type0_PDCCH_CSS_config[ra->beam_id];
      BWPStart = type0_PDCCH_CSS_config->cset_start_rb;
      BWPSize = type0_PDCCH_CSS_config->num_rbs;
    }
1460

1461 1462
    // get CCEindex, needed also for PUCCH and then later for PDCCH
    uint8_t aggregation_level;
1463 1464 1465 1466 1467 1468 1469
    int CCEIndex = get_cce_index(nr_mac,
                                 CC_id, slotP, 0,
                                 &aggregation_level,
                                 ss,
                                 coreset,
                                 &ra->sched_pdcch,
                                 true);
1470

1471
    if (CCEIndex < 0) {
1472
      LOG_E(NR_MAC, "%s(): cannot find free CCE for RA RNTI 0x%04x!\n", __func__, ra->rnti);
1473 1474 1475
      return;
    }

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    // Checking if the DCI allocation is feasible in current subframe
    nfapi_nr_dl_tti_request_body_t *dl_req = &nr_mac->DL_req[CC_id].dl_tti_request_body;
    if (dl_req->nPDUs > NFAPI_NR_MAX_DL_TTI_PDUS - 2) {
      LOG_I(NR_MAC, "[RAPROC] Subframe %d: FAPI DL structure is full, skip scheduling UE %d\n", slotP, ra->rnti);
      return;
    }

    uint8_t time_domain_assignment = get_dl_tda(nr_mac, scc, slotP);
    NR_tda_info_t msg4_tda = nr_get_pdsch_tda_info(dl_bwp, time_domain_assignment);
    NR_pdsch_dmrs_t dmrs_info = get_dl_dmrs_params(scc,
                                                   dl_bwp,
                                                   &msg4_tda,
                                                   1);

    uint8_t mcsTableIdx = dl_bwp->mcsTableIdx;
    uint8_t mcsIndex = 0;
    int rbStart = 0;
    int rbSize = 0;
    uint8_t tb_scaling = 0;
    uint32_t tb_size = 0;
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
    uint16_t pdu_length;
    if(current_harq_pid >= 0) { // in case of retransmission
      NR_UE_harq_t *harq = &sched_ctrl->harq_processes[current_harq_pid];
      DevAssert(!harq->is_waiting);
      pdu_length = harq->tb_size;
    }
    else {
      uint8_t subheader_len = (mac_sdu_length < 256) ? sizeof(NR_MAC_SUBHEADER_SHORT) : sizeof(NR_MAC_SUBHEADER_LONG);
      pdu_length = mac_sdu_length + subheader_len + 7; //7 is contetion resolution length
    }

1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
    // increase PRBs until we get to BWPSize or TBS is bigger than MAC PDU size
    do {
      if(rbSize < BWPSize)
        rbSize++;
      else
        mcsIndex++;
      LOG_D(NR_MAC,"Calling nr_compute_tbs with N_PRB_DMRS %d, N_DMRS_SLOT %d\n",dmrs_info.N_PRB_DMRS,dmrs_info.N_DMRS_SLOT);
      tb_size = nr_compute_tbs(nr_get_Qm_dl(mcsIndex, mcsTableIdx),
                                     nr_get_code_rate_dl(mcsIndex, mcsTableIdx),
                                     rbSize, msg4_tda.nrOfSymbols, dmrs_info.N_PRB_DMRS * dmrs_info.N_DMRS_SLOT, 0, tb_scaling,1) >> 3;
    } while (tb_size < pdu_length && mcsIndex<=28);

    AssertFatal(tb_size >= pdu_length,"Cannot allocate Msg4\n");

    int i = 0;
1522
    uint16_t *vrb_map = cc[CC_id].vrb_map;
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
    while ((i < rbSize) && (rbStart + rbSize <= BWPSize)) {
      if (vrb_map[BWPStart + rbStart + i]&SL_to_bitmap(msg4_tda.startSymbolIndex, msg4_tda.nrOfSymbols)) {
        rbStart += i+1;
        i = 0;
      } else {
        i++;
      }
    }

    if (rbStart > (BWPSize - rbSize)) {
      LOG_E(NR_MAC, "%s(): cannot find free vrb_map for RNTI %04x!\n", __func__, ra->rnti);
      return;
    }

1537
    const int delta_PRI=0;
francescomani's avatar
francescomani committed
1538
    int r_pucch = nr_get_pucch_resource(coreset, ra->UL_BWP.pucch_Config, CCEIndex);
1539

1540
    LOG_D(NR_MAC,"[RAPROC] Msg4 r_pucch %d (CCEIndex %d, delta_PRI %d)\n", r_pucch, CCEIndex, delta_PRI);
1541

francescomani's avatar
francescomani committed
1542
    int alloc = nr_acknack_scheduling(nr_mac, UE, frameP, slotP, r_pucch, 1);
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    if (alloc<0) {
      LOG_D(NR_MAC,"Couldn't find a pucch allocation for ack nack (msg4) in frame %d slot %d\n",frameP,slotP);
      return;
    }

    LOG_I(NR_MAC,"Generate msg4, rnti: %04x\n", ra->rnti);

    // HARQ management
    if (current_harq_pid < 0) {
      AssertFatal(sched_ctrl->available_dl_harq.head >= 0,
                  "UE context not initialized: no HARQ processes found\n");
      current_harq_pid = sched_ctrl->available_dl_harq.head;
      remove_front_nr_list(&sched_ctrl->available_dl_harq);
    }
    NR_UE_harq_t *harq = &sched_ctrl->harq_processes[current_harq_pid];
    DevAssert(!harq->is_waiting);
    add_tail_nr_list(&sched_ctrl->feedback_dl_harq, current_harq_pid);
    harq->is_waiting = true;
    ra->harq_pid = current_harq_pid;

    // Remove UE associated to TC-RNTI
    if(harq->round==0 && ra->msg3_dcch_dtch) {
      mac_remove_nr_ue(nr_mac, tc_rnti);
    }

1568 1569 1570
    NR_sched_pucch_t *pucch = &sched_ctrl->sched_pucch[alloc];
    harq->feedback_slot = pucch->ul_slot;
    harq->feedback_frame = pucch->frame;
1571
    harq->tb_size = tb_size;
1572

1573
    uint8_t *buf = (uint8_t *) harq->transportBlock;
1574 1575
    // Bytes to be transmitted
    if (harq->round == 0) {
1576 1577 1578 1579 1580
      if (ra->msg3_dcch_dtch) {
        // If the UE used MSG3 to transfer a DCCH or DTCH message, then contention resolution is successful if the UE receives a PDCCH transmission which has its CRC bits scrambled by the C-RNTI
        // Just send padding LCID
        ra->mac_pdu_length = 0;
      } else {
1581
        // UE Contention Resolution Identity MAC CE
1582 1583
        uint16_t mac_pdu_length = nr_write_ce_dlsch_pdu(module_idP, nr_mac->sched_ctrlCommon, buf, 255, ra->cont_res_id);
        LOG_D(NR_MAC,"Encoded contention resolution mac_pdu_length %d\n",mac_pdu_length);
1584 1585
        uint8_t buffer[CCCH_SDU_SIZE];
        uint8_t mac_subheader_len = sizeof(NR_MAC_SUBHEADER_SHORT);
1586
        // Get RLC data on the SRB (RRCSetup, RRCReestablishment)
1587 1588 1589 1590 1591 1592
        mac_sdu_length = mac_rlc_data_req(module_idP,
                                          ra->rnti,
                                          module_idP,
                                          frameP,
                                          ENB_FLAG_YES,
                                          MBMS_FLAG_NO,
1593
                                          lcid,
1594 1595 1596 1597
                                          CCCH_SDU_SIZE,
                                          (char *)buffer,
                                          0,
                                          0);
1598

1599
        if (mac_sdu_length < 256) {
1600 1601 1602 1603
          ((NR_MAC_SUBHEADER_SHORT *)&buf[mac_pdu_length])->R = 0;
          ((NR_MAC_SUBHEADER_SHORT *)&buf[mac_pdu_length])->F = 0;
          ((NR_MAC_SUBHEADER_SHORT *)&buf[mac_pdu_length])->LCID = lcid;
          ((NR_MAC_SUBHEADER_SHORT *)&buf[mac_pdu_length])->L = mac_sdu_length;
1604 1605 1606
          ra->mac_pdu_length = mac_pdu_length + mac_sdu_length + sizeof(NR_MAC_SUBHEADER_SHORT);
        } else {
          mac_subheader_len = sizeof(NR_MAC_SUBHEADER_LONG);
1607 1608 1609 1610
          ((NR_MAC_SUBHEADER_LONG *)&buf[mac_pdu_length])->R = 0;
          ((NR_MAC_SUBHEADER_LONG *)&buf[mac_pdu_length])->F = 1;
          ((NR_MAC_SUBHEADER_LONG *)&buf[mac_pdu_length])->LCID = lcid;
          ((NR_MAC_SUBHEADER_LONG *)&buf[mac_pdu_length])->L = htons(mac_sdu_length);
1611 1612 1613 1614
          ra->mac_pdu_length = mac_pdu_length + mac_sdu_length + sizeof(NR_MAC_SUBHEADER_LONG);
        }
        LOG_I(NR_MAC,"Encoded RRCSetup Piggyback (%d + %d bytes), mac_pdu_length %d\n", mac_sdu_length, mac_subheader_len, ra->mac_pdu_length);
        memcpy(&buf[mac_pdu_length + mac_subheader_len], buffer, mac_sdu_length);
1615
      }
1616
    }
1617

1618 1619 1620
    // look up the PDCCH PDU for this CC, BWP, and CORESET. If it does not exist, create it. This is especially
    // important if we have multiple RAs, and the DLSCH has to reuse them, so we need to mark them
    const int coresetid = coreset->controlResourceSetId;
1621
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_rel15 = nr_mac->pdcch_pdu_idx[CC_id][coresetid];
1622 1623 1624 1625 1626 1627 1628
    if (!pdcch_pdu_rel15) {
      nfapi_nr_dl_tti_request_pdu_t *dl_tti_pdcch_pdu = &dl_req->dl_tti_pdu_list[dl_req->nPDUs];
      memset(dl_tti_pdcch_pdu, 0, sizeof(nfapi_nr_dl_tti_request_pdu_t));
      dl_tti_pdcch_pdu->PDUType = NFAPI_NR_DL_TTI_PDCCH_PDU_TYPE;
      dl_tti_pdcch_pdu->PDUSize = (uint8_t)(2 + sizeof(nfapi_nr_dl_tti_pdcch_pdu));
      dl_req->nPDUs += 1;
      pdcch_pdu_rel15 = &dl_tti_pdcch_pdu->pdcch_pdu.pdcch_pdu_rel15;
1629
      nr_configure_pdcch(pdcch_pdu_rel15, coreset, false, &ra->sched_pdcch);
1630
      nr_mac->pdcch_pdu_idx[CC_id][coresetid] = pdcch_pdu_rel15;
1631 1632 1633 1634 1635 1636 1637 1638 1639
    }

    nfapi_nr_dl_tti_request_pdu_t *dl_tti_pdsch_pdu = &dl_req->dl_tti_pdu_list[dl_req->nPDUs];
    memset((void *)dl_tti_pdsch_pdu,0,sizeof(nfapi_nr_dl_tti_request_pdu_t));
    dl_tti_pdsch_pdu->PDUType = NFAPI_NR_DL_TTI_PDSCH_PDU_TYPE;
    dl_tti_pdsch_pdu->PDUSize = (uint8_t)(2+sizeof(nfapi_nr_dl_tti_pdsch_pdu));
    dl_req->nPDUs+=1;
    nfapi_nr_dl_tti_pdsch_pdu_rel15_t *pdsch_pdu_rel15 = &dl_tti_pdsch_pdu->pdsch_pdu.pdsch_pdu_rel15;

1640
    LOG_A(NR_MAC, "[gNB %d] [RAPROC] CC_id %d Frame %d, slotP %d: Generating RA-Msg4 DCI, state %d\n", module_idP, CC_id, frameP, slotP, ra->state);
1641 1642 1643 1644

    // SCF222: PDU index incremented for each PDSCH PDU sent in TX control message. This is used to associate control
    // information to data and is reset every slot.
    const int pduindex = nr_mac->pdu_index[CC_id]++;
rmagueta's avatar
rmagueta committed
1645 1646 1647

    pdsch_pdu_rel15->pduBitmap = 0;
    pdsch_pdu_rel15->rnti = ra->rnti;
1648
    pdsch_pdu_rel15->pduIndex = pduindex;
rmagueta's avatar
rmagueta committed
1649 1650
    pdsch_pdu_rel15->BWPSize  = BWPSize;
    pdsch_pdu_rel15->BWPStart = BWPStart;
francescomani's avatar
francescomani committed
1651
    pdsch_pdu_rel15->SubcarrierSpacing = dl_bwp->scs;
1652 1653
    pdsch_pdu_rel15->CyclicPrefix = 0;
    pdsch_pdu_rel15->NrOfCodewords = 1;
1654
    int R = nr_get_code_rate_dl(mcsIndex,mcsTableIdx);
1655
    pdsch_pdu_rel15->targetCodeRate[0] = R;
1656 1657
    int Qm = nr_get_Qm_dl(mcsIndex, mcsTableIdx);
    pdsch_pdu_rel15->qamModOrder[0] = Qm;
1658
    pdsch_pdu_rel15->mcsIndex[0] = mcsIndex;
rmagueta's avatar
rmagueta committed
1659
    pdsch_pdu_rel15->mcsTable[0] = mcsTableIdx;
1660
    pdsch_pdu_rel15->rvIndex[0] = nr_rv_round_map[harq->round%4];
cig's avatar
cig committed
1661 1662 1663 1664
    pdsch_pdu_rel15->dataScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->nrOfLayers = 1;
    pdsch_pdu_rel15->transmissionScheme = 0;
    pdsch_pdu_rel15->refPoint = 0;
francescomani's avatar
francescomani committed
1665
    pdsch_pdu_rel15->dmrsConfigType = dmrs_info.dmrsConfigType;
cig's avatar
cig committed
1666 1667
    pdsch_pdu_rel15->dlDmrsScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->SCID = 0;
francescomani's avatar
francescomani committed
1668
    pdsch_pdu_rel15->numDmrsCdmGrpsNoData = dmrs_info.numDmrsCdmGrpsNoData;
cig's avatar
cig committed
1669 1670
    pdsch_pdu_rel15->dmrsPorts = 1;
    pdsch_pdu_rel15->resourceAlloc = 1;
1671 1672
    pdsch_pdu_rel15->rbStart = rbStart;
    pdsch_pdu_rel15->rbSize = rbSize;
1673
    pdsch_pdu_rel15->VRBtoPRBMapping = 0;
francescomani's avatar
francescomani committed
1674 1675 1676
    pdsch_pdu_rel15->StartSymbolIndex = msg4_tda.startSymbolIndex;
    pdsch_pdu_rel15->NrOfSymbols = msg4_tda.nrOfSymbols;
    pdsch_pdu_rel15->dlDmrsSymbPos = dmrs_info.dl_dmrs_symb_pos;
1677

rmagueta's avatar
rmagueta committed
1678 1679
    int x_Overhead = 0;
    nr_get_tbs_dl(&dl_tti_pdsch_pdu->pdsch_pdu, x_Overhead, pdsch_pdu_rel15->numDmrsCdmGrpsNoData, tb_scaling);
cig's avatar
cig committed
1680

1681
    int scc_bwpsize = NRRIV2BW(scc->downlinkConfigCommon->initialDownlinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
francescomani's avatar
francescomani committed
1682
    int bw_tbslbrm = get_dlbw_tbslbrm(scc_bwpsize, ra->CellGroup);
1683 1684 1685
    pdsch_pdu_rel15->maintenance_parms_v3.tbSizeLbrmBytes = nr_compute_tbslbrm(mcsTableIdx,
                                                                               bw_tbslbrm,
                                                                               1);
1686
    pdsch_pdu_rel15->maintenance_parms_v3.ldpcBaseGraph = get_BG(harq->tb_size<<3,R);
1687

1688 1689 1690 1691 1692 1693
    pdsch_pdu_rel15->precodingAndBeamforming.num_prgs=1;
    pdsch_pdu_rel15->precodingAndBeamforming.prg_size=275;
    pdsch_pdu_rel15->precodingAndBeamforming.dig_bf_interfaces=1;
    pdsch_pdu_rel15->precodingAndBeamforming.prgs_list[0].pm_idx = 0;
    pdsch_pdu_rel15->precodingAndBeamforming.prgs_list[0].dig_bf_interface_list[0].beam_idx = ra->beam_id;

1694 1695 1696
    /* Fill PDCCH DL DCI PDU */
    nfapi_nr_dl_dci_pdu_t *dci_pdu = &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci];
    pdcch_pdu_rel15->numDlDci++;
1697
    dci_pdu->RNTI = ra->rnti;
1698 1699 1700 1701 1702 1703 1704 1705 1706
    dci_pdu->ScramblingId = *scc->physCellId;
    dci_pdu->ScramblingRNTI = 0;
    dci_pdu->AggregationLevel = aggregation_level;
    dci_pdu->CceIndex = CCEIndex;
    dci_pdu->beta_PDCCH_1_0 = 0;
    dci_pdu->powerControlOffsetSS = 1;

    dci_pdu_rel15_t dci_payload;
    dci_payload.frequency_domain_assignment.val = PRBalloc_to_locationandbandwidth0(pdsch_pdu_rel15->rbSize,
1707
                                                                                    pdsch_pdu_rel15->rbStart,
1708
                                                                                    BWPSize);
rmagueta's avatar
rmagueta committed
1709

1710
    dci_payload.format_indicator = 1;
1711 1712 1713
    dci_payload.time_domain_assignment.val = time_domain_assignment;
    dci_payload.vrb_to_prb_mapping.val = 0;
    dci_payload.mcs = pdsch_pdu_rel15->mcsIndex[0];
rmagueta's avatar
rmagueta committed
1714
    dci_payload.tb_scaling = tb_scaling;
1715 1716 1717
    dci_payload.rv = pdsch_pdu_rel15->rvIndex[0];
    dci_payload.harq_pid = current_harq_pid;
    dci_payload.ndi = harq->ndi;
1718
    dci_payload.dai[0].val = (pucch->dai_c-1)&3;
1719
    dci_payload.tpc = sched_ctrl->tpc1; // TPC for PUCCH: table 7.2.1-1 in 38.213
1720
    dci_payload.pucch_resource_indicator = delta_PRI; // This is delta_PRI from 9.2.1 in 38.213
1721
    dci_payload.pdsch_to_harq_feedback_timing_indicator.val = pucch->timing_indicator;
1722

rmagueta's avatar
rmagueta committed
1723
    LOG_D(NR_MAC,
1724
          "[RAPROC] DCI 1_0 payload: freq_alloc %d (%d,%d,%d), time_alloc %d, vrb to prb %d, mcs %d tb_scaling %d pucchres %d harqtiming %d\n",
1725
          dci_payload.frequency_domain_assignment.val,
1726 1727
          pdsch_pdu_rel15->rbStart,
          pdsch_pdu_rel15->rbSize,
rmagueta's avatar
rmagueta committed
1728
          pdsch_pdu_rel15->BWPSize,
1729 1730 1731
          dci_payload.time_domain_assignment.val,
          dci_payload.vrb_to_prb_mapping.val,
          dci_payload.mcs,
1732 1733 1734
          dci_payload.tb_scaling,
          dci_payload.pucch_resource_indicator,
          dci_payload.pdsch_to_harq_feedback_timing_indicator.val);
cig's avatar
cig committed
1735

rmagueta's avatar
rmagueta committed
1736
    LOG_D(NR_MAC,
Eurecom's avatar
Eurecom committed
1737
          "[RAPROC] DCI params: rnti 0x%x, rnti_type %d, dci_format %d coreset params: FreqDomainResource %llx, start_symbol %d  n_symb %d, BWPsize %d\n",
1738
          pdcch_pdu_rel15->dci_pdu[0].RNTI,
rmagueta's avatar
rmagueta committed
1739 1740
          NR_RNTI_TC,
          NR_DL_DCI_FORMAT_1_0,
1741 1742
          (unsigned long long)pdcch_pdu_rel15->FreqDomainResource,
          pdcch_pdu_rel15->StartSymbolIndex,
Eurecom's avatar
Eurecom committed
1743 1744
          pdcch_pdu_rel15->DurationSymbols,
          pdsch_pdu_rel15->BWPSize);
cig's avatar
cig committed
1745

1746
    fill_dci_pdu_rel15(scc,
1747
                       ra->CellGroup,
francescomani's avatar
francescomani committed
1748
                       dl_bwp,
rmagueta's avatar
rmagueta committed
1749
                       &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci - 1],
1750
                       &dci_payload,
rmagueta's avatar
rmagueta committed
1751 1752 1753
                       NR_DL_DCI_FORMAT_1_0,
                       NR_RNTI_TC,
                       pdsch_pdu_rel15->BWPSize,
francescomani's avatar
francescomani committed
1754
                       dl_bwp->bwp_id,
1755
                       coreset,
1756
                       nr_mac->cset0_bwp_size);
cig's avatar
cig committed
1757

1758
    // Add padding header and zero rest out if there is space left
1759 1760
    if (ra->mac_pdu_length < harq->tb_size) {
      NR_MAC_SUBHEADER_FIXED *padding = (NR_MAC_SUBHEADER_FIXED *) &buf[ra->mac_pdu_length];
1761 1762
      padding->R = 0;
      padding->LCID = DL_SCH_LCID_PADDING;
1763
      for(int k = ra->mac_pdu_length+1; k<harq->tb_size; k++) {
1764 1765 1766 1767
        buf[k] = 0;
      }
    }

1768
    T(T_GNB_MAC_DL_PDU_WITH_DATA, T_INT(module_idP), T_INT(CC_id), T_INT(ra->rnti),
1769
      T_INT(frameP), T_INT(slotP), T_INT(current_harq_pid), T_BUFFER(harq->transportBlock, harq->tb_size));
1770

cig's avatar
cig committed
1771
    // DL TX request
1772
    nfapi_nr_pdu_t *tx_req = &nr_mac->TX_req[CC_id].pdu_list[nr_mac->TX_req[CC_id].Number_of_PDUs];
1773
    memcpy(tx_req->TLVs[0].value.direct, harq->transportBlock, sizeof(uint8_t) * harq->tb_size);
1774
    tx_req->PDU_length =  harq->tb_size;
1775
    tx_req->PDU_index = pduindex;
cig's avatar
cig committed
1776
    tx_req->num_TLV = 1;
1777
    tx_req->TLVs[0].length =  harq->tb_size + 2;
cig's avatar
cig committed
1778 1779 1780
    nr_mac->TX_req[CC_id].SFN = frameP;
    nr_mac->TX_req[CC_id].Number_of_PDUs++;
    nr_mac->TX_req[CC_id].Slot = slotP;
1781

1782
    // Mark the corresponding symbols and RBs as used
1783 1784
    fill_pdcch_vrb_map(nr_mac,
                       CC_id,
1785
                       &ra->sched_pdcch,
1786 1787
                       CCEIndex,
                       aggregation_level);
1788
    for (int rb = 0; rb < pdsch_pdu_rel15->rbSize; rb++) {
francescomani's avatar
francescomani committed
1789
      vrb_map[BWPStart + rb + pdsch_pdu_rel15->rbStart] |= SL_to_bitmap(msg4_tda.startSymbolIndex, msg4_tda.nrOfSymbols);
1790
    }
1791

rmagueta's avatar
rmagueta committed
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
    LOG_D(NR_MAC,"BWPSize: %i\n", pdcch_pdu_rel15->BWPSize);
    LOG_D(NR_MAC,"BWPStart: %i\n", pdcch_pdu_rel15->BWPStart);
    LOG_D(NR_MAC,"SubcarrierSpacing: %i\n", pdcch_pdu_rel15->SubcarrierSpacing);
    LOG_D(NR_MAC,"CyclicPrefix: %i\n", pdcch_pdu_rel15->CyclicPrefix);
    LOG_D(NR_MAC,"StartSymbolIndex: %i\n", pdcch_pdu_rel15->StartSymbolIndex);
    LOG_D(NR_MAC,"DurationSymbols: %i\n", pdcch_pdu_rel15->DurationSymbols);
    for(int n=0;n<6;n++) LOG_D(NR_MAC,"FreqDomainResource[%i]: %x\n",n, pdcch_pdu_rel15->FreqDomainResource[n]);
    LOG_D(NR_MAC,"CceRegMappingType: %i\n", pdcch_pdu_rel15->CceRegMappingType);
    LOG_D(NR_MAC,"RegBundleSize: %i\n", pdcch_pdu_rel15->RegBundleSize);
    LOG_D(NR_MAC,"InterleaverSize: %i\n", pdcch_pdu_rel15->InterleaverSize);
    LOG_D(NR_MAC,"CoreSetType: %i\n", pdcch_pdu_rel15->CoreSetType);
    LOG_D(NR_MAC,"ShiftIndex: %i\n", pdcch_pdu_rel15->ShiftIndex);
    LOG_D(NR_MAC,"precoderGranularity: %i\n", pdcch_pdu_rel15->precoderGranularity);
    LOG_D(NR_MAC,"numDlDci: %i\n", pdcch_pdu_rel15->numDlDci);

1807
    if(ra->msg3_dcch_dtch) {
1808
      // If the UE used MSG3 to transfer a DCCH or DTCH message, then contention resolution is successful upon transmission of PDCCH
1809
      LOG_A(NR_MAC, "(ue rnti 0x%04x) CBRA procedure succeeded!\n", ra->rnti);
1810
      nr_clear_ra_proc(module_idP, CC_id, frameP, ra);
1811
      UE->Msg3_dcch_dtch = true;
Laurent THOMAS's avatar
Laurent THOMAS committed
1812
      UE->Msg4_ACKed = true;
1813
      UE->ra_timer = 0;
1814 1815 1816 1817 1818 1819 1820

      remove_front_nr_list(&sched_ctrl->feedback_dl_harq);
      harq->feedback_slot = -1;
      harq->is_waiting = false;
      add_tail_nr_list(&sched_ctrl->available_dl_harq, current_harq_pid);
      harq->round = 0;
      harq->ndi ^= 1;
1821

1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
      if(!UE->CellGroup)
        // In the  specific scenario where UE correctly received MSG4 (assuming it decoded RRCsetup with CellGroup) and gNB didn't correctly received an ACK, 
        // the UE would already have CG but the UE-dedicated gNB structure wouldn't (because RA didn't complete on gNB side).
        uper_decode(NULL,
                    &asn_DEF_NR_CellGroupConfig,   //might be added prefix later
                    (void **)&UE->CellGroup,
                    (uint8_t *)UE->cg_buf,
                    (UE->enc_rval.encoded+7)/8, 0, 0);
      process_CellGroup(UE->CellGroup, sched_ctrl);
      configure_UE_BWP(nr_mac, scc, sched_ctrl, NULL, UE);
1832 1833 1834 1835

      // Reset uplink failure flags/counters/timers at MAC so gNB will resume again scheduling resources for this UE
      UE->UE_sched_ctrl.pusch_consecutive_dtx_cnt = 0;
      UE->UE_sched_ctrl.ul_failure = 0;
1836 1837 1838 1839
    } else {
      ra->state = WAIT_Msg4_ACK;
      LOG_D(NR_MAC,"[gNB %d][RAPROC] Frame %d, Subframe %d: RA state %d\n", module_idP, frameP, slotP, ra->state);
    }
1840 1841
  }
}
1842

1843
void nr_check_Msg4_Ack(module_id_t module_id, int CC_id, frame_t frame, sub_frame_t slot, NR_RA_t *ra) {
1844

1845
  NR_UE_info_t *UE = find_nr_UE(&RC.nrmac[module_id]->UE_info, ra->rnti);
1846 1847
  const int current_harq_pid = ra->harq_pid;

Laurent THOMAS's avatar
Laurent THOMAS committed
1848
  NR_UE_sched_ctrl_t *sched_ctrl = &UE->UE_sched_ctrl;
francescomani's avatar
francescomani committed
1849
  NR_UE_harq_t *harq = &sched_ctrl->harq_processes[current_harq_pid];
Laurent THOMAS's avatar
Laurent THOMAS committed
1850
  NR_mac_stats_t *stats = &UE->mac_stats;
1851

Laurent THOMAS's avatar
Laurent THOMAS committed
1852
  LOG_D(NR_MAC, "ue rnti 0x%04x, harq is waiting %d, round %d, frame %d %d, harq id %d\n", ra->rnti, harq->is_waiting, harq->round, frame, slot, current_harq_pid);
1853

1854 1855
  if (harq->is_waiting == 0) {
    if (harq->round == 0) {
Laurent THOMAS's avatar
Laurent THOMAS committed
1856

1857
      if (stats->dl.errors == 0) {
Laurent THOMAS's avatar
Laurent THOMAS committed
1858 1859
        LOG_A(NR_MAC, "(UE RNTI 0x%04x) Received Ack of RA-Msg4. CBRA procedure succeeded!\n", ra->rnti);
        UE->Msg4_ACKed = true;
1860
        UE->ra_timer = 0;
1861

1862
        // Pause scheduling according to:
1863
        // 3GPP TS 38.331 Section 12 Table 12.1-1: UE performance requirements for RRC procedures for UEs
Laurent THOMAS's avatar
Laurent THOMAS committed
1864
        const NR_ServingCellConfig_t *servingCellConfig = UE->CellGroup ? UE->CellGroup->spCellConfig->spCellConfigDedicated : NULL;
1865 1866
        uint32_t delay_ms = servingCellConfig && servingCellConfig->downlinkBWP_ToAddModList ?
            NR_RRC_SETUP_DELAY_MS + NR_RRC_BWP_SWITCHING_DELAY_MS : NR_RRC_SETUP_DELAY_MS;
luis_pereira87's avatar
luis_pereira87 committed
1867

1868
        sched_ctrl->rrc_processing_timer = (delay_ms << ra->DL_BWP.scs);
Laurent THOMAS's avatar
Laurent THOMAS committed
1869
        LOG_I(NR_MAC, "(%d.%d) Activating RRC processing timer for UE %04x with %d ms\n", frame, slot, UE->rnti, delay_ms);
1870
      } else {
Laurent THOMAS's avatar
Laurent THOMAS committed
1871
        LOG_I(NR_MAC, "(ue rnti 0x%04x) RA Procedure failed at Msg4!\n", ra->rnti);
1872 1873 1874
      }

      nr_clear_ra_proc(module_id, CC_id, frame, ra);
1875
      if (sched_ctrl->retrans_dl_harq.head >= 0) {
1876
        remove_nr_list(&sched_ctrl->retrans_dl_harq, current_harq_pid);
1877
      }
1878
    } else {
Laurent THOMAS's avatar
Laurent THOMAS committed
1879
      LOG_I(NR_MAC, "(UE %04x) Received Nack of RA-Msg4. Preparing retransmission!\n", ra->rnti);
1880 1881
      ra->state = Msg4;
    }
cig's avatar
cig committed
1882
  }
1883 1884
}

1885
void nr_clear_ra_proc(module_id_t module_idP, int CC_id, frame_t frameP, NR_RA_t *ra){
1886
  LOG_D(NR_MAC,"[gNB %d][RAPROC] CC_id %d Frame %d Clear Random access information rnti %x\n", module_idP, CC_id, frameP, ra->rnti);
1887
  ra->state = RA_IDLE;
cig's avatar
cig committed
1888 1889 1890
  ra->timing_offset = 0;
  ra->RRC_timer = 20;
  ra->msg3_round = 0;
1891
  ra->msg3_dcch_dtch = false;
1892
  ra->crnti = 0;
1893 1894 1895
  if(ra->cfra == false) {
    ra->rnti = 0;
  }
1896 1897
}

1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922

/////////////////////////////////////
//    Random Access Response PDU   //
//         TS 38.213 ch 8.2        //
//        TS 38.321 ch 6.2.3       //
/////////////////////////////////////
//| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |// bit-wise
//| E | T |       R A P I D       |//
//| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |//
//| R |           T A             |//
//|       T A         |  UL grant |//
//|            UL grant           |//
//|            UL grant           |//
//|            UL grant           |//
//|         T C - R N T I         |//
//|         T C - R N T I         |//
/////////////////////////////////////
//       UL grant  (27 bits)       //
/////////////////////////////////////
//| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |// bit-wise
//|-------------------|FHF|F_alloc|//
//|        Freq allocation        |//
//|    F_alloc    |Time allocation|//
//|      MCS      |     TPC   |CSI|//
/////////////////////////////////////
cig's avatar
cig committed
1923
// WIP
cig's avatar
cig committed
1924 1925 1926
// todo:
// - handle MAC RAR BI subheader
// - sending only 1 RAR subPDU
1927
// - UL Grant: hardcoded CSI, TPC, time alloc
cig's avatar
cig committed
1928
// - padding
1929 1930
void nr_fill_rar(uint8_t Mod_idP,
                 NR_RA_t * ra,
cig's avatar
cig committed
1931
                 uint8_t * dlsch_buffer,
1932
                 nfapi_nr_pusch_pdu_t  *pusch_pdu){
cig's avatar
cig committed
1933

1934
  LOG_D(NR_MAC, "[gNB] Generate RAR MAC PDU frame %d slot %d preamble index %u TA command %d \n", ra->Msg2_frame, ra-> Msg2_slot, ra->preamble_index, ra->timing_offset);
1935 1936 1937
  NR_RA_HEADER_BI *rarbi = (NR_RA_HEADER_BI *) dlsch_buffer;
  NR_RA_HEADER_RAPID *rarh = (NR_RA_HEADER_RAPID *) (dlsch_buffer + 1);
  NR_MAC_RAR *rar = (NR_MAC_RAR *) (dlsch_buffer + 2);
Francesco Mani's avatar
Francesco Mani committed
1938
  unsigned char csi_req = 0, tpc_command;
1939

Francesco Mani's avatar
Francesco Mani committed
1940 1941
  tpc_command = 3; // this is 0 dB

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
  /// E/T/R/R/BI subheader ///
  // E = 1, MAC PDU includes another MAC sub-PDU (RAPID)
  // T = 0, Back-off indicator subheader
  // R = 2, Reserved
  // BI = 0, 5ms
  rarbi->E = 1;
  rarbi->T = 0;
  rarbi->R = 0;
  rarbi->BI = 0;

1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
  /// E/T/RAPID subheader ///
  // E = 0, one only RAR, first and last
  // T = 1, RAPID
  rarh->E = 0;
  rarh->T = 1;
  rarh->RAPID = ra->preamble_index;

  /// RAR MAC payload ///
  rar->R = 0;

  // TA command
  rar->TA1 = (uint8_t) (ra->timing_offset >> 5);    // 7 MSBs of timing advance
  rar->TA2 = (uint8_t) (ra->timing_offset & 0x1f);  // 5 LSBs of timing advance

  // TC-RNTI
  rar->TCRNTI_1 = (uint8_t) (ra->rnti >> 8);        // 8 MSBs of rnti
  rar->TCRNTI_2 = (uint8_t) (ra->rnti & 0xff);      // 8 LSBs of rnti

  // UL grant
1971

1972
  ra->msg3_TPC = tpc_command;
1973

1974
  if (pusch_pdu->frequency_hopping)
1975
    AssertFatal(1==0,"PUSCH with frequency hopping currently not supported");
1976

1977 1978 1979 1980 1981 1982
  int bwp_size = pusch_pdu->bwp_size;
  int prb_alloc = PRBalloc_to_locationandbandwidth0(ra->msg3_nb_rb, ra->msg3_first_rb, bwp_size);
  int valid_bits = 14;
  int f_alloc = prb_alloc & ((1 << valid_bits) - 1);

  uint32_t ul_grant = csi_req | (tpc_command << 1) | (pusch_pdu->mcs_index << 4) | (ra->Msg3_tda_id << 8) | (f_alloc << 12) | (pusch_pdu->frequency_hopping << 26);
1983

1984 1985 1986 1987
  rar->UL_GRANT_1 = (uint8_t) (ul_grant >> 24) & 0x07;
  rar->UL_GRANT_2 = (uint8_t) (ul_grant >> 16) & 0xff;
  rar->UL_GRANT_3 = (uint8_t) (ul_grant >> 8) & 0xff;
  rar->UL_GRANT_4 = (uint8_t) ul_grant & 0xff;
1988

rmagueta's avatar
rmagueta committed
1989
#ifdef DEBUG_RAR
rmagueta's avatar
rmagueta committed
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
  LOG_I(NR_MAC, "rarh->E = 0x%x\n", rarh->E);
  LOG_I(NR_MAC, "rarh->T = 0x%x\n", rarh->T);
  LOG_I(NR_MAC, "rarh->RAPID = 0x%x (%i)\n", rarh->RAPID, rarh->RAPID);
  LOG_I(NR_MAC, "rar->R = 0x%x\n", rar->R);
  LOG_I(NR_MAC, "rar->TA1 = 0x%x\n", rar->TA1);
  LOG_I(NR_MAC, "rar->TA2 = 0x%x\n", rar->TA2);
  LOG_I(NR_MAC, "rar->UL_GRANT_1 = 0x%x\n", rar->UL_GRANT_1);
  LOG_I(NR_MAC, "rar->UL_GRANT_2 = 0x%x\n", rar->UL_GRANT_2);
  LOG_I(NR_MAC, "rar->UL_GRANT_3 = 0x%x\n", rar->UL_GRANT_3);
  LOG_I(NR_MAC, "rar->UL_GRANT_4 = 0x%x\n", rar->UL_GRANT_4);
  LOG_I(NR_MAC, "rar->TCRNTI_1 = 0x%x\n", rar->TCRNTI_1);
  LOG_I(NR_MAC, "rar->TCRNTI_2 = 0x%x\n", rar->TCRNTI_2);
rmagueta's avatar
rmagueta committed
2002
#endif
rmagueta's avatar
rmagueta committed
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015

  int mcs = (unsigned char) (rar->UL_GRANT_4 >> 4);
  // time alloc
  int Msg3_t_alloc = (unsigned char) (rar->UL_GRANT_3 & 0x07);
  // frequency alloc
  int Msg3_f_alloc = (uint16_t) ((rar->UL_GRANT_3 >> 4) | (rar->UL_GRANT_2 << 4) | ((rar->UL_GRANT_1 & 0x03) << 12));
  // frequency hopping
  int freq_hopping = (unsigned char) (rar->UL_GRANT_1 >> 2);
  // TA command
  int  ta_command = rar->TA2 + (rar->TA1 << 5);
  // TC-RNTI
  int t_crnti = rar->TCRNTI_2 + (rar->TCRNTI_1 << 8);

rmagueta's avatar
rmagueta committed
2016
  LOG_D(NR_MAC, "In %s: Transmitted RAR with t_alloc %d f_alloc %d ta_command %d mcs %d freq_hopping %d tpc_command %d csi_req %d t_crnti %x \n",
rmagueta's avatar
rmagueta committed
2017 2018 2019 2020 2021 2022 2023 2024 2025
        __FUNCTION__,
        Msg3_t_alloc,
        Msg3_f_alloc,
        ta_command,
        mcs,
        freq_hopping,
        tpc_command,
        csi_req,
        t_crnti);
2026
}