gNB_scheduler_RA.c 87.8 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

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

49
uint8_t DELTA[4]= {2,3,4,6};
50

51 52 53 54 55
#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
56 57 58 59 60 61
			     sub_frame_t slotP,
			     uint16_t preamble_index,
			     uint8_t freq_index,
			     uint8_t symbol) {
  
  gNB_MAC_INST *gNB = RC.nrmac[module_idP];
62
  NR_COMMON_channels_t *cc = &gNB->common_channels[0];
63 64 65 66
  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;
67
  uint8_t fdm = cfg->prach_config.num_prach_fd_occasions.value;
kn.raju's avatar
kn.raju committed
68
  
69
  uint8_t total_RApreambles = MAX_NUM_NR_PRACH_PREAMBLES;
70
  if( scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->totalNumberOfRA_Preambles != NULL)
kn.raju's avatar
kn.raju committed
71 72
    total_RApreambles = *scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->totalNumberOfRA_Preambles;	
  
73
  float  num_ssb_per_RO = ssb_per_rach_occasion[cfg->prach_config.ssb_per_rach.value];	
74
  uint16_t start_symbol_index = 0;
75
  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
76
  uint16_t format,RA_sfn_index = -1;
77
  uint8_t config_period = 1;
kn.raju's avatar
kn.raju committed
78
  uint16_t prach_occasion_id = -1;
79
  uint8_t num_active_ssb = cc->num_active_ssb;
80 81 82 83 84 85 86

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

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

134
  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",
135 136
        frameP, slotP, prach_occasion_id, num_ssb_per_RO, num_active_ssb, index, fdm, start_symbol_index, freq_index, total_RApreambles);

137 138
  return index;
}
139 140


141 142 143
//Compute Total active SSBs and RO available
void find_SSB_and_RO_available(module_id_t module_idP) {

144
  gNB_MAC_INST *gNB = RC.nrmac[module_idP];
145
  NR_COMMON_channels_t *cc = &gNB->common_channels[0];
146 147 148 149
  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;
150
  uint8_t mu,N_dur=0,N_t_slot=0,start_symbol=0,N_RA_slot = 0;
kn.raju's avatar
kn.raju committed
151
  uint16_t format,N_RA_sfn = 0,unused_RA_occasion,repetition = 0;
152
  uint8_t num_active_ssb = 0;
153
  uint8_t max_association_period = 1;
154

kn.raju's avatar
kn.raju committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  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;
    }

187 188 189 190 191 192 193
  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,
194 195 196 197 198 199 200 201 202 203
                                        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);
204 205

  float num_ssb_per_RO = ssb_per_rach_occasion[cfg->prach_config.ssb_per_rach.value];	
206
  uint8_t fdm = cfg->prach_config.num_prach_fd_occasions.value;
207
  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 ;
208
  uint32_t total_RA_occasions = N_RA_sfn * N_t_slot * N_RA_slot * fdm;
209

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

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

227 228 229
  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
230

231
  LOG_I(NR_MAC,
kn.raju's avatar
kn.raju committed
232 233 234 235 236 237 238
        "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);
239 240
}		
		
241 242
void schedule_nr_prach(module_id_t module_idP, frame_t frameP, sub_frame_t slotP)
{
243 244 245
  gNB_MAC_INST *gNB = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = gNB->common_channels;
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
246
  nfapi_nr_ul_tti_request_t *UL_tti_req = &RC.nrmac[module_idP]->UL_tti_req_ahead[0][slotP];
247
  nfapi_nr_config_request_scf_t *cfg = &RC.nrmac[module_idP]->config[0];
248

249
  if (is_nr_UL_slot(scc->tdd_UL_DL_ConfigurationCommon, slotP, cc->frame_type)) {
250

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    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;

    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;
      }
291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
      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)){

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

317
            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",
318 319 320 321 322 323 324 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
                  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");
              }
            }
          }
379
        }
380
      }
381 382 383 384 385 386 387 388 389 390

      // 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)
        vrb_map_UL[rach_ConfigGeneric->msg1_FrequencyStart + i] = 0xff; // all symbols
391 392 393 394 395 396 397 398
    }
  }
}

void nr_schedule_msg2(uint16_t rach_frame, uint16_t rach_slot,
                      uint16_t *msg2_frame, uint16_t *msg2_slot,
                      NR_ServingCellConfigCommon_t *scc,
                      uint16_t monitoring_slot_period,
399
                      uint16_t monitoring_offset,uint8_t beam_index,
400
                      uint8_t num_active_ssb,
401
                      int16_t *tdd_beam_association){
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

  // 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 mu = *scc->ssbSubcarrierSpacing;
  uint8_t response_window = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->rach_ConfigGeneric.ra_ResponseWindow;
  uint8_t slot_window;
  // number of mixed slot or of last dl slot if there is no mixed slot
  uint8_t last_dl_slot_period = scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSlots;
  // lenght of tdd period in slots
  uint8_t tdd_period_slot =  scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSlots + scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSlots;
  if (scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSymbols == 0)
    last_dl_slot_period--;
  if ((scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSymbols > 0) || (scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSymbols > 0))
    tdd_period_slot++;

  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
446
  AssertFatal(slot_window<=nr_slots_per_frame[mu],"Msg2 response window needs to be lower or equal to 10ms");
447 448

  // slot and frame limit to transmit msg2 according to response window
cig's avatar
cig committed
449
  uint8_t slot_limit = (rach_slot + slot_window)%nr_slots_per_frame[mu];
Francesco Mani's avatar
Francesco Mani committed
450
  uint8_t frame_limit = (slot_limit>(rach_slot))? rach_frame : (rach_frame +1);
451

452 453 454 455 456
  // computing start of next period

  int FR = *scc->downlinkConfigCommon->frequencyInfoDL->frequencyBandList.list.array[0] >= 257 ? nr_FR2 : nr_FR1;

  uint8_t start_next_period = (rach_slot-(rach_slot%tdd_period_slot)+tdd_period_slot)%nr_slots_per_frame[mu];
457
  *msg2_slot = start_next_period + last_dl_slot_period; // initializing scheduling of slot to next mixed (or last dl) slot
rmagueta's avatar
rmagueta committed
458
  *msg2_frame = ((*msg2_slot>(rach_slot))? rach_frame : (rach_frame+1))%1024;
459 460 461 462 463

  // we can't schedule msg2 before sl_ahead since prach
  int eff_slot = *msg2_slot+(*msg2_frame-rach_frame)*nr_slots_per_frame[mu];
  if ((eff_slot-rach_slot)<=sl_ahead) {
    *msg2_slot = (*msg2_slot+tdd_period_slot)%nr_slots_per_frame[mu];
rmagueta's avatar
rmagueta committed
464
    *msg2_frame = ((*msg2_slot>(rach_slot))? rach_frame : (rach_frame+1))%1024;
465 466 467 468 469
  }
  if (FR==nr_FR2) {
    int num_tdd_period = *msg2_slot/tdd_period_slot;
    while((tdd_beam_association[num_tdd_period]!=-1)&&(tdd_beam_association[num_tdd_period]!=beam_index)) {
      *msg2_slot = (*msg2_slot+tdd_period_slot)%nr_slots_per_frame[mu];
rmagueta's avatar
rmagueta committed
470
      *msg2_frame = ((*msg2_slot>(rach_slot))? rach_frame : (rach_frame+1))%1024;
471 472 473 474 475 476
      num_tdd_period = *msg2_slot/tdd_period_slot;
    }
    if(tdd_beam_association[num_tdd_period] == -1)
      tdd_beam_association[num_tdd_period] = beam_index;
  }

477 478
  // 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)
Francesco Mani's avatar
Francesco Mani committed
479
  while (((*msg2_slot>slot_limit)&&(*msg2_frame>frame_limit)) || ((*msg2_frame*nr_slots_per_frame[mu]+*msg2_slot-monitoring_offset)%monitoring_slot_period !=0))  {
480
    if((*msg2_slot%tdd_period_slot) > 0)
Raphael Defosseux's avatar
Raphael Defosseux committed
481
      (*msg2_slot)--;
482 483 484
    else
      AssertFatal(1==0,"No available DL slot to schedule msg2 has been found");
  }
cig's avatar
cig committed
485
}
486

487

488 489 490 491 492
void nr_initiate_ra_proc(module_id_t module_idP,
                         int CC_id,
                         frame_t frameP,
                         sub_frame_t slotP,
                         uint16_t preamble_index,
493 494
                         uint8_t freq_index,
                         uint8_t symbol,
495 496
                         int16_t timing_offset){

497 498
  uint8_t ul_carrier_id = 0; // 0 for NUL 1 for SUL
  NR_SearchSpace_t *ss;
499

500
  uint16_t msg2_frame, msg2_slot,monitoring_slot_period,monitoring_offset;
cig's avatar
cig committed
501 502
  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];
503
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
kn.raju's avatar
kn.raju committed
504

505
  uint8_t total_RApreambles = MAX_NUM_NR_PRACH_PREAMBLES;
506
  uint8_t  num_ssb_per_RO = scc->uplinkConfigCommon->initialUplinkBWP->rach_ConfigCommon->choice.setup->ssb_perRACH_OccasionAndCB_PreamblesPerSSB->present;
507 508
  int pr_found;

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

kn.raju's avatar
kn.raju committed
512 513 514 515
  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 ;
  }
516

517 518
  for (int i = 0; i < NR_NB_RA_PROC_MAX; i++) {
    NR_RA_t *ra = &cc->ra[i];
519
    pr_found = 0;
520
    if (ra->state == RA_IDLE) {
521 522 523 524 525 526 527 528
      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]) {
          pr_found=1;
          break;
        }
      }
      if (pr_found == 0) {
529
         continue;
530
      }
531

532
      uint16_t ra_rnti;
rmagueta's avatar
rmagueta committed
533

534 535 536 537 538 539 540 541 542
      // 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);

      // This should be handled differently when we use the initialBWP for RA
543 544 545
      ra->bwp_id = 0;
      NR_BWP_Downlink_t *bwp=NULL;
      if (ra->CellGroup && ra->CellGroup->spCellConfig && ra->CellGroup->spCellConfig->spCellConfigDedicated &&
546 547
          ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList) {
        ra->bwp_id = 1;
francescomani's avatar
francescomani committed
548
        bwp = ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id - 1];
549
      }
550

551 552
      VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_INITIATE_RA_PROC, 1);

553
      LOG_D(NR_MAC,
554 555 556 557 558 559
            "[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);
560 561 562 563 564 565 566 567

      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(
568
              NR_MAC,
569 570 571 572 573
              "[gNB %d][RAPROC] FAILURE: preamble %d does not correspond to any of the ones in rach_ConfigDedicated\n",
              module_idP,
              preamble_index);
          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
574
      }
575
      LOG_D(NR_MAC, "Frame %d, Slot %d: Activating RA process \n", frameP, slotP);
576 577 578 579
      ra->state = Msg2;
      ra->timing_offset = timing_offset;
      ra->preamble_slot = slotP;

580 581 582 583 584 585 586 587 588
      NR_SearchSpaceId_t	ra_SearchSpace = 0;
      struct NR_PDCCH_ConfigCommon__commonSearchSpaceList *commonSearchSpaceList = NULL;
      if(bwp) {
        commonSearchSpaceList = bwp->bwp_Common->pdcch_ConfigCommon->choice.setup->commonSearchSpaceList;
        ra_SearchSpace = *bwp->bwp_Common->pdcch_ConfigCommon->choice.setup->ra_SearchSpace;
      } else {
        commonSearchSpaceList = scc->downlinkConfigCommon->initialDownlinkBWP->pdcch_ConfigCommon->choice.setup->commonSearchSpaceList;
        ra_SearchSpace = *scc->downlinkConfigCommon->initialDownlinkBWP->pdcch_ConfigCommon->choice.setup->ra_SearchSpace;
      }
589
      AssertFatal(commonSearchSpaceList->list.count > 0, "common SearchSpace list has 0 elements\n");
590

591
      // Common SearchSpace list
592 593
      for (int i = 0; i < commonSearchSpaceList->list.count; i++) {
        ss = commonSearchSpaceList->list.array[i];
594
        if (ss->searchSpaceId == ra_SearchSpace)
595
          ra->ra_ss = ss;
Francesco Mani's avatar
Francesco Mani committed
596
      }
597

598 599
      AssertFatal(ra->ra_ss!=NULL,"SearchSpace cannot be null for RA\n");

600 601 602 603 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,
                       scc,
                       monitoring_slot_period,
                       monitoring_offset,
                       beam_index,
611 612
                       cc->num_active_ssb,
                       nr_mac->tdd_beam_association);
613 614 615 616

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

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

      int loop = 0;
620
      if (ra->rnti == 0) { // This condition allows for the usage of a preconfigured rnti for the CFRA
621 622 623 624 625 626 627
        do {
          ra->rnti = (taus() % 65518) + 1;
          loop++;
        } while (loop != 100
                 && !((find_nr_UE_id(module_idP, ra->rnti) == -1) && (find_nr_RA_id(module_idP, CC_id, ra->rnti) == -1)
                      && ra->rnti >= 1 && ra->rnti <= 65519));
        if (loop == 100) {
628
          LOG_E(NR_MAC, "%s:%d:%s: [RAPROC] initialisation random access aborted\n", __FILE__, __LINE__, __FUNCTION__);
629 630 631
          abort();
        }
      }
632

633 634 635 636
      ra->RA_rnti = ra_rnti;
      ra->preamble_index = preamble_index;
      ra->beam_id = beam_index;

637
      LOG_D(NR_MAC,
638 639 640 641 642 643 644 645 646 647 648
            "[gNB %d][RAPROC] CC_id %d Frame %d Activating Msg2 generation in frame %d, slot %d using RA rnti %x SSB "
            "index %u\n",
            module_idP,
            CC_id,
            frameP,
            ra->Msg2_frame,
            ra->Msg2_slot,
            ra->RA_rnti,
            cc->ssb_index[beam_index]);

      return;
cig's avatar
cig committed
649
    }
650
  }
651
  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);
652

cig's avatar
cig committed
653
  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_INITIATE_RA_PROC, 0);
654 655
}

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
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;
681 682
      }
    }
cig's avatar
cig committed
683
  }
684 685 686 687 688 689 690 691 692 693
  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;

rmagueta's avatar
rmagueta committed
694 695 696 697 698 699 700 701 702 703 704 705 706
  NR_BWP_Uplink_t *ubwp = NULL;
  NR_BWP_UplinkDedicated_t *ubwpd = NULL;
  NR_PUSCH_TimeDomainResourceAllocationList_t *pusch_TimeDomainAllocationList = NULL;
  NR_BWP_t *genericParameters = NULL;
  if(ra->CellGroup) {
    ubwp = ra->CellGroup->spCellConfig->spCellConfigDedicated->uplinkConfig->uplinkBWP_ToAddModList->list.array[ra->bwp_id-1];
    ubwpd = ra->CellGroup->spCellConfig->spCellConfigDedicated->uplinkConfig->initialUplinkBWP;
    genericParameters = &ubwp->bwp_Common->genericParameters;
    pusch_TimeDomainAllocationList = ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList;
  } else {
    genericParameters = &scc->uplinkConfigCommon->initialUplinkBWP->genericParameters;
    pusch_TimeDomainAllocationList = scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList;
  }
707

rmagueta's avatar
rmagueta committed
708
  int mu = genericParameters->subcarrierSpacing;
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
  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) {
      uint8_t tdd_period_slot =  scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSlots + scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSlots;
      if ((scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSymbols > 0) || (scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSymbols > 0))
        tdd_period_slot++;
      int num_tdd_period = sched_slot/tdd_period_slot;
      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 bwpSize = NRRIV2BW(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
    int bwpStart = NRRIV2PRBOFFSET(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
    int scs = scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.subcarrierSpacing;
    int fh = 0;
    int startSymbolAndLength = scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->startSymbolAndLength;
    int mappingtype = scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->mappingType;

    if (ra->CellGroup) {
      AssertFatal(ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.count == 1,
                  "downlinkBWP_ToAddModList has %d BWP!\n", ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.count);
      int act_bwp_start = NRRIV2PRBOFFSET(ubwp->bwp_Common->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
      int act_bwp_size  = NRRIV2BW(ubwp->bwp_Common->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
      startSymbolAndLength = ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->startSymbolAndLength;
      mappingtype = ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->mappingType;
      scs = ubwp->bwp_Common->genericParameters.subcarrierSpacing;
      fh = ubwp->bwp_Dedicated->pusch_Config->choice.setup->frequencyHopping ? 1 : 0;
      if ((bwpStart < act_bwp_start) || (bwpSize > act_bwp_size))
        bwpStart = act_bwp_start;
    }
    uint16_t *vrb_map_UL =
        &RC.nrmac[module_idP]->common_channels[CC_id].vrb_map_UL[sched_slot * MAX_BWP_SIZE];

    int rbStart = 0;
    for (int i = 0; (i < ra->msg3_nb_rb) && (rbStart <= (bwpSize - ra->msg3_nb_rb)); i++) {
      if (vrb_map_UL[rbStart + bwpStart + i]) {
        rbStart += i;
        i = 0;
754 755
      }
    }
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
    if (rbStart > (bwpSize - ra->msg3_nb_rb)) {
      // 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);
    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,
778
                        ra->msg3_round,
779 780 781 782 783 784 785 786 787 788 789
                        startSymbolAndLength,
                        ra->rnti, scs,
                        bwpSize, bwpStart,
                        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;
    NR_BWP_Downlink_t *bwp = NULL;
    NR_ControlResourceSet_t *coreset = NULL;
rmagueta's avatar
rmagueta committed
790
    NR_Type0_PDCCH_CSS_config_t *type0_PDCCH_CSS_config = *ss->controlResourceSetId==0 ? &nr_mac->type0_PDCCH_CSS_config[ra->beam_id] : NULL;
791 792 793 794 795 796 797 798

    if (ra->CellGroup &&
        ra->CellGroup->spCellConfig &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id-1])
      bwp = ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id-1];

799 800 801 802
    if (*ss->controlResourceSetId == 0)
      coreset = nr_mac->sched_ctrlCommon->coreset; // this is coreset 0
    else
      coreset = get_coreset(scc, bwp, ss, NR_SearchSpace__searchSpaceType_PR_common);
803 804 805 806 807 808 809 810 811 812 813 814 815
    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;
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_rel15 = nr_mac->pdcch_pdu_idx[CC_id][ra->bwp_id][coresetid];
    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;
rmagueta's avatar
rmagueta committed
816
      nr_configure_pdcch(pdcch_pdu_rel15, ss, coreset, scc, genericParameters, type0_PDCCH_CSS_config);
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
      nr_mac->pdcch_pdu_idx[CC_id][ra->bwp_id][coresetid] = pdcch_pdu_rel15;
    }

    uint8_t aggregation_level;
    uint8_t nr_of_candidates;
    find_aggregation_candidates(&aggregation_level, &nr_of_candidates, ss);
    int CCEIndex = allocate_nr_CCEs(nr_mac, bwp, coreset, aggregation_level, 0, 0, nr_of_candidates);
    if (CCEIndex < 0) {
      LOG_E(NR_MAC, "%s(): cannot find free CCE for RA RNTI %04x!\n", __func__, ra->rnti);
      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));

    config_uldci(ubwp,
rmagueta's avatar
rmagueta committed
844
                 ubwpd,
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
                 scc,
                 pusch_pdu,
                 &uldci_payload,
                 NR_UL_DCI_FORMAT_0_0,
                 ra->Msg3_tda_id,
                 ra->msg3_TPC,
                 0, // not used in format 0_0
                 ra->bwp_id);

    fill_dci_pdu_rel15(scc,
                       ra->CellGroup,
                       dci_pdu,
                       &uldci_payload,
                       NR_UL_DCI_FORMAT_0_0,
                       NR_RNTI_TC,
                       pusch_pdu->bwp_size,
                       ra->bwp_id);

    // Mark the corresponding RBs as used
    for (int rb = 0; rb < ra->msg3_nb_rb; rb++) {
      vrb_map_UL[rbStart + bwpStart + rb] = 1;
    }

    // reset state to wait msg3
    ra->state = WAIT_Msg3;
francescomani's avatar
francescomani committed
870 871
    ra->Msg3_frame = sched_frame;
    ra->Msg3_slot = sched_slot;
872

cig's avatar
cig committed
873
  }
874

875
}
876

877 878 879
void nr_get_Msg3alloc(module_id_t module_id,
                      int CC_id,
                      NR_ServingCellConfigCommon_t *scc,
880
                      NR_BWP_Uplink_t *ubwp,
881 882
                      sub_frame_t current_slot,
                      frame_t current_frame,
rmagueta's avatar
rmagueta committed
883 884
                      NR_RA_t *ra,
                      int16_t *tdd_beam_association) {
885

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  // msg3 is scheduled in mixed slot in the following TDD period

  uint16_t msg3_nb_rb = 8 + sizeof(NR_MAC_SUBHEADER_SHORT) + sizeof(NR_MAC_SUBHEADER_SHORT); // sdu has 6 or 8 bytes

  int mu = ubwp ?
    ubwp->bwp_Common->genericParameters.subcarrierSpacing :
    scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.subcarrierSpacing;
  int StartSymbolIndex = 0;
  int NrOfSymbols = 0;
  int startSymbolAndLength = 0;
  int temp_slot = 0;
  ra->Msg3_tda_id = 16; // initialization to a value above limit

  NR_PUSCH_TimeDomainResourceAllocationList_t *pusch_TimeDomainAllocationList= ubwp ?
    ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList:
    scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList;

  uint8_t k2 = 0;
  for (int i=0; i<pusch_TimeDomainAllocationList->list.count; i++) {
    startSymbolAndLength = pusch_TimeDomainAllocationList->list.array[i]->startSymbolAndLength;
    SLIV2SL(startSymbolAndLength, &StartSymbolIndex, &NrOfSymbols);
    // we want to transmit in the uplink symbols of mixed slot
    if (NrOfSymbols == scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSymbols) {
      k2 = *pusch_TimeDomainAllocationList->list.array[i]->k2;
      temp_slot = current_slot + k2 + DELTA[mu]; // msg3 slot according to 8.3 in 38.213
      ra->Msg3_slot = temp_slot%nr_slots_per_frame[mu];
      if (is_xlsch_in_slot(RC.nrmac[module_id]->ulsch_slot_bitmap[ra->Msg3_slot / 64], ra->Msg3_slot)) {
        ra->Msg3_tda_id = i;
        break;
915
      }
916
    }
917
  }
918

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

921 922 923 924
  if (nr_slots_per_frame[mu]>temp_slot)
    ra->Msg3_frame = current_frame;
  else
    ra->Msg3_frame = (current_frame + (temp_slot/nr_slots_per_frame[mu]))%1024;
925

926 927 928 929 930 931 932 933 934 935 936 937
  // beam association for FR2
  if (*scc->downlinkConfigCommon->frequencyInfoDL->frequencyBandList.list.array[0] >= 257) {
    uint8_t tdd_period_slot =  scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSlots + scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSlots;
    if ((scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofDownlinkSymbols > 0) || (scc->tdd_UL_DL_ConfigurationCommon->pattern1.nrofUplinkSymbols > 0))
      tdd_period_slot++;
    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;
  }

938
  LOG_D(NR_MAC, "[RAPROC] Msg3 slot %d: current slot %u Msg3 frame %u k2 %u Msg3_tda_id %u start symbol index %u\n", ra->Msg3_slot, current_slot, ra->Msg3_frame, k2,ra->Msg3_tda_id, StartSymbolIndex);
939
  uint16_t *vrb_map_UL =
cig's avatar
cig committed
940
      &RC.nrmac[module_id]->common_channels[CC_id].vrb_map_UL[ra->Msg3_slot * MAX_BWP_SIZE];
941
  const uint16_t bwpSize = NRRIV2BW(ubwp ?
942
				    ubwp->bwp_Common->genericParameters.locationAndBandwidth :
943
				    scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth,
944
				    MAX_BWP_SIZE);
rmagueta's avatar
rmagueta committed
945

946
  /* search msg3_nb_rb free RBs */
947 948
  int rbSize = 0;
  int rbStart = 0;
rmagueta's avatar
rmagueta committed
949
  while (rbSize < msg3_nb_rb) {
950 951 952 953
    rbStart += rbSize; /* last iteration rbSize was not enough, skip it */
    rbSize = 0;
    while (rbStart < bwpSize && vrb_map_UL[rbStart])
      rbStart++;
rmagueta's avatar
rmagueta committed
954
    AssertFatal(rbStart < bwpSize - msg3_nb_rb, "no space to allocate Msg 3 for RA!\n");
955 956
    while (rbStart + rbSize < bwpSize
           && !vrb_map_UL[rbStart + rbSize]
rmagueta's avatar
rmagueta committed
957
           && rbSize < msg3_nb_rb)
958
      rbSize++;
959
  }
rmagueta's avatar
rmagueta committed
960
  ra->msg3_nb_rb = msg3_nb_rb;
961
  ra->msg3_first_rb = rbStart;
962 963
}

964 965 966

void fill_msg3_pusch_pdu(nfapi_nr_pusch_pdu_t *pusch_pdu,
                         NR_ServingCellConfigCommon_t *scc,
967
                         int round,
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
                         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;
  SLIV2SL(startSymbolAndLength, &start_symbol_index, &nr_of_symbols);

  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_index = 0;
  pusch_pdu->mcs_table = 0;
  pusch_pdu->target_code_rate = nr_get_code_rate_ul(pusch_pdu->mcs_index,pusch_pdu->mcs_table);
  pusch_pdu->qam_mod_order = nr_get_Qm_ul(pusch_pdu->mcs_index,pusch_pdu->mcs_table);
  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);
  LOG_D(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);
  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;
  //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]
  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
1018
  pusch_pdu->pusch_data.rv_index = nr_rv_round_map[round];
1019
  pusch_pdu->pusch_data.harq_process_id = 0;
1020
  pusch_pdu->pusch_data.new_data_indicator = 1;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
  pusch_pdu->pusch_data.num_cb = 0;
  pusch_pdu->pusch_data.tb_size = nr_compute_tbs(pusch_pdu->qam_mod_order,
                                                 pusch_pdu->target_code_rate,
                                                 pusch_pdu->rb_size,
                                                 pusch_pdu->nr_of_symbols,
                                                 12, // nb dmrs set for no data in dmrs symbol
                                                 0, //nb_rb_oh
                                                 0, // to verify tb scaling
                                                 pusch_pdu->nrOfLayers)>>3;

}

1033 1034
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)
{
cig's avatar
cig committed
1035 1036 1037 1038
  gNB_MAC_INST                                   *mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t                            *cc = &mac->common_channels[CC_id];
  NR_ServingCellConfigCommon_t                   *scc = cc->ServingCellConfigCommon;

1039
  if (ra->state == RA_IDLE) {
1040
    LOG_W(NR_MAC,"RA is not active for RA %X. skipping msg3 scheduling\n", ra->rnti);
1041 1042
    return;
  }
cig's avatar
cig committed
1043

1044
  uint16_t *vrb_map_UL =
1045
      &RC.nrmac[module_idP]->common_channels[CC_id].vrb_map_UL[ra->Msg3_slot * MAX_BWP_SIZE];
1046 1047 1048 1049 1050 1051 1052 1053 1054
  for (int i = 0; i < ra->msg3_nb_rb; ++i) {
    AssertFatal(!vrb_map_UL[i + ra->msg3_first_rb],
                "RB %d in %4d.%2d is already taken, cannot allocate Msg3!\n",
                i + ra->msg3_first_rb,
                ra->Msg3_frame,
                ra->Msg3_slot);
    vrb_map_UL[i + ra->msg3_first_rb] = 1;
  }

1055
  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);
1056

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  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
1068
  memset(pusch_pdu, 0, sizeof(nfapi_nr_pusch_pdu_t));
1069

1070 1071 1072 1073 1074 1075 1076
  int ibwp_size  = NRRIV2BW(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
  int ibwp_start = NRRIV2PRBOFFSET(scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
  int abwp_size = ibwp_size;
  int abwp_start = ibwp_start;
  int scs = scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.subcarrierSpacing;
  int fh = 0;
  int startSymbolAndLength = scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->startSymbolAndLength;
rmagueta's avatar
rmagueta committed
1077
  int mappingtype = scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->mappingType;
1078 1079 1080 1081 1082 1083 1084

  if (ra->CellGroup) {
    AssertFatal(ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.count == 1,
		"downlinkBWP_ToAddModList has %d BWP!\n", ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.count);
    NR_BWP_Uplink_t *ubwp = ra->CellGroup->spCellConfig->spCellConfigDedicated->uplinkConfig->uplinkBWP_ToAddModList->list.array[ra->bwp_id - 1];

    startSymbolAndLength = ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->startSymbolAndLength;
rmagueta's avatar
rmagueta committed
1085
    mappingtype = ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[ra->Msg3_tda_id]->mappingType;
1086 1087 1088 1089 1090
    abwp_size  = NRRIV2BW(ubwp->bwp_Common->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
    abwp_start = NRRIV2PRBOFFSET(ubwp->bwp_Common->genericParameters.locationAndBandwidth, MAX_BWP_SIZE);
    scs = ubwp->bwp_Common->genericParameters.subcarrierSpacing;
    fh = ubwp->bwp_Dedicated->pusch_Config->choice.setup->frequencyHopping ? 1 : 0;
  }
1091

1092
  LOG_D(NR_MAC, "Frame %d, Subframe %d Adding Msg3 UL Config Request for (%d,%d) : (%d,%d,%d) for rnti: %d\n",
1093 1094 1095 1096 1097 1098 1099 1100
    frameP,
    slotP,
    ra->Msg3_frame,
    ra->Msg3_slot,
    ra->msg3_nb_rb,
    ra->msg3_first_rb,
    ra->msg3_round,
    ra->rnti);
1101

1102
  int bwp_start;
1103
  if ((ibwp_start < abwp_start) || (ibwp_size > abwp_size))
1104
    bwp_start = abwp_start;
1105
  else
1106 1107 1108
    bwp_start = ibwp_start;

  fill_msg3_pusch_pdu(pusch_pdu,scc,
1109
                      ra->msg3_round,
1110 1111 1112 1113 1114 1115
                      startSymbolAndLength,
                      ra->rnti, scs,
                      ibwp_size, bwp_start,
                      mappingtype, fh,
                      ra->msg3_first_rb, ra->msg3_nb_rb);
  future_ul_tti_req->n_pdus += 1;
1116 1117

  // calling function to fill rar message
1118
  nr_fill_rar(module_idP, ra, RAR_pdu, pusch_pdu);
cig's avatar
cig committed
1119 1120
}

1121
void nr_generate_Msg2(module_id_t module_idP, int CC_id, frame_t frameP, sub_frame_t slotP, NR_RA_t *ra)
1122
{
1123

rmagueta's avatar
rmagueta committed
1124 1125
  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];
cig's avatar
cig committed
1126

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

1129
    uint8_t time_domain_assignment = 1;
rmagueta's avatar
rmagueta committed
1130
    uint8_t mcsIndex = 0;
1131
    int rbStart = 0;
1132
    int rbSize = 8;
1133

rmagueta's avatar
rmagueta committed
1134
    NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
1135 1136
    NR_SearchSpace_t *ss = ra->ra_ss;

rmagueta's avatar
rmagueta committed
1137 1138
    NR_BWP_Downlink_t *bwp = NULL;
    NR_ControlResourceSet_t *coreset = NULL;
1139 1140 1141 1142
    NR_BWP_t *genericParameters = NULL;
    NR_PDSCH_TimeDomainResourceAllocationList_t *pdsch_TimeDomainAllocationList=NULL;

    if (ra->CellGroup &&
1143 1144 1145 1146
        ra->CellGroup->spCellConfig &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id-1]) {
1147 1148 1149
      bwp = ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id-1];
      genericParameters = &bwp->bwp_Common->genericParameters;
      pdsch_TimeDomainAllocationList = bwp->bwp_Common->pdsch_ConfigCommon->choice.setup->pdsch_TimeDomainAllocationList;
rmagueta's avatar
rmagueta committed
1150
    }
1151 1152 1153
    else {
      genericParameters= &scc->downlinkConfigCommon->initialDownlinkBWP->genericParameters;
      pdsch_TimeDomainAllocationList = scc->downlinkConfigCommon->initialDownlinkBWP->pdsch_ConfigCommon->choice.setup->pdsch_TimeDomainAllocationList;
rmagueta's avatar
rmagueta committed
1154
    }
rmagueta's avatar
rmagueta committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

    long BWPStart = 0;
    long BWPSize = 0;
    NR_Type0_PDCCH_CSS_config_t *type0_PDCCH_CSS_config = NULL;
    if(*ss->controlResourceSetId!=0) {
      BWPStart = NRRIV2PRBOFFSET(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
      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;
    }
1167

francescomani's avatar
francescomani committed
1168 1169 1170 1171
    if (*ss->controlResourceSetId == 0)
      coreset = nr_mac->sched_ctrlCommon->coreset; // this is coreset 0
    else
      coreset = get_coreset(scc, bwp, ss, NR_SearchSpace__searchSpaceType_PR_common);
1172 1173

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

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

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

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

rmagueta's avatar
rmagueta committed
1195 1196
    uint8_t aggregation_level;
    uint8_t nr_of_candidates;
1197
    find_aggregation_candidates(&aggregation_level, &nr_of_candidates, ss);
rmagueta's avatar
rmagueta committed
1198
    int CCEIndex = allocate_nr_CCEs(nr_mac, bwp, coreset, aggregation_level,0,0,nr_of_candidates);
1199
    if (CCEIndex < 0) {
1200
      LOG_E(NR_MAC, "%s(): cannot find free CCE for RA RNTI %04x!\n", __func__, ra->rnti);
1201 1202 1203
      return;
    }

rmagueta's avatar
rmagueta committed
1204 1205
    // Calculate number of symbols
    int startSymbolIndex, nrOfSymbols;
1206
    const int startSymbolAndLength = pdsch_TimeDomainAllocationList->list.array[time_domain_assignment]->startSymbolAndLength;
rmagueta's avatar
rmagueta committed
1207 1208 1209
    SLIV2SL(startSymbolAndLength, &startSymbolIndex, &nrOfSymbols);
    AssertFatal(startSymbolIndex >= 0, "StartSymbolIndex is negative\n");

1210
    LOG_D(NR_MAC,"Msg2 startSymbolIndex.nrOfSymbols %d.%d\n",startSymbolIndex,nrOfSymbols);
rmagueta's avatar
rmagueta committed
1211

1212
    int mappingtype = pdsch_TimeDomainAllocationList->list.array[time_domain_assignment]->mappingType;
1213

rmagueta's avatar
rmagueta committed
1214 1215
    // 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
1216
    const int bwpid = bwp ? bwp->bwp_Id : 0;
1217 1218 1219 1220 1221 1222 1223 1224 1225
    const int coresetid = coreset->controlResourceSetId;
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_rel15 = nr_mac->pdcch_pdu_idx[CC_id][bwpid][coresetid];
    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;
rmagueta's avatar
rmagueta committed
1226
      nr_configure_pdcch(pdcch_pdu_rel15, ss, coreset, scc, genericParameters, type0_PDCCH_CSS_config);
1227
      nr_mac->pdcch_pdu_idx[CC_id][bwpid][coresetid] = pdcch_pdu_rel15;
1228
    }
rmagueta's avatar
rmagueta committed
1229

1230
    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
1231 1232 1233
    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));
1234
    dl_req->nPDUs+=1;
cig's avatar
cig committed
1235
    nfapi_nr_dl_tti_pdsch_pdu_rel15_t *pdsch_pdu_rel15 = &dl_tti_pdsch_pdu->pdsch_pdu.pdsch_pdu_rel15;
1236

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

rmagueta's avatar
rmagueta committed
1240 1241
    // 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.
1242
    const int pduindex = nr_mac->pdu_index[CC_id]++;
1243

rmagueta's avatar
rmagueta committed
1244
    uint8_t mcsTableIdx = 0;
1245
    if (bwp &&
1246 1247 1248 1249
        bwp->bwp_Dedicated &&
        bwp->bwp_Dedicated->pdsch_Config &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup->mcs_Table) {
rmagueta's avatar
rmagueta committed
1250 1251 1252 1253 1254
      if (*bwp->bwp_Dedicated->pdsch_Config->choice.setup->mcs_Table == 0)
        mcsTableIdx = 1;
      else
        mcsTableIdx = 2;
    }
1255 1256 1257 1258
    else mcsTableIdx = 0;

    int dmrsConfigType=0;
    if (bwp &&
1259 1260 1261 1262 1263 1264
        bwp->bwp_Dedicated &&
        bwp->bwp_Dedicated->pdsch_Config &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup->dmrs_DownlinkForPDSCH_MappingTypeA &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup->dmrs_DownlinkForPDSCH_MappingTypeA->choice.setup &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup->dmrs_DownlinkForPDSCH_MappingTypeA->choice.setup->dmrs_Type)
1265
      dmrsConfigType = 1;
1266

rmagueta's avatar
rmagueta committed
1267 1268
    pdsch_pdu_rel15->pduBitmap = 0;
    pdsch_pdu_rel15->rnti = ra->RA_rnti;
1269
    pdsch_pdu_rel15->pduIndex = pduindex;
1270 1271
    pdsch_pdu_rel15->BWPSize  = BWPSize;
    pdsch_pdu_rel15->BWPStart = BWPStart;
1272
    pdsch_pdu_rel15->SubcarrierSpacing = genericParameters->subcarrierSpacing;
cig's avatar
cig committed
1273 1274
    pdsch_pdu_rel15->CyclicPrefix = 0;
    pdsch_pdu_rel15->NrOfCodewords = 1;
rmagueta's avatar
rmagueta committed
1275
    pdsch_pdu_rel15->targetCodeRate[0] = nr_get_code_rate_dl(mcsIndex,mcsTableIdx);
cig's avatar
cig committed
1276 1277
    pdsch_pdu_rel15->qamModOrder[0] = 2;
    pdsch_pdu_rel15->mcsIndex[0] = mcsIndex;
rmagueta's avatar
rmagueta committed
1278
    pdsch_pdu_rel15->mcsTable[0] = mcsTableIdx;
cig's avatar
cig committed
1279 1280 1281 1282 1283
    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;
1284
    pdsch_pdu_rel15->dmrsConfigType = dmrsConfigType;
cig's avatar
cig committed
1285 1286
    pdsch_pdu_rel15->dlDmrsScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->SCID = 0;
1287
    pdsch_pdu_rel15->numDmrsCdmGrpsNoData = nrOfSymbols <= 2 ? 1 : 2;
cig's avatar
cig committed
1288 1289
    pdsch_pdu_rel15->dmrsPorts = 1;
    pdsch_pdu_rel15->resourceAlloc = 1;
1290 1291
    pdsch_pdu_rel15->rbStart = rbStart;
    pdsch_pdu_rel15->rbSize = rbSize;
rmagueta's avatar
rmagueta committed
1292
    pdsch_pdu_rel15->VRBtoPRBMapping = 0;
rmagueta's avatar
rmagueta committed
1293 1294
    pdsch_pdu_rel15->StartSymbolIndex = startSymbolIndex;
    pdsch_pdu_rel15->NrOfSymbols = nrOfSymbols;
1295
    pdsch_pdu_rel15->dlDmrsSymbPos = fill_dmrs_mask(NULL,
rmagueta's avatar
rmagueta committed
1296 1297
                                                    nr_mac->common_channels->ServingCellConfigCommon->dmrs_TypeA_Position,
                                                    nrOfSymbols,
1298 1299
                                                    startSymbolIndex,
                                                    mappingtype);
cig's avatar
cig committed
1300

rmagueta's avatar
rmagueta committed
1301 1302 1303
    int x_Overhead = 0;
    uint8_t tb_scaling = 0;
    nr_get_tbs_dl(&dl_tti_pdsch_pdu->pdsch_pdu, x_Overhead, pdsch_pdu_rel15->numDmrsCdmGrpsNoData, tb_scaling);
cig's avatar
cig committed
1304

rmagueta's avatar
rmagueta committed
1305
    // Fill PDCCH DL DCI PDU
1306 1307
    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
1308
    dci_pdu->RNTI = ra->RA_rnti;
1309 1310 1311 1312 1313 1314 1315 1316
    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;
1317
    int effective_BWPSize = get_softmodem_params()->sa == 1 ? (pdcch_pdu_rel15->FreqDomainResource[0]==0xFF ? 48 : 24) : pdsch_pdu_rel15->BWPSize;
1318
    dci_payload.frequency_domain_assignment.val = PRBalloc_to_locationandbandwidth0(pdsch_pdu_rel15->rbSize,
rmagueta's avatar
rmagueta committed
1319
                                                                                    pdsch_pdu_rel15->rbStart,
1320
                                                                                    effective_BWPSize);
1321

rmagueta's avatar
rmagueta committed
1322
    LOG_D(NR_MAC,"Msg2 rbSize.rbStart.BWPsize %d.%d.%d\n",pdsch_pdu_rel15->rbSize,
1323
	  pdsch_pdu_rel15->rbStart,
1324
	  effective_BWPSize);
rmagueta's avatar
rmagueta committed
1325

1326 1327 1328
    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
1329
    dci_payload.tb_scaling = tb_scaling;
1330

rmagueta's avatar
rmagueta committed
1331
    LOG_D(NR_MAC,
1332
          "[RAPROC] DCI type 1 payload: freq_alloc %d (%d,%d,%d), time_alloc %d, vrb to prb %d, mcs %d tb_scaling %d \n",
1333
          dci_payload.frequency_domain_assignment.val,
1334 1335
          pdsch_pdu_rel15->rbStart,
          pdsch_pdu_rel15->rbSize,
1336
          effective_BWPSize,
1337 1338 1339 1340
          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
1341

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

1351
    fill_dci_pdu_rel15(scc,
1352
                       ra->CellGroup,
rmagueta's avatar
rmagueta committed
1353
                       &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci - 1],
1354
                       &dci_payload,
rmagueta's avatar
rmagueta committed
1355 1356
                       NR_DL_DCI_FORMAT_1_0,
                       NR_RNTI_RA,
1357
                       effective_BWPSize,
1358
                       bwpid);
cig's avatar
cig committed
1359 1360

    // DL TX request
1361
    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
1362 1363

    // Program UL processing for Msg3
1364 1365
    NR_BWP_Uplink_t *ubwp = ra->CellGroup ?
      ra->CellGroup->spCellConfig->spCellConfigDedicated->uplinkConfig->uplinkBWP_ToAddModList->list.array[ra->bwp_id-1] :
1366
      NULL;
1367
    nr_get_Msg3alloc(module_idP, CC_id, scc, ubwp, slotP, frameP, ra, nr_mac->tdd_beam_association);
rmagueta's avatar
rmagueta committed
1368 1369
    nr_add_msg3(module_idP, CC_id, frameP, slotP, ra, (uint8_t *) &tx_req->TLVs[0].value.direct[0]);

1370
    if(ra->cfra) {
1371
      LOG_I(NR_MAC, "Frame %d, Subframe %d: Setting RA-Msg3 reception for Frame %d Subframe %d\n", frameP, slotP, ra->Msg3_frame, ra->Msg3_slot);
1372
    }
rmagueta's avatar
rmagueta committed
1373 1374 1375 1376

    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
1377
    tx_req->PDU_length = pdsch_pdu_rel15->TBSize[0];
1378
    tx_req->PDU_index = pduindex;
cig's avatar
cig committed
1379
    tx_req->num_TLV = 1;
1380
    tx_req->TLVs[0].length = tx_req->PDU_length + 2;
cig's avatar
cig committed
1381 1382 1383
    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;
1384 1385 1386 1387

    // Mark the corresponding RBs as used
    for (int rb = 0; rb < rbSize; rb++) {
      vrb_map[rb + rbStart] = 1;
rmagueta's avatar
rmagueta committed
1388
    }
rmagueta's avatar
rmagueta committed
1389 1390

    ra->state = WAIT_Msg3;
rmagueta's avatar
rmagueta committed
1391
    LOG_D(NR_MAC,"[gNB %d][RAPROC] Frame %d, Subframe %d: RA state %d\n", module_idP, frameP, slotP, ra->state);
cig's avatar
cig committed
1392
  }
1393 1394
}

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

  gNB_MAC_INST *nr_mac = RC.nrmac[module_idP];
  NR_COMMON_channels_t *cc = &nr_mac->common_channels[CC_id];

  if (ra->Msg4_frame == frameP && ra->Msg4_slot == slotP ) {

rmagueta's avatar
rmagueta committed
1402 1403
    uint8_t time_domain_assignment = 0;
    uint8_t mcsIndex = 0;
1404

1405 1406 1407
    NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
    NR_SearchSpace_t *ss = ra->ra_ss;

1408 1409 1410
    NR_BWP_Downlink_t *bwp = NULL;
    NR_ControlResourceSet_t *coreset = NULL;
    NR_PDSCH_TimeDomainResourceAllocationList_t *pdsch_TimeDomainAllocationList=NULL;
1411

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
    if (ra->CellGroup &&
        ra->CellGroup->spCellConfig &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList &&
        ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id-1]) {
      bwp = ra->CellGroup->spCellConfig->spCellConfigDedicated->downlinkBWP_ToAddModList->list.array[ra->bwp_id-1];
      pdsch_TimeDomainAllocationList = bwp->bwp_Common->pdsch_ConfigCommon->choice.setup->pdsch_TimeDomainAllocationList;
    }
    else {
      pdsch_TimeDomainAllocationList = scc->downlinkConfigCommon->initialDownlinkBWP->pdsch_ConfigCommon->choice.setup->pdsch_TimeDomainAllocationList;
    }
francescomani's avatar
francescomani committed
1423 1424 1425 1426 1427

    if (*ss->controlResourceSetId == 0)
      coreset = nr_mac->sched_ctrlCommon->coreset; // this is coreset 0
    else
      coreset = get_coreset(scc, bwp, ss, NR_SearchSpace__searchSpaceType_PR_common);
1428

1429
    AssertFatal(coreset!=NULL,"Coreset cannot be null for RA-Msg4\n");
1430 1431 1432 1433

    int UE_id = find_nr_UE_id(module_idP, ra->rnti);
    NR_UE_info_t *UE_info = &nr_mac->UE_info;
    NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
1434

rmagueta's avatar
rmagueta committed
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
    NR_BWP_t *genericParameters = bwp ? & bwp->bwp_Common->genericParameters : &scc->downlinkConfigCommon->initialDownlinkBWP->genericParameters;

    long BWPStart = 0;
    long BWPSize = 0;
    NR_Type0_PDCCH_CSS_config_t *type0_PDCCH_CSS_config = NULL;
    if(*ss->controlResourceSetId!=0) {
      BWPStart = NRRIV2PRBOFFSET(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
      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;
    }
1448

1449
    // HARQ management
1450 1451 1452 1453
    AssertFatal(sched_ctrl->available_dl_harq.head >= 0,
                "UE context not initialized: no HARQ processes found\n");
    int current_harq_pid = sched_ctrl->available_dl_harq.head;
    remove_front_nr_list(&sched_ctrl->available_dl_harq);
1454 1455 1456 1457 1458 1459
    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;

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
    // get CCEindex, needed also for PUCCH and then later for PDCCH
    uint8_t aggregation_level;
    uint8_t nr_of_candidates;
    find_aggregation_candidates(&aggregation_level, &nr_of_candidates, ss);
    int CCEIndex = allocate_nr_CCEs(nr_mac, bwp, coreset, aggregation_level,0,0,nr_of_candidates);
    if (CCEIndex < 0) {
      LOG_E(NR_MAC, "%s(): cannot find free CCE for RA RNTI %04x!\n", __func__, ra->rnti);
      return;
    }

    int n_rb=0;
    for (int i=0;i<6;i++)
      for (int j=0;j<8;j++) {
1473
	      n_rb+=((coreset->frequencyDomainResources.buf[i]>>j)&1);
1474 1475 1476
      }
    n_rb*=6;
    const uint16_t N_cce = n_rb * coreset->duration / NR_NB_REG_PER_CCE;
1477
    const int delta_PRI=0;
1478 1479
    int r_pucch = ((CCEIndex<<1)/N_cce)+(delta_PRI<<1);

rmagueta's avatar
rmagueta committed
1480
    LOG_D(NR_MAC,"[RAPROC] Msg4 r_pucch %d (CCEIndex %d, N_cce %d, nb_of_candidates %d,delta_PRI %d)\n",r_pucch,CCEIndex,N_cce,nr_of_candidates,delta_PRI);
1481
    int alloc = nr_acknack_scheduling(module_idP, UE_id, frameP, slotP, r_pucch, 1);
1482 1483 1484 1485
    AssertFatal(alloc>=0,"Couldn't find a pucch allocation for ack nack (msg4)\n");
    NR_sched_pucch_t *pucch = &sched_ctrl->sched_pucch[alloc];
    harq->feedback_slot = pucch->ul_slot;
    harq->feedback_frame = pucch->frame;
1486

rmagueta's avatar
rmagueta committed
1487
    // Bytes to be transmitted
1488 1489
    uint8_t *buf = (uint8_t *) harq->tb;
    uint16_t mac_pdu_length = nr_write_ce_dlsch_pdu(module_idP, nr_mac->sched_ctrlCommon, buf, 255, ra->cont_res_id);
rmagueta's avatar
rmagueta committed
1490
    LOG_D(NR_MAC,"Encoded contention resolution mac_pdu_length %d\n",mac_pdu_length);
1491 1492 1493 1494
    uint16_t mac_sdu_length = mac_rrc_nr_data_req(module_idP, CC_id, frameP, CCCH, ra->rnti, 1, &buf[mac_pdu_length+2]);
    ((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 = DL_SCH_LCID_CCCH;
rmagueta's avatar
rmagueta committed
1495 1496 1497
    ((NR_MAC_SUBHEADER_SHORT *) &buf[mac_pdu_length])->L = mac_sdu_length;
    mac_pdu_length = mac_pdu_length + mac_sdu_length + sizeof(NR_MAC_SUBHEADER_SHORT);

1498 1499
    LOG_D(NR_MAC,"Encoded RRCSetup Piggyback (%d + %d bytes), mac_pdu_length %d\n", mac_sdu_length, (int)sizeof(NR_MAC_SUBHEADER_SHORT), mac_pdu_length);

rmagueta's avatar
rmagueta committed
1500 1501
    // Calculate number of symbols
    int startSymbolIndex, nrOfSymbols;
1502
    const int startSymbolAndLength = pdsch_TimeDomainAllocationList->list.array[time_domain_assignment]->startSymbolAndLength;
rmagueta's avatar
rmagueta committed
1503 1504
    SLIV2SL(startSymbolAndLength, &startSymbolIndex, &nrOfSymbols);
    AssertFatal(startSymbolIndex >= 0, "StartSymbolIndex is negative\n");
1505

1506
    int mappingtype = pdsch_TimeDomainAllocationList->list.array[time_domain_assignment]->mappingType;
1507

1508
    uint16_t dlDmrsSymbPos = fill_dmrs_mask(NULL,
1509
                                            scc->dmrs_TypeA_Position,
rmagueta's avatar
rmagueta committed
1510
                                            nrOfSymbols,
1511 1512
                                            startSymbolIndex,
                                            mappingtype);
1513

rmagueta's avatar
rmagueta committed
1514
    uint16_t N_DMRS_SLOT = get_num_dmrs(dlDmrsSymbPos);
rmagueta's avatar
rmagueta committed
1515

1516
    long dmrsConfigType = bwp!=NULL ? (bwp->bwp_Dedicated->pdsch_Config->choice.setup->dmrs_DownlinkForPDSCH_MappingTypeA->choice.setup->dmrs_Type == NULL ? 0 : 1) : 0;
1517

rmagueta's avatar
rmagueta committed
1518 1519 1520 1521
    nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData = 2;
    if (nrOfSymbols == 2) {
      nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData = 1;
    }
rmagueta's avatar
rmagueta committed
1522

1523 1524 1525 1526
    AssertFatal(nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData == 1
                || nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData == 2,
                "nr_mac->schedCtrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData %d is not possible",
                nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData);
1527

rmagueta's avatar
rmagueta committed
1528 1529
    uint8_t N_PRB_DMRS = 0;
    if (dmrsConfigType==NFAPI_NR_DMRS_TYPE1) {
1530
      N_PRB_DMRS = nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData * 6;
rmagueta's avatar
rmagueta committed
1531 1532
    }
    else {
1533
      N_PRB_DMRS = nr_mac->sched_ctrlCommon->pdsch_semi_static.numDmrsCdmGrpsNoData * 4;
rmagueta's avatar
rmagueta committed
1534 1535
    }

rmagueta's avatar
rmagueta committed
1536
    uint8_t mcsTableIdx = 0;
1537
    if (bwp &&
1538 1539 1540 1541
        bwp->bwp_Dedicated &&
        bwp->bwp_Dedicated->pdsch_Config &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup &&
        bwp->bwp_Dedicated->pdsch_Config->choice.setup->mcs_Table) {
1542
      if (*bwp->bwp_Dedicated->pdsch_Config->choice.setup->mcs_Table == 0)
rmagueta's avatar
rmagueta committed
1543
        mcsTableIdx = 1;
1544
      else
rmagueta's avatar
rmagueta committed
1545
        mcsTableIdx = 2;
1546
    }
1547
    else mcsTableIdx = 0;
rmagueta's avatar
rmagueta committed
1548

rmagueta's avatar
rmagueta committed
1549 1550 1551 1552
    int rbStart = 0;
    int rbSize = 0;
    uint8_t tb_scaling = 0;
    uint16_t *vrb_map = cc[CC_id].vrb_map;
rmagueta's avatar
rmagueta committed
1553 1554
    do {
      rbSize++;
rmagueta's avatar
rmagueta committed
1555
      LOG_D(NR_MAC,"Calling nr_compute_tbs with N_PRB_DMRS %d, N_DMRS_SLOT %d\n",N_PRB_DMRS,N_DMRS_SLOT);
1556
      harq->tb_size = nr_compute_tbs(nr_get_Qm_dl(mcsIndex, mcsTableIdx),
rmagueta's avatar
rmagueta committed
1557 1558
                           nr_get_code_rate_dl(mcsIndex, mcsTableIdx),
                           rbSize, nrOfSymbols, N_PRB_DMRS * N_DMRS_SLOT, 0, tb_scaling,1) >> 3;
1559
    } while (rbStart + rbSize < BWPSize && !vrb_map[rbStart + rbSize] && harq->tb_size < mac_pdu_length);
rmagueta's avatar
rmagueta committed
1560 1561 1562 1563 1564 1565 1566 1567 1568

    for (int i = 0; (i < rbSize) && (rbStart <= (BWPSize - rbSize)); i++) {
      if (vrb_map[rbStart + i]) {
        rbStart += i;
        i = 0;
      }
    }

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

1573
    // Checking if the DCI allocation is feasible in current subframe
rmagueta's avatar
rmagueta committed
1574
    nfapi_nr_dl_tti_request_body_t *dl_req = &nr_mac->DL_req[CC_id].dl_tti_request_body;
1575 1576 1577 1578 1579 1580 1581 1582
    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;
    }


    // 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
rmagueta's avatar
rmagueta committed
1583
    const int bwpid = bwp ? bwp->bwp_Id : 0;
1584 1585 1586 1587 1588 1589 1590 1591 1592
    const int coresetid = coreset->controlResourceSetId;
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_rel15 = nr_mac->pdcch_pdu_idx[CC_id][bwpid][coresetid];
    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;
rmagueta's avatar
rmagueta committed
1593
      nr_configure_pdcch(pdcch_pdu_rel15, ss, coreset, scc, genericParameters, type0_PDCCH_CSS_config);
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
      nr_mac->pdcch_pdu_idx[CC_id][bwpid][coresetid] = pdcch_pdu_rel15;
    }

    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;

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

    // 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
1609 1610 1611

    pdsch_pdu_rel15->pduBitmap = 0;
    pdsch_pdu_rel15->rnti = ra->rnti;
1612
    pdsch_pdu_rel15->pduIndex = pduindex;
rmagueta's avatar
rmagueta committed
1613 1614
    pdsch_pdu_rel15->BWPSize  = BWPSize;
    pdsch_pdu_rel15->BWPStart = BWPStart;
1615
    pdsch_pdu_rel15->SubcarrierSpacing = genericParameters->subcarrierSpacing;
1616 1617
    pdsch_pdu_rel15->CyclicPrefix = 0;
    pdsch_pdu_rel15->NrOfCodewords = 1;
rmagueta's avatar
rmagueta committed
1618
    pdsch_pdu_rel15->targetCodeRate[0] = nr_get_code_rate_dl(mcsIndex,mcsTableIdx);
1619 1620
    pdsch_pdu_rel15->qamModOrder[0] = 2;
    pdsch_pdu_rel15->mcsIndex[0] = mcsIndex;
rmagueta's avatar
rmagueta committed
1621
    pdsch_pdu_rel15->mcsTable[0] = mcsTableIdx;
1622
    pdsch_pdu_rel15->rvIndex[0] = nr_rv_round_map[harq->round];
cig's avatar
cig committed
1623 1624 1625 1626
    pdsch_pdu_rel15->dataScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->nrOfLayers = 1;
    pdsch_pdu_rel15->transmissionScheme = 0;
    pdsch_pdu_rel15->refPoint = 0;
rmagueta's avatar
rmagueta committed
1627
    pdsch_pdu_rel15->dmrsConfigType = dmrsConfigType;
cig's avatar
cig committed
1628 1629
    pdsch_pdu_rel15->dlDmrsScramblingId = *scc->physCellId;
    pdsch_pdu_rel15->SCID = 0;
1630
    pdsch_pdu_rel15->numDmrsCdmGrpsNoData = nrOfSymbols <= 2 ? 1 : 2;
cig's avatar
cig committed
1631 1632
    pdsch_pdu_rel15->dmrsPorts = 1;
    pdsch_pdu_rel15->resourceAlloc = 1;
1633 1634
    pdsch_pdu_rel15->rbStart = rbStart;
    pdsch_pdu_rel15->rbSize = rbSize;
1635
    pdsch_pdu_rel15->VRBtoPRBMapping = 0;
rmagueta's avatar
rmagueta committed
1636 1637 1638
    pdsch_pdu_rel15->StartSymbolIndex = startSymbolIndex;
    pdsch_pdu_rel15->NrOfSymbols = nrOfSymbols;
    pdsch_pdu_rel15->dlDmrsSymbPos = dlDmrsSymbPos;
cig's avatar
cig committed
1639

rmagueta's avatar
rmagueta committed
1640 1641
    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
1642

1643 1644 1645 1646 1647 1648
    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;

1649 1650 1651
    /* 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++;
1652
    dci_pdu->RNTI = ra->rnti;
1653 1654 1655 1656 1657 1658 1659 1660 1661
    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,
1662
                                                                                    pdsch_pdu_rel15->rbStart,
1663
                                                                                    BWPSize);
rmagueta's avatar
rmagueta committed
1664

1665
    dci_payload.format_indicator = 1;
1666 1667 1668
    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
1669
    dci_payload.tb_scaling = tb_scaling;
1670 1671 1672
    dci_payload.rv = pdsch_pdu_rel15->rvIndex[0];
    dci_payload.harq_pid = current_harq_pid;
    dci_payload.ndi = harq->ndi;
1673
    dci_payload.dai[0].val = (pucch->dai_c-1)&3;
1674
    dci_payload.tpc = sched_ctrl->tpc1; // TPC for PUCCH: table 7.2.1-1 in 38.213
1675
    dci_payload.pucch_resource_indicator = delta_PRI; // This is delta_PRI from 9.2.1 in 38.213
1676
    dci_payload.pdsch_to_harq_feedback_timing_indicator.val = pucch->timing_indicator;
1677

rmagueta's avatar
rmagueta committed
1678
    LOG_D(NR_MAC,
1679
          "[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",
1680
          dci_payload.frequency_domain_assignment.val,
1681 1682
          pdsch_pdu_rel15->rbStart,
          pdsch_pdu_rel15->rbSize,
rmagueta's avatar
rmagueta committed
1683
          pdsch_pdu_rel15->BWPSize,
1684 1685 1686
          dci_payload.time_domain_assignment.val,
          dci_payload.vrb_to_prb_mapping.val,
          dci_payload.mcs,
1687
          dci_payload.tb_scaling,
1688 1689
          dci_payload.pucch_resource_indicator,
          dci_payload.pdsch_to_harq_feedback_timing_indicator.val);
cig's avatar
cig committed
1690

rmagueta's avatar
rmagueta committed
1691
    LOG_D(NR_MAC,
Eurecom's avatar
Eurecom committed
1692
          "[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",
1693
          pdcch_pdu_rel15->dci_pdu[0].RNTI,
rmagueta's avatar
rmagueta committed
1694 1695
          NR_RNTI_TC,
          NR_DL_DCI_FORMAT_1_0,
1696 1697
          (unsigned long long)pdcch_pdu_rel15->FreqDomainResource,
          pdcch_pdu_rel15->StartSymbolIndex,
Eurecom's avatar
Eurecom committed
1698 1699
          pdcch_pdu_rel15->DurationSymbols,
          pdsch_pdu_rel15->BWPSize);
cig's avatar
cig committed
1700

1701
    fill_dci_pdu_rel15(scc,
1702
                       ra->CellGroup,
rmagueta's avatar
rmagueta committed
1703
                       &pdcch_pdu_rel15->dci_pdu[pdcch_pdu_rel15->numDlDci - 1],
1704
                       &dci_payload,
rmagueta's avatar
rmagueta committed
1705 1706 1707
                       NR_DL_DCI_FORMAT_1_0,
                       NR_RNTI_TC,
                       pdsch_pdu_rel15->BWPSize,
1708
                       bwpid);
1709

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    // Add padding header and zero rest out if there is space left
    if (mac_pdu_length < harq->tb_size) {
      NR_MAC_SUBHEADER_FIXED *padding = (NR_MAC_SUBHEADER_FIXED *) &buf[mac_pdu_length];
      padding->R = 0;
      padding->LCID = DL_SCH_LCID_PADDING;
      for(int k = mac_pdu_length+1; k<harq->tb_size; k++) {
        buf[k] = 0;
      }
    }

1720 1721 1722
    T(T_GNB_MAC_DL_PDU_WITH_DATA, T_INT(module_idP), T_INT(CC_id), T_INT(ra->rnti),
      T_INT(frameP), T_INT(slotP), T_INT(current_harq_pid), T_BUFFER(harq->tb, harq->tb_size));

cig's avatar
cig committed
1723
    // DL TX request
1724
    nfapi_nr_pdu_t *tx_req = &nr_mac->TX_req[CC_id].pdu_list[nr_mac->TX_req[CC_id].Number_of_PDUs];
1725 1726
    memcpy(tx_req->TLVs[0].value.direct, harq->tb, sizeof(uint8_t) * harq->tb_size);
    tx_req->PDU_length =  harq->tb_size;
1727
    tx_req->PDU_index = pduindex;
cig's avatar
cig committed
1728
    tx_req->num_TLV = 1;
1729
    tx_req->TLVs[0].length =  harq->tb_size + 2;
cig's avatar
cig committed
1730 1731 1732
    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;
1733

1734
    // Mark the corresponding RBs as used
1735 1736 1737 1738
    for (int rb = 0; rb < pdsch_pdu_rel15->rbSize; rb++) {
      vrb_map[rb + pdsch_pdu_rel15->rbStart] = 1;
    }

rmagueta's avatar
rmagueta committed
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
    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);

    ra->state = WAIT_Msg4_ACK;
rmagueta's avatar
rmagueta committed
1755
    LOG_D(NR_MAC,"[gNB %d][RAPROC] Frame %d, Subframe %d: RA state %d\n", module_idP, frameP, slotP, ra->state);
1756 1757
  }
}
1758

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

1761 1762
  int UE_id = find_nr_UE_id(module_id, ra->rnti);
  const int current_harq_pid = ra->harq_pid;
1763

1764 1765 1766
  NR_UE_info_t *UE_info = &RC.nrmac[module_id]->UE_info;
  NR_UE_harq_t *harq = &UE_info->UE_sched_ctrl[UE_id].harq_processes[current_harq_pid];

1767
  LOG_D(NR_MAC, "ue %d, rnti %d, harq is waiting %d, round %d, frame %d %d, harq id %d\n", UE_id, ra->rnti, harq->is_waiting, harq->round, frame, slot, current_harq_pid);
1768 1769 1770 1771 1772

  if (harq->is_waiting == 0)
  {
    if (harq->round == 0)
    {
1773
      LOG_I(NR_MAC, "(ue %i, rnti 0x%04x) Received Ack of RA-Msg4. CBRA procedure succeeded!\n", UE_id, ra->rnti);
1774
      nr_clear_ra_proc(module_id, CC_id, frame, ra);
1775
      UE_info->active[UE_id] = true;
1776
      UE_info->Msg4_ACKed[UE_id] = true;
1777 1778 1779
    }
    else
    {
1780 1781 1782 1783 1784 1785
//      ra->state = Msg4;
      LOG_I(NR_MAC, "(ue %i, rnti 0x%04x) Received Nak of RA-Msg4. CBRA procedure failed!\n", UE_id, ra->rnti);
      mac_remove_nr_ue(module_id,ra->rnti);
      nr_clear_ra_proc(module_id, CC_id, frame, ra);
      UE_info->active[UE_id] = false;
      UE_info->Msg4_ACKed[UE_id] = false;
1786
    }
cig's avatar
cig committed
1787
  }
1788

1789 1790
}

1791
void nr_clear_ra_proc(module_id_t module_idP, int CC_id, frame_t frameP, NR_RA_t *ra){
1792
  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);
1793
  ra->state = RA_IDLE;
cig's avatar
cig committed
1794 1795 1796
  ra->timing_offset = 0;
  ra->RRC_timer = 20;
  ra->msg3_round = 0;
1797 1798 1799
  if(ra->cfra == false) {
    ra->rnti = 0;
  }
1800 1801
}

1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

/////////////////////////////////////
//    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
1827
// WIP
cig's avatar
cig committed
1828 1829 1830
// todo:
// - handle MAC RAR BI subheader
// - sending only 1 RAR subPDU
1831
// - UL Grant: hardcoded CSI, TPC, time alloc
cig's avatar
cig committed
1832
// - padding
1833 1834
void nr_fill_rar(uint8_t Mod_idP,
                 NR_RA_t * ra,
cig's avatar
cig committed
1835
                 uint8_t * dlsch_buffer,
1836
                 nfapi_nr_pusch_pdu_t  *pusch_pdu){
cig's avatar
cig committed
1837

1838
  LOG_I(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);
1839 1840 1841
  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
1842
  unsigned char csi_req = 0, tpc_command;
1843 1844
  //uint8_t N_UL_Hop;
  uint8_t valid_bits;
1845 1846
  uint32_t ul_grant;
  uint16_t f_alloc, prb_alloc, bwp_size, truncation=0;
1847

Francesco Mani's avatar
Francesco Mani committed
1848 1849
  tpc_command = 3; // this is 0 dB

1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
  /// 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;

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  /// 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
1879

1880
  ra->msg3_TPC = tpc_command;
1881

1882
  bwp_size = pusch_pdu->bwp_size;
1883
  prb_alloc = PRBalloc_to_locationandbandwidth0(ra->msg3_nb_rb, ra->msg3_first_rb, bwp_size);
1884 1885 1886 1887 1888 1889
  if (bwp_size>180) {
    AssertFatal(1==0,"Initial UBWP larger than 180 currently not supported");
  }
  else {
    valid_bits = (uint8_t)ceil(log2(bwp_size*(bwp_size+1)>>1));
  }
1890

1891 1892
  if (pusch_pdu->frequency_hopping){
    AssertFatal(1==0,"PUSCH with frequency hopping currently not supported");
1893
  } else {
1894 1895 1896
    for (int i=0; i<valid_bits; i++)
      truncation |= (1<<i);
    f_alloc = (prb_alloc&truncation);
1897
  }
1898

1899
  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);
1900

1901 1902 1903 1904
  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;
1905

rmagueta's avatar
rmagueta committed
1906
#ifdef DEBUG_RAR
1907 1908 1909 1910 1911
  //LOG_I(NR_MAC, "rarbi->E = 0x%x\n", rarbi->E);
  //LOG_I(NR_MAC, "rarbi->T = 0x%x\n", rarbi->T);
  //LOG_I(NR_MAC, "rarbi->R = 0x%x\n", rarbi->R);
  //LOG_I(NR_MAC, "rarbi->BI = 0x%x\n", rarbi->BI);

rmagueta's avatar
rmagueta committed
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
  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
1928
#endif
rmagueta's avatar
rmagueta committed
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941

  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
1942
  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
1943 1944 1945 1946 1947 1948 1949 1950 1951
        __FUNCTION__,
        Msg3_t_alloc,
        Msg3_f_alloc,
        ta_command,
        mcs,
        freq_hopping,
        tpc_command,
        csi_req,
        t_crnti);
1952
}