gNB_scheduler_ulsch.c 74.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this file
 * except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */

/*! \file gNB_scheduler_ulsch.c
 * \brief gNB procedures for the ULSCH transport channel
 * \author Navid Nikaein and Raymond Knopp, Guido Casati
 * \date 2019
 * \email: guido.casati@iis.fraunhofer.de
 * \version 1.0
 * @ingroup _mac
 */


#include "LAYER2/NR_MAC_gNB/mac_proto.h"
33
#include "executables/softmodem-common.h"
34
#include "common/utils/nr/nr_common.h"
35 36
#include <openair2/UTIL/OPT/opt.h>

37
#include "LAYER2/NR_MAC_COMMON/nr_mac_extern.h"
38

Eurecom's avatar
Eurecom committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52
int get_dci_format(NR_UE_sched_ctrl_t *sched_ctrl) {

    const long f = sched_ctrl->search_space->searchSpaceType->choice.ue_Specific->dci_Formats;
    int dci_format;
    if (sched_ctrl->search_space) {
       dci_format = f ? NR_UL_DCI_FORMAT_0_1 : NR_UL_DCI_FORMAT_0_0;
    }
    else {
       dci_format = NR_UL_DCI_FORMAT_0_0;
    }

    return(dci_format);
}

53 54 55 56 57 58 59 60
void calculate_preferred_ul_tda(module_id_t module_id, const NR_BWP_Uplink_t *ubwp)
{
  gNB_MAC_INST *nrmac = RC.nrmac[module_id];
  const int bwp_id = ubwp->bwp_Id;
  if (nrmac->preferred_ul_tda[bwp_id])
    return;

  /* there is a mixed slot only when in TDD */
rmagueta's avatar
rmagueta committed
61
  NR_ServingCellConfigCommon_t *scc = nrmac->common_channels->ServingCellConfigCommon;
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  const int mu = scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.subcarrierSpacing;
  const NR_TDD_UL_DL_Pattern_t *tdd =
      scc->tdd_UL_DL_ConfigurationCommon ? &scc->tdd_UL_DL_ConfigurationCommon->pattern1 : NULL;
  /* Uplink symbols are at the end of the slot */
  const int symb_ulMixed = tdd ? ((1 << tdd->nrofUplinkSymbols) - 1) << (14 - tdd->nrofUplinkSymbols) : 0;

  const struct NR_PUCCH_Config__resourceToAddModList *resList = ubwp->bwp_Dedicated->pucch_Config->choice.setup->resourceToAddModList;
  // for the moment, just block any symbol that might hold a PUCCH, regardless
  // of the RB. This is a big simplification, as most RBs will NOT have a PUCCH
  // in the respective symbols, but it simplifies scheduling
  uint16_t symb_pucch = 0;
  for (int i = 0; i < resList->list.count; ++i) {
    const NR_PUCCH_Resource_t *resource = resList->list.array[i];
    int nrofSymbols = 0;
    int startingSymbolIndex = 0;
    switch (resource->format.present) {
      case NR_PUCCH_Resource__format_PR_format0:
        nrofSymbols = resource->format.choice.format0->nrofSymbols;
        startingSymbolIndex = resource->format.choice.format0->startingSymbolIndex;
        break;
      case NR_PUCCH_Resource__format_PR_format1:
        nrofSymbols = resource->format.choice.format1->nrofSymbols;
        startingSymbolIndex = resource->format.choice.format1->startingSymbolIndex;
        break;
      case NR_PUCCH_Resource__format_PR_format2:
        nrofSymbols = resource->format.choice.format2->nrofSymbols;
        startingSymbolIndex = resource->format.choice.format2->startingSymbolIndex;
        break;
      case NR_PUCCH_Resource__format_PR_format3:
        nrofSymbols = resource->format.choice.format3->nrofSymbols;
        startingSymbolIndex = resource->format.choice.format3->startingSymbolIndex;
        break;
      case NR_PUCCH_Resource__format_PR_format4:
        nrofSymbols = resource->format.choice.format4->nrofSymbols;
        startingSymbolIndex = resource->format.choice.format4->startingSymbolIndex;
        break;
      default:
        AssertFatal(0, "found NR_PUCCH format index %d\n", resource->format.present);
        break;
    }
    symb_pucch |= ((1 << nrofSymbols) - 1) << startingSymbolIndex;
  }

  /* check that TDA index 1 fits into UL slot and does not overlap with PUCCH */
  const struct NR_PUSCH_TimeDomainResourceAllocationList *tdaList = ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList;
  AssertFatal(tdaList->list.count >= 3, "need to have at least three TDAs for UL slots\n");
  const NR_PUSCH_TimeDomainResourceAllocation_t *tdaP_UL = tdaList->list.array[0];
rmagueta's avatar
rmagueta committed
109
  const int k2 = get_K2(scc, (NR_BWP_Uplink_t*)ubwp,0, mu);
110 111 112 113 114 115 116 117 118 119 120
  int start, len;
  SLIV2SL(tdaP_UL->startSymbolAndLength, &start, &len);
  const uint16_t symb_tda = ((1 << len) - 1) << start;
  // check whether PUCCH and TDA overlap: then, we cannot use it. Note that
  // here we assume that the PUCCH is scheduled in every slot, and on all RBs
  // (which is mostly not true, this is a simplification)
  AssertFatal((symb_pucch & symb_tda) == 0, "TDA index 0 for UL overlaps with PUCCH\n");

  // get largest time domain allocation (TDA) for UL slot and UL in mixed slot
  int tdaMi = -1;
  const NR_PUSCH_TimeDomainResourceAllocation_t *tdaP_Mi = tdaList->list.array[1];
rmagueta's avatar
rmagueta committed
121
  AssertFatal(k2 == get_K2(scc, (NR_BWP_Uplink_t*)ubwp, 1, mu),
122 123
              "scheduler cannot handle different k2 for UL slot (%d) and UL Mixed slot (%ld)\n",
              k2,
rmagueta's avatar
rmagueta committed
124
              get_K2(scc, (NR_BWP_Uplink_t*)ubwp, 1, mu));
125 126 127 128 129 130 131 132 133
  SLIV2SL(tdaP_Mi->startSymbolAndLength, &start, &len);
  const uint16_t symb_tda_mi = ((1 << len) - 1) << start;
  // check whether PUCCH and TDA overlap: then, we cannot use it. Also, check
  // whether TDA is entirely within mixed slot, UL. Note that here we assume
  // that the PUCCH is scheduled in every slot, and on all RBs (which is
  // mostly not true, this is a simplification)
  if ((symb_pucch & symb_tda_mi) == 0 && (symb_ulMixed & symb_tda_mi) == symb_tda_mi) {
    tdaMi = 1;
  } else {
134
    LOG_E(NR_MAC,
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
          "TDA index 1 UL overlaps with PUCCH or is not entirely in mixed slot (symb_pucch %x symb_ulMixed %x symb_tda_mi %x), won't schedule UL mixed slot\n",
          symb_pucch,
          symb_ulMixed,
          symb_tda_mi);
  }

  const uint8_t slots_per_frame[5] = {10, 20, 40, 80, 160};
  const int n = slots_per_frame[*scc->ssbSubcarrierSpacing];
  nrmac->preferred_ul_tda[bwp_id] = malloc(n * sizeof(*nrmac->preferred_ul_tda[bwp_id]));

  const int nr_mix_slots = tdd ? tdd->nrofDownlinkSymbols != 0 || tdd->nrofUplinkSymbols != 0 : 0;
  const int nr_slots_period = tdd ? tdd->nrofDownlinkSlots + tdd->nrofUplinkSlots + nr_mix_slots : n;
  for (int slot = 0; slot < n; ++slot) {
    const int sched_slot = (slot + k2) % n;
    nrmac->preferred_ul_tda[bwp_id][slot] = -1;
    if (!tdd || sched_slot % nr_slots_period >= tdd->nrofDownlinkSlots + nr_mix_slots)
      nrmac->preferred_ul_tda[bwp_id][slot] = 0;
    else if (tdd && nr_mix_slots && sched_slot % nr_slots_period == tdd->nrofDownlinkSlots)
      nrmac->preferred_ul_tda[bwp_id][slot] = tdaMi;
154
    LOG_D(MAC, "DL slot %d UL slot %d preferred_ul_tda %d\n", slot, sched_slot, nrmac->preferred_ul_tda[bwp_id][slot]);
155 156 157
  }

  if (k2 < tdd->nrofUplinkSlots)
158
    LOG_W(NR_MAC,
159 160 161 162 163
          "k2 %d < tdd->nrofUplinkSlots %ld: not all UL slots can be scheduled\n",
          k2,
          tdd->nrofUplinkSlots);
}

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
//  For both UL-SCH except:
//   - UL-SCH: fixed-size MAC CE(known by LCID)
//   - UL-SCH: padding
//   - UL-SCH: MSG3 48-bits
//  |0|1|2|3|4|5|6|7|  bit-wise
//  |R|F|   LCID    |
//  |       L       |
//  |0|1|2|3|4|5|6|7|  bit-wise
//  |R|F|   LCID    |
//  |       L       |
//  |       L       |
//
//  For:
//   - UL-SCH: fixed-size MAC CE(known by LCID)
//   - UL-SCH: padding, for single/multiple 1-oct padding CE(s)
//   - UL-SCH: MSG3 48-bits
//  |0|1|2|3|4|5|6|7|  bit-wise
//  |R|R|   LCID    |
//
//  LCID: The Logical Channel ID field identifies the logical channel instance of the corresponding MAC SDU or the type of the corresponding MAC CE or padding as described in Tables 6.2.1-1 and 6.2.1-2 for the DL-SCH and UL-SCH respectively. There is one LCID field per MAC subheader. The LCID field size is 6 bits;
//  L: The Length field indicates the length of the corresponding MAC SDU or variable-sized MAC CE in bytes. There is one L field per MAC subheader except for subheaders corresponding to fixed-sized MAC CEs and padding. The size of the L field is indicated by the F field;
//  F: length of L is 0:8 or 1:16 bits wide
//  R: Reserved bit, set to zero.

Eurecom's avatar
Eurecom committed
188
int nr_process_mac_pdu(module_id_t module_idP,
189 190 191 192 193
                        int UE_id,
                        uint8_t CC_id,
                        frame_t frameP,
                        sub_frame_t slot,
                        uint8_t *pduP,
194
                        int pdu_len)
195
{
cig's avatar
cig committed
196

197 198 199 200 201
    uint8_t rx_lcid;
    uint8_t done = 0;
    uint16_t mac_ce_len;
    uint16_t mac_subheader_len;
    uint16_t mac_sdu_len;
cig's avatar
cig committed
202

203 204
    NR_UE_info_t *UE_info = &RC.nrmac[module_idP]->UE_info;
    NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
205

206
    if ( pduP[0] != UL_SCH_LCID_PADDING )
207 208 209 210 211 212
      trace_NRpdu(DIRECTION_UPLINK, pduP, pdu_len, UE_id, WS_C_RNTI, UE_info->rnti[UE_id], frameP, 0, 0, 0);

    #ifdef ENABLE_MAC_PAYLOAD_DEBUG
    LOG_I(NR_MAC, "In %s: dumping MAC PDU in %d.%d:\n", __func__, frameP, slot);
    log_dump(NR_MAC, pduP, pdu_len, LOG_DUMP_CHAR, "\n");
    #endif
cig's avatar
cig committed
213 214

    while (!done && pdu_len > 0){
215
        mac_ce_len = 0;
216
        mac_subheader_len = sizeof(NR_MAC_SUBHEADER_FIXED);
217
        mac_sdu_len = 0;
218
        rx_lcid = ((NR_MAC_SUBHEADER_FIXED *)pduP)->LCID;
cig's avatar
cig committed
219

220
        LOG_D(NR_MAC, "In %s: received UL-SCH sub-PDU with LCID 0x%x in %d.%d (remaining PDU length %d)\n", __func__, rx_lcid, frameP, slot, pdu_len);
221

ChiehChun's avatar
ChiehChun committed
222
        unsigned char *ce_ptr;
223
        int n_Lcg = 0;
ChiehChun's avatar
ChiehChun committed
224

cig's avatar
cig committed
225
        switch(rx_lcid){
226 227 228
            //  MAC CE

            /*#ifdef DEBUG_HEADER_PARSING
229
              LOG_D(NR_MAC, "[UE] LCID %d, PDU length %d\n", ((NR_MAC_SUBHEADER_FIXED *)pduP)->LCID, pdu_len);
230
            #endif*/
231 232 233 234 235 236 237
        case UL_SCH_LCID_RECOMMENDED_BITRATE_QUERY:
              // 38.321 Ch6.1.3.20
              mac_ce_len = 2;
              break;
        case UL_SCH_LCID_CONFIGURED_GRANT_CONFIRMATION:
                // 38.321 Ch6.1.3.7
                break;
238 239 240

        case UL_SCH_LCID_S_BSR:
        case UL_SCH_LCID_S_TRUNCATED_BSR:
241 242 243 244
               //38.321 section 6.1.3.1
               //fixed length
               mac_ce_len =1;
               /* Extract short BSR value */
245
               ce_ptr = &pduP[mac_subheader_len];
ChiehChun's avatar
ChiehChun committed
246
               NR_BSR_SHORT *bsr_s = (NR_BSR_SHORT *) ce_ptr;
247 248
               sched_ctrl->estimated_ul_buffer = 0;
               sched_ctrl->estimated_ul_buffer = NR_SHORT_BSR_TABLE[bsr_s->Buffer_size];
249
               LOG_D(NR_MAC,
250 251 252
                     "SHORT BSR at %4d.%2d, LCG ID %d, BS Index %d, BS value < %d, est buf %d\n",
                     frameP,
                     slot,
253 254 255 256
                     bsr_s->LcgID,
                     bsr_s->Buffer_size,
                     NR_SHORT_BSR_TABLE[bsr_s->Buffer_size],
                     sched_ctrl->estimated_ul_buffer);
257
               break;
258 259

        case UL_SCH_LCID_L_BSR:
260
        case UL_SCH_LCID_L_TRUNCATED_BSR:
261 262
        	//38.321 section 6.1.3.1
        	//variable length
263
        	mac_ce_len |= (uint16_t)((NR_MAC_SUBHEADER_SHORT *)pduP)->L;
264
        	mac_subheader_len = 2;
265 266
        	if(((NR_MAC_SUBHEADER_SHORT *)pduP)->F){
        		mac_ce_len |= (uint16_t)(((NR_MAC_SUBHEADER_LONG *)pduP)->L2)<<8;
267 268 269
        		mac_subheader_len = 3;
        	}
        	/* Extract long BSR value */
270
               ce_ptr = &pduP[mac_subheader_len];
ChiehChun's avatar
ChiehChun committed
271
               NR_BSR_LONG *bsr_l = (NR_BSR_LONG *) ce_ptr;
272
               sched_ctrl->estimated_ul_buffer = 0;
273

274 275
               n_Lcg = bsr_l->LcgID7 + bsr_l->LcgID6 + bsr_l->LcgID5 + bsr_l->LcgID4 +
                       bsr_l->LcgID3 + bsr_l->LcgID2 + bsr_l->LcgID1 + bsr_l->LcgID0;
276

277
               LOG_D(NR_MAC, "LONG BSR, LCG ID(7-0) %d/%d/%d/%d/%d/%d/%d/%d\n",
278 279 280 281
                     bsr_l->LcgID7, bsr_l->LcgID6, bsr_l->LcgID5, bsr_l->LcgID4,
                     bsr_l->LcgID3, bsr_l->LcgID2, bsr_l->LcgID1, bsr_l->LcgID0);

               for (int n = 0; n < n_Lcg; n++){
282
                 LOG_D(NR_MAC, "LONG BSR, %d/%d (n/n_Lcg), BS Index %d, BS value < %d",
283 284
                       n, n_Lcg, pduP[mac_subheader_len + 1 + n],
                       NR_LONG_BSR_TABLE[pduP[mac_subheader_len + 1 + n]]);
285
                 sched_ctrl->estimated_ul_buffer +=
286
                       NR_LONG_BSR_TABLE[pduP[mac_subheader_len + 1 + n]];
287
                 LOG_D(NR_MAC,
288 289 290 291 292
                       "LONG BSR at %4d.%2d, %d/%d (n/n_Lcg), BS Index %d, BS value < %d, total %d\n",
                       frameP,
                       slot,
                       n,
                       n_Lcg,
293 294
                       pduP[mac_subheader_len + 1 + n],
                       NR_LONG_BSR_TABLE[pduP[mac_subheader_len + 1 + n]],
295
                       sched_ctrl->estimated_ul_buffer);
296 297
               }

298
               break;
299 300

        case UL_SCH_LCID_C_RNTI:
301 302 303 304 305

          for (int i = 0; i < NR_NB_RA_PROC_MAX; i++) {
            NR_RA_t *ra = &RC.nrmac[module_idP]->common_channels[CC_id].ra[i];
            if (ra->state >= WAIT_Msg3 && ra->rnti == UE_info->rnti[UE_id]) {
              ra->crnti = ((pduP[1]&0xFF)<<8)|(pduP[2]&0xFF);
306 307
              ra->msg3_dcch_dtch = true;
              LOG_I(NR_MAC, "Received UL_SCH_LCID_C_RNTI with C-RNTI 0x%04x\n", ra->crnti);
308 309 310 311
              break;
            }
          }

312 313 314 315 316 317 318 319 320 321 322
        	//38.321 section 6.1.3.2
        	//fixed length
        	mac_ce_len = 2;
        	/* Extract CRNTI value */
        	break;

        case UL_SCH_LCID_SINGLE_ENTRY_PHR:
        	//38.321 section 6.1.3.8
        	//fixed length
        	mac_ce_len = 2;
        	/* Extract SINGLE ENTRY PHR elements for PHR calculation */
323
        	ce_ptr = &pduP[mac_subheader_len];
324 325 326 327 328 329 330 331 332 333 334
        	NR_SINGLE_ENTRY_PHR_MAC_CE *phr = (NR_SINGLE_ENTRY_PHR_MAC_CE *) ce_ptr;
        	/* Save the phr info */
        	const int PH = phr->PH;
        	const int PCMAX = phr->PCMAX;
        	/* 38.133 Table10.1.17.1-1 */
        	if (PH < 55)
        	  sched_ctrl->ph = PH - 32;
        	else
        	  sched_ctrl->ph = PH - 32 + (PH - 54);
        	/* 38.133 Table10.1.18.1-1 */
        	sched_ctrl->pcmax = PCMAX - 29;
335
        	LOG_D(NR_MAC, "SINGLE ENTRY PHR R1 %d PH %d (%d dB) R2 %d PCMAX %d (%d dBm)\n",
336
                      phr->R1, PH, sched_ctrl->ph, phr->R2, PCMAX, sched_ctrl->pcmax);
337 338 339 340 341
        	break;

        case UL_SCH_LCID_MULTI_ENTRY_PHR_1_OCT:
        	//38.321 section 6.1.3.9
        	//  varialbe length
342
        	mac_ce_len |= (uint16_t)((NR_MAC_SUBHEADER_SHORT *)pduP)->L;
343
        	mac_subheader_len = 2;
344 345
        	if(((NR_MAC_SUBHEADER_SHORT *)pduP)->F){
        		mac_ce_len |= (uint16_t)(((NR_MAC_SUBHEADER_LONG *)pduP)->L2)<<8;
346 347 348 349 350 351 352 353
        		mac_subheader_len = 3;
        	}
        	/* Extract MULTI ENTRY PHR elements from single octet bitmap for PHR calculation */
        	break;

        case UL_SCH_LCID_MULTI_ENTRY_PHR_4_OCT:
        	//38.321 section 6.1.3.9
        	//  varialbe length
354
        	mac_ce_len |= (uint16_t)((NR_MAC_SUBHEADER_SHORT *)pduP)->L;
355
        	mac_subheader_len = 2;
356 357
        	if(((NR_MAC_SUBHEADER_SHORT *)pduP)->F){
        		mac_ce_len |= (uint16_t)(((NR_MAC_SUBHEADER_LONG *)pduP)->L2)<<8;
358 359 360 361 362 363 364 365 366 367
        		mac_subheader_len = 3;
        	}
        	/* Extract MULTI ENTRY PHR elements from four octets bitmap for PHR calculation */
        	break;

        case UL_SCH_LCID_PADDING:
        	done = 1;
        	//  end of MAC PDU, can ignore the rest.
        	break;

368
        case UL_SCH_LCID_SRB1:
369
        case UL_SCH_LCID_SRB2:
370 371
          if(((NR_MAC_SUBHEADER_SHORT *)pduP)->F){
            //mac_sdu_len |= (uint16_t)(((NR_MAC_SUBHEADER_LONG *)pduP)->L2)<<8;
372
            mac_subheader_len = 3;
373 374
            mac_sdu_len = ((uint16_t)(((NR_MAC_SUBHEADER_LONG *) pduP)->L1 & 0x7f) << 8)
                | ((uint16_t)((NR_MAC_SUBHEADER_LONG *) pduP)->L2 & 0xff);
375
          } else {
376
            mac_sdu_len = (uint16_t)((NR_MAC_SUBHEADER_SHORT *)pduP)->L;
377 378
            mac_subheader_len = 2;
          }
379 380 381 382 383 384

          rnti_t crnti = UE_info->rnti[UE_id];
          int UE_idx = UE_id;
          for (int i = 0; i < NR_NB_RA_PROC_MAX; i++) {
            NR_RA_t *ra = &RC.nrmac[module_idP]->common_channels[CC_id].ra[i];
            if (ra->state >= WAIT_Msg3 && ra->rnti == UE_info->rnti[UE_id]) {
rmagueta's avatar
rmagueta committed
385
              uint8_t *next_subpduP = pduP + mac_subheader_len + mac_sdu_len;
386 387 388 389 390 391 392 393 394 395
              if ((pduP[mac_subheader_len+mac_sdu_len] & 0x3F) == UL_SCH_LCID_C_RNTI) {
                crnti = ((next_subpduP[1]&0xFF)<<8)|(next_subpduP[2]&0xFF);
                UE_idx = find_nr_UE_id(module_idP, crnti);
                break;
              }
            }
          }

          if (UE_info->CellGroup[UE_idx]) {
            LOG_D(NR_MAC, "[UE %d] Frame %d : ULSCH -> UL-DCCH %d (gNB %d, %d bytes), rnti: 0x%04x \n", module_idP, frameP, rx_lcid, module_idP, mac_sdu_len, crnti);
Eurecom's avatar
Eurecom committed
396
            mac_rlc_data_ind(module_idP,
397
                             crnti,
Eurecom's avatar
Eurecom committed
398 399 400 401 402
                             module_idP,
                             frameP,
                             ENB_FLAG_YES,
                             MBMS_FLAG_NO,
                             rx_lcid,
403
                             (char *) (pduP + mac_subheader_len),
Eurecom's avatar
Eurecom committed
404 405 406 407
                             mac_sdu_len,
                             1,
                             NULL);
          } else {
408
            AssertFatal(1==0,"[UE %d] Frame/Slot %d.%d : Received LCID %d which is not configured, dropping packet\n",UE_id,frameP,slot,rx_lcid);
Eurecom's avatar
Eurecom committed
409
          }
410
          break;
411 412 413
        case UL_SCH_LCID_SRB3:
              // todo
              break;
414

415
        case UL_SCH_LCID_CCCH:
416
        case UL_SCH_LCID_CCCH1:
417
          // fixed length
418
          mac_subheader_len = 1;
419 420 421 422 423

          if ( rx_lcid == UL_SCH_LCID_CCCH1 ) {
            // RRCResumeRequest1 message includes the full I-RNTI and has a size of 8 bytes
            mac_sdu_len = 8;

rmagueta's avatar
rmagueta committed
424
            // Check if it is a valid CCCH1 message, we get all 00's messages very often
425 426
            int i = 0;
            for(i=0; i<(mac_subheader_len+mac_sdu_len); i++) {
427
              if(pduP[i] != 0) {
428 429 430 431
                break;
              }
            }
            if (i == (mac_subheader_len+mac_sdu_len)) {
rmagueta's avatar
rmagueta committed
432
              LOG_D(NR_MAC, "%s() Invalid CCCH1 message!, pdu_len: %d\n", __func__, pdu_len);
433 434
              done = 1;
              break;
435 436 437 438 439 440
            }
          } else {
            // fixed length of 6 bytes
            mac_sdu_len = 6;
          }

441 442 443 444 445
          nr_mac_rrc_data_ind(module_idP,
                              CC_id,
                              frameP,
                              0,
                              0,
446
                              UE_info->rnti[UE_id],
447
                              CCCH,
448
                              pduP + mac_subheader_len,
449
                              mac_sdu_len,
450 451
                              0);
          break;
452

453
        case UL_SCH_LCID_DTCH:
454
          //  check if LCID is valid at current time.
455 456
          if (((NR_MAC_SUBHEADER_SHORT *)pduP)->F) {
            // mac_sdu_len |= (uint16_t)(((NR_MAC_SUBHEADER_LONG *)pduP)->L2)<<8;
457
            mac_subheader_len = 3;
458 459
            mac_sdu_len = ((uint16_t)(((NR_MAC_SUBHEADER_LONG *)pduP)->L1 & 0x7f) << 8)
                          | ((uint16_t)((NR_MAC_SUBHEADER_LONG *)pduP)->L2 & 0xff);
460 461

          } else {
462
            mac_sdu_len = (uint16_t)((NR_MAC_SUBHEADER_SHORT *)pduP)->L;
463 464 465
            mac_subheader_len = 2;
          }

466 467
          LOG_D(NR_MAC, "In %s: [UE %d] %d.%d : ULSCH -> UL-%s %d (gNB %d, %d bytes)\n",
                __func__,
468 469
                module_idP,
                frameP,
470
                slot,
471
                rx_lcid<4?"DCCH":"DTCH",
472 473 474 475
                rx_lcid,
                module_idP,
                mac_sdu_len);
          UE_info->mac_stats[UE_id].lc_bytes_rx[rx_lcid] += mac_sdu_len;
476

477 478 479 480 481 482 483
          mac_rlc_data_ind(module_idP,
                           UE_info->rnti[UE_id],
                           module_idP,
                           frameP,
                           ENB_FLAG_YES,
                           MBMS_FLAG_NO,
                           rx_lcid,
484
                           (char *)(pduP + mac_subheader_len),
485 486 487 488 489 490 491 492 493 494
                           mac_sdu_len,
                           1,
                           NULL);

          /* Updated estimated buffer when receiving data */
          if (sched_ctrl->estimated_ul_buffer >= mac_sdu_len)
            sched_ctrl->estimated_ul_buffer -= mac_sdu_len;
          else
            sched_ctrl->estimated_ul_buffer = 0;
          break;
495 496

        default:
497
          LOG_E(NR_MAC, "Received unknown MAC header (LCID = 0x%02x)\n", rx_lcid);
Eurecom's avatar
Eurecom committed
498
          return -1;
499
          break;
cig's avatar
cig committed
500
        }
501 502 503 504 505 506 507 508 509 510 511 512 513 514

        #ifdef ENABLE_MAC_PAYLOAD_DEBUG
        if (rx_lcid < 45 || rx_lcid == 52 || rx_lcid == 63) {
          LOG_I(NR_MAC, "In %s: dumping UL MAC SDU sub-header with length %d (LCID = 0x%02x):\n", __func__, mac_subheader_len, rx_lcid);
          log_dump(NR_MAC, pduP, mac_subheader_len, LOG_DUMP_CHAR, "\n");
          LOG_I(NR_MAC, "In %s: dumping UL MAC SDU with length %d (LCID = 0x%02x):\n", __func__, mac_sdu_len, rx_lcid);
          log_dump(NR_MAC, pduP + mac_subheader_len, mac_sdu_len, LOG_DUMP_CHAR, "\n");
        } else {
          LOG_I(NR_MAC, "In %s: dumping UL MAC CE with length %d (LCID = 0x%02x):\n", __func__, mac_ce_len, rx_lcid);
          log_dump(NR_MAC, pduP + mac_subheader_len + mac_sdu_len, mac_ce_len, LOG_DUMP_CHAR, "\n");
        }
        #endif

        pduP += ( mac_subheader_len + mac_ce_len + mac_sdu_len );
cig's avatar
cig committed
515 516
        pdu_len -= ( mac_subheader_len + mac_ce_len + mac_sdu_len );

517
        if (pdu_len < 0) {
518
          LOG_E(NR_MAC, "In %s: residual UL MAC PDU in %d.%d with length < 0!, pdu_len %d \n", __func__, frameP, slot, pdu_len);
519
          LOG_E(NR_MAC, "MAC PDU ");
520
          for (int i = 0; i < 20; i++) // Only printf 1st - 20nd bytes
521
            printf("%02x ", pduP[i]);
522
          printf("\n");
Eurecom's avatar
Eurecom committed
523
          return 0;
524
        }
525
    }
Eurecom's avatar
Eurecom committed
526
  return 0;
527
}
528

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
void abort_nr_ul_harq(module_id_t mod_id, int UE_id, int8_t harq_pid)
{
  NR_UE_info_t *UE_info = &RC.nrmac[mod_id]->UE_info;
  NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
  NR_UE_ul_harq_t *harq = &sched_ctrl->ul_harq_processes[harq_pid];

  harq->ndi ^= 1;
  harq->round = 0;
  UE_info->mac_stats[UE_id].ulsch_errors++;
  add_tail_nr_list(&sched_ctrl->available_ul_harq, harq_pid);

  /* the transmission failed: the UE won't send the data we expected initially,
   * so retrieve to correctly schedule after next BSR */
  sched_ctrl->sched_ul_bytes -= harq->sched_pusch.tb_size;
  if (sched_ctrl->sched_ul_bytes < 0)
    sched_ctrl->sched_ul_bytes = 0;
}

547 548
void handle_nr_ul_harq(const int CC_idP,
                       module_id_t mod_id,
549 550 551 552
                       frame_t frame,
                       sub_frame_t slot,
                       const nfapi_nr_crc_t *crc_pdu)
{
553
  gNB_MAC_INST *gNB_mac = RC.nrmac[mod_id];
554 555
  int UE_id = find_nr_UE_id(mod_id, crc_pdu->rnti);
  if (UE_id < 0) {
556 557 558 559 560 561
    for (int i = 0; i < NR_NB_RA_PROC_MAX; ++i) {
      NR_RA_t *ra = &gNB_mac->common_channels[CC_idP].ra[i];
      if (ra->state >= WAIT_Msg3 &&
          ra->rnti == crc_pdu->rnti)
        return;
    }
562
    LOG_E(NR_MAC, "%s(): unknown RNTI 0x%04x in PUSCH\n", __func__, crc_pdu->rnti);
563 564 565 566
    return;
  }
  NR_UE_info_t *UE_info = &RC.nrmac[mod_id]->UE_info;
  NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
567 568
  int8_t harq_pid = sched_ctrl->feedback_ul_harq.head;
  while (crc_pdu->harq_id != harq_pid || harq_pid < 0) {
569
    LOG_W(NR_MAC,
570
          "Unexpected ULSCH HARQ PID %d (have %d) for RNTI 0x%04x (ignore this warning for RA)\n",
571 572
          crc_pdu->harq_id,
          harq_pid,
573
          crc_pdu->rnti);
574 575 576 577
    if (harq_pid < 0)
      return;

    remove_front_nr_list(&sched_ctrl->feedback_ul_harq);
578
    sched_ctrl->ul_harq_processes[harq_pid].is_waiting = false;
579 580
    if(sched_ctrl->ul_harq_processes[harq_pid].round >= MAX_HARQ_ROUNDS - 1) {
      abort_nr_ul_harq(mod_id, UE_id, harq_pid);
581 582 583 584
    } else {
      sched_ctrl->ul_harq_processes[harq_pid].round++;
      add_tail_nr_list(&sched_ctrl->retrans_ul_harq, harq_pid);
    }
585
    harq_pid = sched_ctrl->feedback_ul_harq.head;
586 587 588 589 590 591 592 593 594
  }
  remove_front_nr_list(&sched_ctrl->feedback_ul_harq);
  NR_UE_ul_harq_t *harq = &sched_ctrl->ul_harq_processes[harq_pid];
  DevAssert(harq->is_waiting);
  harq->feedback_slot = -1;
  harq->is_waiting = false;
  if (!crc_pdu->tb_crc_status) {
    harq->ndi ^= 1;
    harq->round = 0;
595
    LOG_D(NR_MAC,
596 597 598 599
          "Ulharq id %d crc passed for RNTI %04x\n",
          harq_pid,
          crc_pdu->rnti);
    add_tail_nr_list(&sched_ctrl->available_ul_harq, harq_pid);
600
  } else if (harq->round >= MAX_HARQ_ROUNDS - 1) {
601
    abort_nr_ul_harq(mod_id, UE_id, harq_pid);
602
    LOG_D(NR_MAC,
603 604 605 606 607
          "RNTI %04x: Ulharq id %d crc failed in all rounds\n",
          crc_pdu->rnti,
          harq_pid);
  } else {
    harq->round++;
608
    LOG_D(NR_MAC,
609 610 611 612 613
          "Ulharq id %d crc failed for RNTI %04x\n",
          harq_pid,
          crc_pdu->rnti);
    add_tail_nr_list(&sched_ctrl->retrans_ul_harq, harq_pid);
  }
614
}
615

616 617 618
/*
* When data are received on PHY and transmitted to MAC
*/
619 620 621
void nr_rx_sdu(const module_id_t gnb_mod_idP,
               const int CC_idP,
               const frame_t frameP,
622
               const sub_frame_t slotP,
623 624 625 626
               const rnti_t rntiP,
               uint8_t *sduP,
               const uint16_t sdu_lenP,
               const uint16_t timing_advance,
627 628
               const uint8_t ul_cqi,
               const uint16_t rssi){
629

Robert Schmidt's avatar
Robert Schmidt committed
630 631 632 633 634 635
  gNB_MAC_INST *gNB_mac = RC.nrmac[gnb_mod_idP];
  NR_UE_info_t *UE_info = &gNB_mac->UE_info;

  const int current_rnti = rntiP;
  const int UE_id = find_nr_UE_id(gnb_mod_idP, current_rnti);
  const int target_snrx10 = gNB_mac->pusch_target_snrx10;
636
  const int pusch_failure_thres = gNB_mac->pusch_failure_thres;
637

638
  if (UE_id != -1) {
Robert Schmidt's avatar
Robert Schmidt committed
639 640 641 642 643 644 645
    NR_UE_sched_ctrl_t *UE_scheduling_control = &UE_info->UE_sched_ctrl[UE_id];
    const int8_t harq_pid = UE_scheduling_control->feedback_ul_harq.head;

    if (sduP)
      T(T_GNB_MAC_UL_PDU_WITH_DATA, T_INT(gnb_mod_idP), T_INT(CC_idP),
        T_INT(rntiP), T_INT(frameP), T_INT(slotP), T_INT(harq_pid),
        T_BUFFER(sduP, sdu_lenP));
646

647
    UE_info->mac_stats[UE_id].ulsch_total_bytes_rx += sdu_lenP;
rmagueta's avatar
rmagueta committed
648
    LOG_D(NR_MAC, "[gNB %d][PUSCH %d] CC_id %d %d.%d Received ULSCH sdu from PHY (rnti %x, UE_id %d) ul_cqi %d TA %d sduP %p, rssi %d\n",
649 650 651 652
          gnb_mod_idP,
          harq_pid,
          CC_idP,
          frameP,
653
          slotP,
654 655
          current_rnti,
          UE_id,
656
          ul_cqi,
657
          timing_advance,
658 659
          sduP,
          rssi);
660

661
    // if not missed detection (10dB threshold for now)
662
    if (rssi>0) {
663
      UE_scheduling_control->tpc0 = nr_get_tpc(target_snrx10,ul_cqi,30);
664 665
      if (timing_advance != 0xffff)
        UE_scheduling_control->ta_update = timing_advance;
666 667
      UE_scheduling_control->raw_rssi = rssi;
      UE_scheduling_control->pusch_snrx10 = ul_cqi * 5 - 640;
rmagueta's avatar
rmagueta committed
668
      LOG_D(NR_MAC, "[UE %d] PUSCH TPC %d and TA %d\n",UE_id,UE_scheduling_control->tpc0,UE_scheduling_control->ta_update);
669 670
    }
    else{
rmagueta's avatar
rmagueta committed
671
      LOG_D(NR_MAC,"[UE %d] Detected DTX : increasing UE TX power\n",UE_id);
672
      UE_scheduling_control->tpc0 = 3;
673 674
    }

675
#if defined(ENABLE_MAC_PAYLOAD_DEBUG)
Laurent's avatar
Laurent committed
676

677
    LOG_I(NR_MAC, "Printing received UL MAC payload at gNB side: %d \n");
678
    for (int i = 0; i < sdu_lenP ; i++) {
679 680 681
	  //harq_process_ul_ue->a[i] = (unsigned char) rand();
	  //printf("a[%d]=0x%02x\n",i,harq_process_ul_ue->a[i]);
	  printf("%02x ",(unsigned char)sduP[i]);
682 683
    }
    printf("\n");
Laurent's avatar
Laurent committed
684

685 686 687
#endif

    if (sduP != NULL){
rmagueta's avatar
rmagueta committed
688
      LOG_D(NR_MAC, "Received PDU at MAC gNB \n");
689

690
      UE_info->UE_sched_ctrl[UE_id].pusch_consecutive_dtx_cnt = 0;
691 692
      const uint32_t tb_size = UE_scheduling_control->ul_harq_processes[harq_pid].sched_pusch.tb_size;
      UE_scheduling_control->sched_ul_bytes -= tb_size;
693 694 695
      if (UE_scheduling_control->sched_ul_bytes < 0)
        UE_scheduling_control->sched_ul_bytes = 0;

696
      nr_process_mac_pdu(gnb_mod_idP, UE_id, CC_idP, frameP, slotP, sduP, sdu_lenP);
697 698
    }
    else {
699 700 701
      NR_UE_ul_harq_t *cur_harq = &UE_scheduling_control->ul_harq_processes[harq_pid];
      /* reduce sched_ul_bytes when cur_harq->round == 3 */
      if (cur_harq->round == 3){
702 703
        const uint32_t tb_size = UE_scheduling_control->ul_harq_processes[harq_pid].sched_pusch.tb_size;
        UE_scheduling_control->sched_ul_bytes -= tb_size;
704 705 706
        if (UE_scheduling_control->sched_ul_bytes < 0)
          UE_scheduling_control->sched_ul_bytes = 0;
      }
707 708 709 710
      if (ul_cqi <= 128) {
        UE_info->UE_sched_ctrl[UE_id].pusch_consecutive_dtx_cnt++;
        UE_info->mac_stats[UE_id].ulsch_DTX++;
      }
711
      if (UE_info->UE_sched_ctrl[UE_id].pusch_consecutive_dtx_cnt >= pusch_failure_thres) {
luis_pereira87's avatar
luis_pereira87 committed
712
         LOG_D(NR_MAC,"Detected UL Failure on PUSCH, stopping scheduling\n");
713
         UE_info->UE_sched_ctrl[UE_id].ul_failure = 1;
rmagueta's avatar
rmagueta committed
714
         nr_mac_gNB_rrc_ul_failure(gnb_mod_idP,CC_idP,frameP,slotP,rntiP);
715
      }
716
    }
717 718 719 720 721 722 723 724 725 726 727 728 729
  } else if(sduP) {

    bool no_sig = true;
    for (int k = 0; k < sdu_lenP; k++) {
      if(sduP[k]!=0) {
        no_sig = false;
        break;
      }
    }

    if(no_sig) {
      LOG_W(NR_MAC, "No signal\n");
    }
730

Robert Schmidt's avatar
Robert Schmidt committed
731 732 733 734
    T(T_GNB_MAC_UL_PDU_WITH_DATA, T_INT(gnb_mod_idP), T_INT(CC_idP),
      T_INT(rntiP), T_INT(frameP), T_INT(slotP), T_INT(-1) /* harq_pid */,
      T_BUFFER(sduP, sdu_lenP));

735 736 737 738 739 740 741 742
    /* we don't know this UE (yet). Check whether there is a ongoing RA (Msg 3)
     * and check the corresponding UE's RNTI match, in which case we activate
     * it. */
    for (int i = 0; i < NR_NB_RA_PROC_MAX; ++i) {
      NR_RA_t *ra = &gNB_mac->common_channels[CC_idP].ra[i];
      if (ra->state != WAIT_Msg3)
        continue;

743
      if(no_sig) {
744
        LOG_W(NR_MAC, "Random Access %i failed at state %i (no signal)\n", i, ra->state);
745
        nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
746
        nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
747 748 749 750 751
      } else {

        // random access pusch with TC-RNTI
        if (ra->rnti != current_rnti) {
          LOG_W(NR_MAC,
rmagueta's avatar
rmagueta committed
752
                "expected TC_RNTI %04x to match current RNTI %04x\n",
753 754
                ra->rnti,
                current_rnti);
rmagueta's avatar
rmagueta committed
755 756

          if( (frameP==ra->Msg3_frame) && (slotP==ra->Msg3_slot) ) {
757
            LOG_W(NR_MAC, "Random Access %i failed at state %i (TC_RNTI %04x RNTI %04x)\n", i, ra->state,ra->rnti,current_rnti);
rmagueta's avatar
rmagueta committed
758 759 760 761
            nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
            nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
          }

762 763
          continue;
        }
rmagueta's avatar
rmagueta committed
764

765 766 767
        int UE_id=-1;

        UE_id = add_new_nr_ue(gnb_mod_idP, ra->rnti, ra->CellGroup);
768 769 770 771 772 773 774
        if (UE_id<0) {
          LOG_W(NR_MAC, "Random Access %i discarded at state %i (TC_RNTI %04x RNTI %04x): max number of users achieved!\n", i, ra->state,ra->rnti,current_rnti);
          nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
          nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
          return;
        }

775
        UE_info->UE_beam_index[UE_id] = ra->beam_id;
rmagueta's avatar
rmagueta committed
776 777 778 779

        // re-initialize ta update variables after RA procedure completion
        UE_info->UE_sched_ctrl[UE_id].ta_frame = frameP;

rmagueta's avatar
rmagueta committed
780
        LOG_D(NR_MAC,
781
              "reset RA state information for RA-RNTI 0x%04x/index %d\n",
782
              ra->rnti,
783
              i);
784

785
        LOG_I(NR_MAC,
786 787
              "[gNB %d][RAPROC] PUSCH with TC_RNTI 0x%04x received correctly, "
              "adding UE MAC Context UE_id %d/RNTI 0x%04x\n",
788 789 790 791
              gnb_mod_idP,
              current_rnti,
              UE_id,
              ra->rnti);
792

793 794 795 796 797 798 799
      NR_UE_sched_ctrl_t *UE_scheduling_control = &UE_info->UE_sched_ctrl[UE_id];

      UE_scheduling_control->tpc0 = nr_get_tpc(target_snrx10,ul_cqi,30);
      if (timing_advance != 0xffff)
        UE_scheduling_control->ta_update = timing_advance;
      UE_scheduling_control->raw_rssi = rssi;
      UE_scheduling_control->pusch_snrx10 = ul_cqi * 5 - 640;
rmagueta's avatar
rmagueta committed
800
      LOG_D(NR_MAC, "[UE %d] PUSCH TPC %d and TA %d\n",UE_id,UE_scheduling_control->tpc0,UE_scheduling_control->ta_update);
801
        if(ra->cfra) {
802

803
          LOG_I(NR_MAC, "(ue %i, rnti 0x%04x) CFRA procedure succeeded!\n", UE_id, ra->rnti);
804
          nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
805 806 807 808
          nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
          UE_info->active[UE_id] = true;

        } else {
809

rmagueta's avatar
rmagueta committed
810 811
          LOG_I(NR_MAC,"[RAPROC] RA-Msg3 received (sdu_lenP %d)\n",sdu_lenP);
          LOG_D(NR_MAC,"[RAPROC] Received Msg3:\n");
812
          for (int k = 0; k < sdu_lenP; k++) {
rmagueta's avatar
rmagueta committed
813
            LOG_D(NR_MAC,"(%i): 0x%x\n",k,sduP[k]);
814
          }
815

816 817 818 819
          // UE Contention Resolution Identity
          // Store the first 48 bits belonging to the uplink CCCH SDU within Msg3 to fill in Msg4
          // First byte corresponds to R/LCID MAC sub-header
          memcpy(ra->cont_res_id, &sduP[1], sizeof(uint8_t) * 6);
820

Eurecom's avatar
Eurecom committed
821
          if (nr_process_mac_pdu(gnb_mod_idP, UE_id, CC_idP, frameP, slotP, sduP, sdu_lenP) == 0) {
822 823 824
            ra->state = Msg4;
            ra->Msg4_frame = (frameP + 2) % 1024;
            ra->Msg4_slot = 1;
825 826 827 828 829 830 831 832 833 834 835 836 837 838
            
            if (ra->msg3_dcch_dtch) {
              // Check if the C-RNTI still exists in the network
              int UE_id_C = find_nr_UE_id(gnb_mod_idP, ra->crnti);
              if (UE_id_C < 0) {
                mac_remove_nr_ue(gnb_mod_idP, ra->rnti);
                nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
                return;
              } else {
                UE_info->UE_sched_ctrl[UE_id_C].pusch_consecutive_dtx_cnt = 0;
                UE_info->UE_sched_ctrl[UE_id_C].ul_failure = 0;
                nr_mac_gNB_rrc_ul_failure_reset(gnb_mod_idP, frameP, slotP, ra->crnti);
              }
            }
839 840
            LOG_I(NR_MAC, "Scheduling RA-Msg4 for TC_RNTI 0x%04x (state %d, frame %d, slot %d)\n",
                  (ra->msg3_dcch_dtch?ra->crnti:ra->rnti), ra->state, ra->Msg4_frame, ra->Msg4_slot);
Eurecom's avatar
Eurecom committed
841 842 843 844 845
          }
          else {
             nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
             nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
          }
846
        }
847
        return;
848
      }
849 850 851 852 853 854
    }
  } else {
    for (int i = 0; i < NR_NB_RA_PROC_MAX; ++i) {
      NR_RA_t *ra = &gNB_mac->common_channels[CC_idP].ra[i];
      if (ra->state != WAIT_Msg3)
        continue;
855

856 857 858
      if( (frameP!=ra->Msg3_frame) || (slotP!=ra->Msg3_slot))
        continue;

859 860
      // for CFRA (NSA) do not schedule retransmission of msg3
      if (ra->cfra) {
861 862 863 864 865 866
        LOG_W(NR_MAC, "Random Access %i failed at state %i (NSA msg3 reception failed)\n", i, ra->state);
        nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
        nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
        return;
      }

867 868 869 870 871 872 873 874 875
      if (ra->msg3_round >= MAX_HARQ_ROUNDS - 1) {
        LOG_W(NR_MAC, "Random Access %i failed at state %i (Reached msg3 max harq rounds)\n", i, ra->state);
        nr_mac_remove_ra_rnti(gnb_mod_idP, ra->rnti);
        nr_clear_ra_proc(gnb_mod_idP, CC_idP, frameP, ra);
        return;
      }

      LOG_W(NR_MAC, "Random Access %i Msg3 CRC did not pass)\n", i);
      ra->msg3_round++;
876
      ra->state = Msg3_retransmission;
877
    }
878
  }
879 880
}

881 882 883 884 885
long get_K2(NR_ServingCellConfigCommon_t *scc,NR_BWP_Uplink_t *ubwp, int time_domain_assignment, int mu) {
  DevAssert(scc);
  const NR_PUSCH_TimeDomainResourceAllocation_t *tda_list = ubwp ?
    ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[time_domain_assignment]:
    scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList->list.array[time_domain_assignment];
886 887 888 889 890 891 892 893 894 895
  if (tda_list->k2)
    return *tda_list->k2;
  else if (mu < 2)
    return 1;
  else if (mu == 2)
    return 2;
  else
    return 3;
}

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
bool nr_UE_is_to_be_scheduled(module_id_t mod_id, int CC_id, int UE_id, frame_t frame, sub_frame_t slot)
{
  const NR_ServingCellConfigCommon_t *scc = RC.nrmac[mod_id]->common_channels->ServingCellConfigCommon;
  const uint8_t slots_per_frame[5] = {10, 20, 40, 80, 160};
  const int n = slots_per_frame[*scc->ssbSubcarrierSpacing];
  const int now = frame * n + slot;

  const struct gNB_MAC_INST_s *nrmac = RC.nrmac[mod_id];
  const NR_UE_sched_ctrl_t *sched_ctrl = &nrmac->UE_info.UE_sched_ctrl[UE_id];
  const int last_ul_sched = sched_ctrl->last_ul_frame * n + sched_ctrl->last_ul_slot;

  const int diff = (now - last_ul_sched + 1024 * n) % (1024 * n);
  /* UE is to be scheduled if
   * (1) we think the UE has more bytes awaiting than what we scheduled
   * (2) there is a scheduling request
   * (3) or we did not schedule it in more than 10 frames */
  const bool has_data = sched_ctrl->estimated_ul_buffer > sched_ctrl->sched_ul_bytes;
913
  const bool high_inactivity = diff >= nrmac->ulsch_max_frame_inactivity * n;
914
  LOG_D(NR_MAC,
915 916 917 918 919 920 921 922 923
        "%4d.%2d UL inactivity %d slots has_data %d SR %d\n",
        frame,
        slot,
        diff,
        has_data,
        sched_ctrl->SR);
  return has_data || sched_ctrl->SR || high_inactivity;
}

924 925 926 927 928 929 930
int next_list_entry_looped(NR_list_t *list, int UE_id)
{
  if (UE_id < 0)
    return list->head;
  return list->next[UE_id] < 0 ? list->head : list->next[UE_id];
}

931 932 933 934 935 936 937 938 939 940 941 942 943
bool allocate_ul_retransmission(module_id_t module_id,
                                frame_t frame,
                                sub_frame_t slot,
                                uint8_t *rballoc_mask,
                                int *n_rb_sched,
                                int UE_id,
                                int harq_pid)
{
  const int CC_id = 0;
  const NR_ServingCellConfigCommon_t *scc = RC.nrmac[module_id]->common_channels[CC_id].ServingCellConfigCommon;
  NR_UE_info_t *UE_info = &RC.nrmac[module_id]->UE_info;
  NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
  NR_sched_pusch_t *retInfo = &sched_ctrl->ul_harq_processes[harq_pid].sched_pusch;
Eurecom's avatar
Eurecom committed
944 945
  NR_CellGroupConfig_t *cg = UE_info->CellGroup[UE_id];
  NR_BWP_UplinkDedicated_t *ubwpd= cg ? cg->spCellConfig->spCellConfigDedicated->uplinkConfig->initialUplinkBWP:NULL;
946
  NR_BWP_t *genericParameters = sched_ctrl->active_ubwp ? &sched_ctrl->active_ubwp->bwp_Common->genericParameters : &scc->uplinkConfigCommon->initialUplinkBWP->genericParameters;
947
  int rbStart = 0; // wrt BWP start
948
  const uint16_t bwpSize = NRRIV2BW(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
949

Eurecom's avatar
Eurecom committed
950
  const uint8_t num_dmrs_cdm_grps_no_data = (sched_ctrl->active_bwp || ubwpd) ? 1 : 2;
951
  const int tda = sched_ctrl->active_ubwp ? RC.nrmac[module_id]->preferred_ul_tda[sched_ctrl->active_ubwp->bwp_Id][slot] : 0;
952
  LOG_D(NR_MAC,"retInfo->time_domain_allocation = %d, tda = %d\n", retInfo->time_domain_allocation, tda);
rmagueta's avatar
rmagueta committed
953
  LOG_D(NR_MAC,"num_dmrs_cdm_grps_no_data %d, tbs %d\n",num_dmrs_cdm_grps_no_data, retInfo->tb_size);
954 955 956 957
  if (tda == retInfo->time_domain_allocation) {
    /* Check the resource is enough for retransmission */
    while (rbStart < bwpSize && !rballoc_mask[rbStart])
      rbStart++;
958 959
    if (rbStart + retInfo->rbSize > bwpSize) {
      LOG_W(NR_MAC, "cannot allocate retransmission of UE %d/RNTI %04x: no resources (rbStart %d, retInfo->rbSize %d, bwpSize %d\n", UE_id, UE_info->rnti[UE_id], rbStart, retInfo->rbSize, bwpSize);
960 961 962 963 964
      return false;
    }
    /* check whether we need to switch the TDA allocation since tha last
     * (re-)transmission */
    NR_pusch_semi_static_t *ps = &sched_ctrl->pusch_semi_static;
Eurecom's avatar
Eurecom committed
965 966 967

    int dci_format = get_dci_format(sched_ctrl);

968 969 970
    if (ps->time_domain_allocation != tda
        || ps->dci_format != dci_format
        || ps->num_dmrs_cdm_grps_no_data != num_dmrs_cdm_grps_no_data)
Eurecom's avatar
Eurecom committed
971
      nr_set_pusch_semi_static(scc, sched_ctrl->active_ubwp, ubwpd, dci_format, tda, num_dmrs_cdm_grps_no_data, ps);
972
    LOG_D(NR_MAC, "%s(): retransmission keeping TDA %d and TBS %d\n", __func__, tda, retInfo->tb_size);
973 974 975 976 977 978 979 980 981
  } else {
    /* the retransmission will use a different time domain allocation, check
     * that we have enough resources */
    while (rbStart < bwpSize && !rballoc_mask[rbStart])
      rbStart++;
    int rbSize = 0;
    while (rbStart + rbSize < bwpSize && rballoc_mask[rbStart + rbSize])
      rbSize++;
    NR_pusch_semi_static_t temp_ps;
Eurecom's avatar
Eurecom committed
982 983
    int dci_format = get_dci_format(sched_ctrl);
    nr_set_pusch_semi_static(scc, sched_ctrl->active_ubwp,ubwpd, dci_format, tda, num_dmrs_cdm_grps_no_data, &temp_ps);
984 985 986 987 988 989 990 991 992 993 994
    uint32_t new_tbs;
    uint16_t new_rbSize;
    bool success = nr_find_nb_rb(retInfo->Qm,
                                 retInfo->R,
                                 temp_ps.nrOfSymbols,
                                 temp_ps.N_PRB_DMRS * temp_ps.num_dmrs_symb,
                                 retInfo->tb_size,
                                 rbSize,
                                 &new_tbs,
                                 &new_rbSize);
    if (!success || new_tbs != retInfo->tb_size) {
995
      LOG_D(NR_MAC, "%s(): new TBsize %d of new TDA does not match old TBS %d\n", __func__, new_tbs, retInfo->tb_size);
996 997
      return false; /* the maximum TBsize we might have is smaller than what we need */
    }
998
    LOG_D(NR_MAC, "%s(): retransmission with TDA %d->%d and TBS %d -> %d\n", __func__, retInfo->time_domain_allocation, tda, retInfo->tb_size, new_tbs);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    /* we can allocate it. Overwrite the time_domain_allocation, the number
     * of RBs, and the new TB size. The rest is done below */
    retInfo->tb_size = new_tbs;
    retInfo->rbSize = new_rbSize;
    retInfo->time_domain_allocation = tda;
    sched_ctrl->pusch_semi_static = temp_ps;
  }

  /* Find free CCE */
  bool freeCCE = find_free_CCE(module_id, slot, UE_id);
  if (!freeCCE) {
1010
    LOG_D(NR_MAC, "%4d.%2d no free CCE for retransmission UL DCI UE %04x\n", frame, slot, UE_info->rnti[UE_id]);
1011 1012 1013
    return false;
  }

1014 1015 1016 1017 1018 1019 1020 1021 1022
  /* frame/slot in sched_pusch has been set previously. In the following, we
   * overwrite the information in the retransmission information before storing
   * as the new scheduling instruction */
  retInfo->frame = sched_ctrl->sched_pusch.frame;
  retInfo->slot = sched_ctrl->sched_pusch.slot;
  /* Get previous PSUCH field info */
  sched_ctrl->sched_pusch = *retInfo;
  NR_sched_pusch_t *sched_pusch = &sched_ctrl->sched_pusch;

1023
  LOG_D(NR_MAC,
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        "%4d.%2d Allocate UL retransmission UE %d/RNTI %04x sched %4d.%2d (%d RBs)\n",
        frame,
        slot,
        UE_id,
        UE_info->rnti[UE_id],
        sched_pusch->frame,
        sched_pusch->slot,
        sched_pusch->rbSize);

  sched_pusch->rbStart = rbStart;
  /* no need to recompute the TBS, it will be the same */

  /* Mark the corresponding RBs as used */
  n_rb_sched -= sched_pusch->rbSize;
  for (int rb = 0; rb < sched_ctrl->sched_pusch.rbSize; rb++)
    rballoc_mask[rb + sched_ctrl->sched_pusch.rbStart] = 0;
  return true;
}

void update_ul_ue_R_Qm(NR_sched_pusch_t *sched_pusch, const NR_pusch_semi_static_t *ps)
{
  const int mcs = sched_pusch->mcs;
  sched_pusch->R = nr_get_code_rate_ul(mcs, ps->mcs_table);
  sched_pusch->Qm = nr_get_Qm_ul(mcs, ps->mcs_table);
1048 1049

  if (ps->pusch_Config && ps->pusch_Config->tp_pi2BPSK && ((ps->mcs_table == 3 && mcs < 2) || (ps->mcs_table == 4 && mcs < 6))) {
1050 1051 1052 1053 1054
    sched_pusch->R >>= 1;
    sched_pusch->Qm <<= 1;
  }
}

1055
float ul_thr_ue[MAX_MOBILES_PER_GNB];
Laurent THOMAS's avatar
Laurent THOMAS committed
1056
uint32_t ul_pf_tbs[3][29]; // pre-computed, approximate TBS values for PF coefficient
ChiehChun's avatar
ChiehChun committed
1057 1058 1059 1060
void pf_ul(module_id_t module_id,
           frame_t frame,
           sub_frame_t slot,
           NR_list_t *UE_list,
1061
           int max_num_ue,
ChiehChun's avatar
ChiehChun committed
1062
           int n_rb_sched,
1063
           uint8_t *rballoc_mask) {
ChiehChun's avatar
ChiehChun committed
1064 1065

  const int CC_id = 0;
1066 1067 1068
  gNB_MAC_INST *nrmac = RC.nrmac[module_id];
  NR_ServingCellConfigCommon_t *scc = nrmac->common_channels[CC_id].ServingCellConfigCommon;
  NR_UE_info_t *UE_info = &nrmac->UE_info;
rmagueta's avatar
rmagueta committed
1069
  const int min_rb = 5;
Robert Schmidt's avatar
Robert Schmidt committed
1070
  float coeff_ue[MAX_MOBILES_PER_GNB];
1071 1072 1073
  // UEs that could be scheduled
  int ue_array[MAX_MOBILES_PER_GNB];
  NR_list_t UE_sched = { .head = -1, .next = ue_array, .tail = -1, .len = MAX_MOBILES_PER_GNB };
ChiehChun's avatar
ChiehChun committed
1074 1075 1076

  /* Loop UE_list to calculate throughput and coeff */
  for (int UE_id = UE_list->head; UE_id >= 0; UE_id = UE_list->next[UE_id]) {
1077 1078 1079

    if (UE_info->Msg4_ACKed[UE_id] != true) continue;

1080
    LOG_D(NR_MAC,"pf_ul: preparing UL scheduling for UE %d\n",UE_id);
ChiehChun's avatar
ChiehChun committed
1081
    NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
rmagueta's avatar
rmagueta committed
1082
    NR_BWP_t *genericParameters = sched_ctrl->active_ubwp ? &sched_ctrl->active_ubwp->bwp_Common->genericParameters : &scc->uplinkConfigCommon->initialUplinkBWP->genericParameters;
1083
    int rbStart = 0; // wrt BWP start
Eurecom's avatar
Eurecom committed
1084 1085 1086
    NR_CellGroupConfig_t *cg = UE_info->CellGroup[UE_id];
    NR_BWP_UplinkDedicated_t *ubwpd= cg ? cg->spCellConfig->spCellConfigDedicated->uplinkConfig->initialUplinkBWP : NULL;

rmagueta's avatar
rmagueta committed
1087
    const uint16_t bwpSize = NRRIV2BW(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
1088 1089
    NR_sched_pusch_t *sched_pusch = &sched_ctrl->sched_pusch;
    NR_pusch_semi_static_t *ps = &sched_ctrl->pusch_semi_static;
ChiehChun's avatar
ChiehChun committed
1090 1091

    /* Calculate throughput */
1092 1093 1094
    const float a = 0.0005f; // corresponds to 200ms window
    const uint32_t b = UE_info->mac_stats[UE_id].ulsch_current_bytes;
    ul_thr_ue[UE_id] = (1 - a) * ul_thr_ue[UE_id] + a * b;
ChiehChun's avatar
ChiehChun committed
1095

1096
    /* Check if retransmission is necessary */
1097
    sched_pusch->ul_harq_pid = sched_ctrl->retrans_ul_harq.head;
1098
    LOG_D(NR_MAC,"pf_ul: UE %d harq_pid %d\n",UE_id,sched_pusch->ul_harq_pid);
1099 1100 1101 1102 1103
    if (sched_pusch->ul_harq_pid >= 0) {
      /* Allocate retransmission*/
      bool r = allocate_ul_retransmission(
          module_id, frame, slot, rballoc_mask, &n_rb_sched, UE_id, sched_pusch->ul_harq_pid);
      if (!r) {
1104
        LOG_D(NR_MAC, "%4d.%2d UL retransmission UE RNTI %04x can NOT be allocated\n", frame, slot, UE_info->rnti[UE_id]);
1105 1106
        continue;
      }
1107 1108
      else LOG_D(NR_MAC,"%4d.%2d UL Retransmission UE RNTI %04x to be allocated, max_num_ue %d\n",frame,slot,UE_info->rnti[UE_id],max_num_ue);

1109 1110 1111 1112
      /* reduce max_num_ue once we are sure UE can be allocated, i.e., has CCE */
      max_num_ue--;
      if (max_num_ue < 0)
        return;
1113 1114 1115
      continue;
    }

1116 1117 1118 1119
    const int B = max(0, sched_ctrl->estimated_ul_buffer - sched_ctrl->sched_ul_bytes);
    /* preprocessor computed sched_frame/sched_slot */
    const bool do_sched = nr_UE_is_to_be_scheduled(module_id, 0, UE_id, sched_pusch->frame, sched_pusch->slot);

1120
    LOG_D(NR_MAC,"pf_ul: do_sched UE %d => %s\n",UE_id,do_sched ? "yes" : "no");
1121
    if (B == 0 && !do_sched)
Robert Schmidt's avatar
Robert Schmidt committed
1122 1123
      continue;

1124 1125 1126
    /* Schedule UE on SR or UL inactivity and no data (otherwise, will be scheduled
     * based on data to transmit) */
    if (B == 0 && do_sched) {
1127
      /* if no data, pre-allocate 5RB */
1128 1129
      bool freeCCE = find_free_CCE(module_id, slot, UE_id);
      if (!freeCCE) {
1130
        LOG_D(NR_MAC, "%4d.%2d no free CCE for UL DCI UE %04x (BSR 0)\n", frame, slot, UE_info->rnti[UE_id]);
1131 1132 1133 1134 1135 1136 1137
        continue;
      }
      /* reduce max_num_ue once we are sure UE can be allocated, i.e., has CCE */
      max_num_ue--;
      if (max_num_ue < 0)
        return;

1138
      LOG_D(NR_MAC,"Looking for min_rb %d RBs, starting at %d\n", min_rb, rbStart);
1139 1140
      while (rbStart < bwpSize && !rballoc_mask[rbStart]) rbStart++;
      if (rbStart + min_rb >= bwpSize) {
1141
        LOG_W(NR_MAC, "cannot allocate continuous UL data for UE %d/RNTI %04x: no resources (rbStart %d, min_rb %d, bwpSize %d\n",
1142
              UE_id, UE_info->rnti[UE_id],rbStart,min_rb,bwpSize);
1143 1144
        return;
      }
1145 1146 1147 1148 1149

      /* Save PUSCH field */
      /* we want to avoid a lengthy deduction of DMRS and other parameters in
       * every TTI if we can save it, so check whether dci_format, TDA, or
       * num_dmrs_cdm_grps_no_data has changed and only then recompute */
Eurecom's avatar
Eurecom committed
1150 1151
      const uint8_t num_dmrs_cdm_grps_no_data = (sched_ctrl->active_ubwp || ubwpd) ? 1 : 2;
      int dci_format = get_dci_format(sched_ctrl);
1152
      const int tda = sched_ctrl->active_ubwp ? nrmac->preferred_ul_tda[sched_ctrl->active_ubwp->bwp_Id][slot] : 0;
1153 1154 1155
      if (ps->time_domain_allocation != tda
          || ps->dci_format != dci_format
          || ps->num_dmrs_cdm_grps_no_data != num_dmrs_cdm_grps_no_data)
Eurecom's avatar
Eurecom committed
1156
        nr_set_pusch_semi_static(scc, sched_ctrl->active_ubwp, ubwpd, dci_format, tda, num_dmrs_cdm_grps_no_data, ps);
1157 1158 1159
      NR_sched_pusch_t *sched_pusch = &sched_ctrl->sched_pusch;
      sched_pusch->mcs = 9;
      update_ul_ue_R_Qm(sched_pusch, ps);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
      sched_pusch->rbStart = rbStart;
      sched_pusch->rbSize = min_rb;
      sched_pusch->tb_size = nr_compute_tbs(sched_pusch->Qm,
                                            sched_pusch->R,
                                            sched_pusch->rbSize,
                                            ps->nrOfSymbols,
                                            ps->N_PRB_DMRS * ps->num_dmrs_symb,
                                            0, // nb_rb_oh
                                            0,
                                            1 /* NrOfLayers */)
                             >> 3;

      /* Mark the corresponding RBs as used */
      n_rb_sched -= sched_pusch->rbSize;
      for (int rb = 0; rb < sched_ctrl->sched_pusch.rbSize; rb++)
        rballoc_mask[rb + sched_ctrl->sched_pusch.rbStart] = 0;

      continue;
1178
    }
1179 1180 1181

    /* Create UE_sched for UEs eligibale for new data transmission*/
    add_tail_nr_list(&UE_sched, UE_id);
Robert Schmidt's avatar
Robert Schmidt committed
1182 1183

    /* Calculate coefficient*/
1184 1185
    sched_pusch->mcs = 9;
    const uint32_t tbs = ul_pf_tbs[ps->mcs_table][sched_pusch->mcs];
Robert Schmidt's avatar
Robert Schmidt committed
1186
    coeff_ue[UE_id] = (float) tbs / ul_thr_ue[UE_id];
1187
    LOG_D(NR_MAC,"b %d, ul_thr_ue[%d] %f, tbs %d, coeff_ue[%d] %f\n",
Robert Schmidt's avatar
Robert Schmidt committed
1188
          b, UE_id, ul_thr_ue[UE_id], tbs, UE_id, coeff_ue[UE_id]);
1189 1190
  }

Robert Schmidt's avatar
Robert Schmidt committed
1191 1192

  /* Loop UE_sched to find max coeff and allocate transmission */
1193
  while (UE_sched.head >= 0 && max_num_ue> 0 && n_rb_sched > 0) {
Robert Schmidt's avatar
Robert Schmidt committed
1194
    /* Find max coeff */
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    int *max = &UE_sched.head; /* Find max coeff: assume head is max */
    int *p = &UE_sched.next[*max];
    while (*p >= 0) {
      /* Find max coeff: if the current one has larger coeff, save for later */
      if (coeff_ue[*p] > coeff_ue[*max])
        max = p;
      p = &UE_sched.next[*p];
    }
    /* Find max coeff: remove the max one: do not use remove_nr_list() since it
     * goes through the whole list every time. Note that UE_sched.tail might
     * not be set correctly anymore */
    const int UE_id = *max;
    p = &UE_sched.next[*max];
    *max = UE_sched.next[*max];
    *p = -1;
Robert Schmidt's avatar
Robert Schmidt committed
1210

1211 1212
    bool freeCCE = find_free_CCE(module_id, slot, UE_id);
    if (!freeCCE) {
1213
      LOG_D(NR_MAC, "%4d.%2d no free CCE for UL DCI UE %04x\n", frame, slot, UE_info->rnti[UE_id]);
1214 1215
      continue;
    }
1216
    else LOG_D(NR_MAC, "%4d.%2d free CCE for UL DCI UE %04x\n",frame,slot, UE_info->rnti[UE_id]);
1217 1218

    /* reduce max_num_ue once we are sure UE can be allocated, i.e., has CCE */
Robert Schmidt's avatar
Robert Schmidt committed
1219
    max_num_ue--;
1220 1221
    if (max_num_ue < 0)
      return;
Robert Schmidt's avatar
Robert Schmidt committed
1222

1223
    NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
Eurecom's avatar
Eurecom committed
1224 1225
    NR_CellGroupConfig_t *cg = UE_info->CellGroup[UE_id];
    NR_BWP_UplinkDedicated_t *ubwpd= cg ? cg->spCellConfig->spCellConfigDedicated->uplinkConfig->initialUplinkBWP:NULL;
rmagueta's avatar
rmagueta committed
1226 1227
    NR_BWP_t *genericParameters = sched_ctrl->active_ubwp ? &sched_ctrl->active_ubwp->bwp_Common->genericParameters : &scc->uplinkConfigCommon->initialUplinkBWP->genericParameters;
    int rbStart = sched_ctrl->active_ubwp ? NRRIV2PRBOFFSET(genericParameters->locationAndBandwidth, MAX_BWP_SIZE) : 0;
1228
    const uint16_t bwpSize = NRRIV2BW(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
Robert Schmidt's avatar
Robert Schmidt committed
1229
    NR_sched_pusch_t *sched_pusch = &sched_ctrl->sched_pusch;
1230
    NR_pusch_semi_static_t *ps = &sched_ctrl->pusch_semi_static;
ChiehChun's avatar
ChiehChun committed
1231 1232 1233

    while (rbStart < bwpSize && !rballoc_mask[rbStart]) rbStart++;
    sched_pusch->rbStart = rbStart;
1234 1235 1236 1237
    uint16_t max_rbSize = 1;
    while (rbStart + max_rbSize < bwpSize && rballoc_mask[rbStart + max_rbSize])
      max_rbSize++;

ChiehChun's avatar
ChiehChun committed
1238
    if (rbStart + min_rb >= bwpSize) {
1239
      LOG_W(NR_MAC, "cannot allocate UL data for UE %d/RNTI %04x: no resources (rbStart %d, min_rb %d, bwpSize %d\n",
1240
	    UE_id, UE_info->rnti[UE_id],rbStart,min_rb,bwpSize);
ChiehChun's avatar
ChiehChun committed
1241
      return;
1242
    }
rmagueta's avatar
rmagueta committed
1243
    else LOG_D(NR_MAC,"allocating UL data for UE %d/RNTI %04x (rbStsart %d, min_rb %d, bwpSize %d\n",UE_id, UE_info->rnti[UE_id],rbStart,min_rb,bwpSize);
ChiehChun's avatar
ChiehChun committed
1244

1245 1246 1247 1248
    /* Save PUSCH field */
    /* we want to avoid a lengthy deduction of DMRS and other parameters in
     * every TTI if we can save it, so check whether dci_format, TDA, or
     * num_dmrs_cdm_grps_no_data has changed and only then recompute */
Eurecom's avatar
Eurecom committed
1249
    const uint8_t num_dmrs_cdm_grps_no_data = (sched_ctrl->active_ubwp || ubwpd) ? 1 : 2;
Eurecom's avatar
Eurecom committed
1250
    int dci_format = get_dci_format(sched_ctrl);
1251
    const int tda = sched_ctrl->active_ubwp ? nrmac->preferred_ul_tda[sched_ctrl->active_ubwp->bwp_Id][slot] : 0;
1252 1253 1254
    if (ps->time_domain_allocation != tda
        || ps->dci_format != dci_format
        || ps->num_dmrs_cdm_grps_no_data != num_dmrs_cdm_grps_no_data)
Eurecom's avatar
Eurecom committed
1255
      nr_set_pusch_semi_static(scc, sched_ctrl->active_ubwp, ubwpd, dci_format, tda, num_dmrs_cdm_grps_no_data, ps);
1256
    update_ul_ue_R_Qm(sched_pusch, ps);
ChiehChun's avatar
ChiehChun committed
1257

1258
    /* Calculate the current scheduling bytes and the necessary RBs */
ChiehChun's avatar
ChiehChun committed
1259
    const int B = cmax(sched_ctrl->estimated_ul_buffer - sched_ctrl->sched_ul_bytes, 0);
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    uint16_t rbSize = 0;
    uint32_t TBS = 0;
    nr_find_nb_rb(sched_pusch->Qm,
                  sched_pusch->R,
                  ps->nrOfSymbols,
                  ps->N_PRB_DMRS * ps->num_dmrs_symb,
                  B,
                  max_rbSize,
                  &TBS,
                  &rbSize);
    sched_pusch->rbSize = rbSize;
    sched_pusch->tb_size = TBS;
1272
    LOG_D(NR_MAC,"rbSize %d, TBS %d, est buf %d, sched_ul %d, B %d, CCE %d, num_dmrs_symb %d, N_PRB_DMRS %d\n",
Eurecom's avatar
Eurecom committed
1273
          rbSize, sched_pusch->tb_size, sched_ctrl->estimated_ul_buffer, sched_ctrl->sched_ul_bytes, B,sched_ctrl->cce_index,ps->num_dmrs_symb,ps->N_PRB_DMRS);
ChiehChun's avatar
ChiehChun committed
1274 1275

    /* Mark the corresponding RBs as used */
1276
    n_rb_sched -= sched_pusch->rbSize;
ChiehChun's avatar
ChiehChun committed
1277 1278
    for (int rb = 0; rb < sched_ctrl->sched_pusch.rbSize; rb++)
      rballoc_mask[rb + sched_ctrl->sched_pusch.rbStart] = 0;
1279 1280 1281
  }
}

1282 1283
bool nr_fr1_ulsch_preprocessor(module_id_t module_id, frame_t frame, sub_frame_t slot)
{
1284 1285 1286 1287 1288
  gNB_MAC_INST *nr_mac = RC.nrmac[module_id];
  NR_COMMON_channels_t *cc = nr_mac->common_channels;
  NR_ServingCellConfigCommon_t *scc = cc->ServingCellConfigCommon;
  const int mu = scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.subcarrierSpacing;
  NR_UE_info_t *UE_info = &nr_mac->UE_info;
1289 1290

  if (UE_info->num_UEs == 0)
1291
    return false;
1292 1293 1294

  const int CC_id = 0;

1295 1296 1297 1298
  /* Get the K2 for first UE to compute offset. The other UEs are guaranteed to
   * have the same K2 (we don't support multiple/different K2s via different
   * TDAs yet). If the TDA is negative, it means that there is no UL slot to
   * schedule now (slot + k2 is not UL slot) */
ChiehChun's avatar
ChiehChun committed
1299 1300
  int UE_id = UE_info->list.head;
  NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
1301
  const int tda = sched_ctrl->active_ubwp ? nr_mac->preferred_ul_tda[sched_ctrl->active_ubwp->bwp_Id][slot] : 0;
1302 1303
  if (tda < 0)
    return false;
rmagueta's avatar
rmagueta committed
1304
  int K2 = get_K2(scc, sched_ctrl->active_ubwp, tda, mu);
ChiehChun's avatar
ChiehChun committed
1305 1306
  const int sched_frame = frame + (slot + K2 >= nr_slots_per_frame[mu]);
  const int sched_slot = (slot + K2) % nr_slots_per_frame[mu];
1307

1308
  if (!is_xlsch_in_slot(nr_mac->ulsch_slot_bitmap[sched_slot / 64], sched_slot))
1309
    return false;
1310

1311 1312 1313 1314 1315 1316 1317
  bool is_mixed_slot = is_xlsch_in_slot(nr_mac->dlsch_slot_bitmap[sched_slot / 64], sched_slot) &&
                        is_xlsch_in_slot(nr_mac->ulsch_slot_bitmap[sched_slot / 64], sched_slot);

  // FIXME: Avoid mixed slots for initialUplinkBWP
  if (sched_ctrl->active_ubwp==NULL && is_mixed_slot)
    return false;

1318 1319
  sched_ctrl->sched_pusch.slot = sched_slot;
  sched_ctrl->sched_pusch.frame = sched_frame;
ChiehChun's avatar
ChiehChun committed
1320
  for (UE_id = UE_info->list.next[UE_id]; UE_id >= 0; UE_id = UE_info->list.next[UE_id]) {
ChiehChun's avatar
ChiehChun committed
1321
    NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
1322 1323
    AssertFatal(K2 == get_K2(scc,sched_ctrl->active_ubwp, tda, mu),
                "Different K2, %d(UE%d) != %ld(UE%d)\n", K2, 0, get_K2(scc,sched_ctrl->active_ubwp, tda, mu), UE_id);
ChiehChun's avatar
ChiehChun committed
1324 1325
    sched_ctrl->sched_pusch.slot = sched_slot;
    sched_ctrl->sched_pusch.frame = sched_frame;
1326
  }
Robert Schmidt's avatar
Robert Schmidt committed
1327

1328 1329 1330
  /* Change vrb_map_UL to rballoc_mask: check which symbols per RB (in
   * vrb_map_UL) overlap with the "default" tda and exclude those RBs.
   * Calculate largest contiguous RBs */
1331 1332
  uint16_t *vrb_map_UL =
      &RC.nrmac[module_id]->common_channels[CC_id].vrb_map_UL[sched_slot * MAX_BWP_SIZE];
1333 1334 1335 1336
  const uint16_t bwpSize = NRRIV2BW(sched_ctrl->active_ubwp ?
                                    sched_ctrl->active_ubwp->bwp_Common->genericParameters.locationAndBandwidth:
                                    scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth,
                                    MAX_BWP_SIZE);
1337 1338 1339 1340
  const uint16_t bwpStart = NRRIV2PRBOFFSET(sched_ctrl->active_ubwp ?
                                            sched_ctrl->active_ubwp->bwp_Common->genericParameters.locationAndBandwidth:
                                            scc->uplinkConfigCommon->initialUplinkBWP->genericParameters.locationAndBandwidth,
                                            MAX_BWP_SIZE);
1341 1342 1343
  const struct NR_PUSCH_TimeDomainResourceAllocationList *tdaList = sched_ctrl->active_ubwp ?
    sched_ctrl->active_ubwp->bwp_Common->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList:
    scc->uplinkConfigCommon->initialUplinkBWP->pusch_ConfigCommon->choice.setup->pusch_TimeDomainAllocationList;
1344 1345 1346 1347
  const int startSymbolAndLength = tdaList->list.array[tda]->startSymbolAndLength;
  int startSymbolIndex, nrOfSymbols;
  SLIV2SL(startSymbolAndLength, &startSymbolIndex, &nrOfSymbols);
  const uint16_t symb = ((1 << nrOfSymbols) - 1) << startSymbolIndex;
1348

1349
  int st = 0, e = 0, len = 0;
1350
  for (int i = 0; i < bwpSize; i++) 
1351
    if (RC.nrmac[module_id]->ulprbbl[i] == 1) vrb_map_UL[i]=symb;
1352

1353
  for (int i = 0; i < bwpSize; i++) {
1354
    while ((vrb_map_UL[bwpStart + i] & symb) != 0 && i < bwpSize)
1355 1356
      i++;
    st = i;
1357
    while ((vrb_map_UL[bwpStart + i] & symb) == 0 && i < bwpSize)
1358 1359 1360 1361 1362
      i++;
    if (i - st > len) {
      len = i - st;
      e = i - 1;
    }
1363
  }
1364 1365
  st = e - len + 1;

Raymond Knopp's avatar
Raymond Knopp committed
1366
  LOG_D(NR_MAC,"UL %d.%d : start_prb %d, end PRB %d\n",frame,slot,st,e);
1367
  
1368 1369 1370 1371 1372
  uint8_t rballoc_mask[bwpSize];

  /* Calculate mask: if any RB in vrb_map_UL is blocked (1), the current RB will be 0 */
  for (int i = 0; i < bwpSize; i++)
    rballoc_mask[i] = i >= st && i <= e;
1373

ChiehChun's avatar
ChiehChun committed
1374 1375 1376 1377 1378
  /* proportional fair scheduling algorithm */
  pf_ul(module_id,
        frame,
        slot,
        &UE_info->list,
1379
        2,
1380
        len,
1381
        rballoc_mask);
1382
  return true;
1383 1384
}

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
nr_pp_impl_ul nr_init_fr1_ulsch_preprocessor(module_id_t module_id, int CC_id)
{
  /* in the PF algorithm, we have to use the TBsize to compute the coefficient.
   * This would include the number of DMRS symbols, which in turn depends on
   * the time domain allocation. In case we are in a mixed slot, we do not want
   * to recalculate all these values, and therefore we provide a look-up table
   * which should approximately(!) give us the TBsize. In particular, the
   * number of symbols, the number of DMRS symbols, and the exact Qm and R, are
   * not correct*/
  for (int mcsTableIdx = 0; mcsTableIdx < 3; ++mcsTableIdx) {
    for (int mcs = 0; mcs < 29; ++mcs) {
      if (mcs > 27 && mcsTableIdx == 1)
        continue;
      const uint8_t Qm = nr_get_Qm_dl(mcs, mcsTableIdx);
      const uint16_t R = nr_get_code_rate_dl(mcs, mcsTableIdx);
      /* note: we do not update R/Qm based on low MCS or pi2BPSK */
      ul_pf_tbs[mcsTableIdx][mcs] = nr_compute_tbs(Qm,
                                                   R,
                                                   1, /* rbSize */
                                                   10, /* hypothetical number of slots */
                                                   0, /* N_PRB_DMRS * N_DMRS_SLOT */
                                                   0 /* N_PRB_oh, 0 for initialBWP */,
                                                   0 /* tb_scaling */,
                                                   1 /* nrOfLayers */)
                                    >> 3;
    }
  }
  return nr_fr1_ulsch_preprocessor;
}

void nr_schedule_ulsch(module_id_t module_id, frame_t frame, sub_frame_t slot)
{
  gNB_MAC_INST *nr_mac = RC.nrmac[module_id];
1418 1419
  /* Uplink data ONLY can be scheduled when the current slot is downlink slot,
   * because we have to schedule the DCI0 first before schedule uplink data */
1420
  if (!is_xlsch_in_slot(nr_mac->dlsch_slot_bitmap[slot / 64], slot)) {
1421
    LOG_D(NR_MAC, "Current slot %d is NOT DL slot, cannot schedule DCI0 for UL data\n", slot);
1422 1423
    return;
  }
1424
  bool do_sched = RC.nrmac[module_id]->pre_processor_ul(module_id, frame, slot);
1425 1426
  if (!do_sched)
    return;
1427

1428 1429 1430 1431 1432 1433 1434
  const int CC_id = 0;
  nfapi_nr_ul_dci_request_t *ul_dci_req = &RC.nrmac[module_id]->UL_dci_req[CC_id];
  ul_dci_req->SFN = frame;
  ul_dci_req->Slot = slot;
  /* a PDCCH PDU groups DCIs per BWP and CORESET. Save a pointer to each
   * allocated PDCCH so we can easily allocate UE's DCIs independent of any
   * CORESET order */
1435
  nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu_bwp_coreset[MAX_NUM_BWP][MAX_NUM_CORESET] = {{0}};
1436

1437
  NR_ServingCellConfigCommon_t *scc = RC.nrmac[module_id]->common_channels[0].ServingCellConfigCommon;
1438
  NR_UE_info_t *UE_info = &RC.nrmac[module_id]->UE_info;
1439
  const NR_list_t *UE_list = &UE_info->list;
1440 1441
  for (int UE_id = UE_list->head; UE_id >= 0; UE_id = UE_list->next[UE_id]) {
    NR_UE_sched_ctrl_t *sched_ctrl = &UE_info->UE_sched_ctrl[UE_id];
1442
    if (sched_ctrl->ul_failure == 1 && get_softmodem_params()->phy_test==0) continue;
1443 1444 1445

    NR_CellGroupConfig_t *cg = UE_info->CellGroup[UE_id];
    NR_BWP_UplinkDedicated_t *ubwpd= cg ? cg->spCellConfig->spCellConfigDedicated->uplinkConfig->initialUplinkBWP:NULL;
1446
    UE_info->mac_stats[UE_id].ulsch_current_bytes = 0;
1447

1448 1449
    /* dynamic PUSCH values (RB alloc, MCS, hence R, Qm, TBS) that change in
     * every TTI are pre-populated by the preprocessor and used below */
Robert Schmidt's avatar
Robert Schmidt committed
1450
    NR_sched_pusch_t *sched_pusch = &sched_ctrl->sched_pusch;
1451
    LOG_D(NR_MAC,"UE %x : sched_pusch->rbSize %d\n",UE_info->rnti[UE_id],sched_pusch->rbSize);
Robert Schmidt's avatar
Robert Schmidt committed
1452
    if (sched_pusch->rbSize <= 0)
1453 1454 1455
      continue;

    uint16_t rnti = UE_info->rnti[UE_id];
Robert Schmidt's avatar
Robert Schmidt committed
1456
    sched_ctrl->SR = false;
1457

1458 1459 1460 1461 1462 1463 1464 1465
    int8_t harq_id = sched_pusch->ul_harq_pid;
    if (harq_id < 0) {
      /* PP has not selected a specific HARQ Process, get a new one */
      harq_id = sched_ctrl->available_ul_harq.head;
      AssertFatal(harq_id >= 0,
                  "no free HARQ process available for UE %d\n",
                  UE_id);
      remove_front_nr_list(&sched_ctrl->available_ul_harq);
1466
      sched_pusch->ul_harq_pid = harq_id;
1467 1468 1469 1470 1471 1472 1473 1474 1475
    } else {
      /* PP selected a specific HARQ process. Check whether it will be a new
       * transmission or a retransmission, and remove from the corresponding
       * list */
      if (sched_ctrl->ul_harq_processes[harq_id].round == 0)
        remove_nr_list(&sched_ctrl->available_ul_harq, harq_id);
      else
        remove_nr_list(&sched_ctrl->retrans_ul_harq, harq_id);
    }
Robert Schmidt's avatar
Robert Schmidt committed
1476
    NR_UE_ul_harq_t *cur_harq = &sched_ctrl->ul_harq_processes[harq_id];
1477 1478 1479 1480
    DevAssert(!cur_harq->is_waiting);
    add_tail_nr_list(&sched_ctrl->feedback_ul_harq, harq_id);
    cur_harq->feedback_slot = sched_pusch->slot;
    cur_harq->is_waiting = true;
Robert Schmidt's avatar
Robert Schmidt committed
1481

Robert Schmidt's avatar
Robert Schmidt committed
1482 1483
    int rnti_types[2] = { NR_RNTI_C, 0 };

1484 1485
    /* pre-computed PUSCH values that only change if time domain allocation,
     * DCI format, or DMRS parameters change. Updated in the preprocessor
1486 1487
     * through nr_set_pusch_semi_static() */
    NR_pusch_semi_static_t *ps = &sched_ctrl->pusch_semi_static;
1488

1489 1490
    /* Statistics */
    UE_info->mac_stats[UE_id].ulsch_rounds[cur_harq->round]++;
1491
    if (cur_harq->round == 0) {
1492
      UE_info->mac_stats[UE_id].ulsch_total_bytes_scheduled += sched_pusch->tb_size;
1493 1494 1495
      /* Save information on MCS, TBS etc for the current initial transmission
       * so we have access to it when retransmitting */
      cur_harq->sched_pusch = *sched_pusch;
1496 1497 1498
      /* save which time allocation has been used, to be used on
       * retransmissions */
      cur_harq->sched_pusch.time_domain_allocation = ps->time_domain_allocation;
1499
      sched_ctrl->sched_ul_bytes += sched_pusch->tb_size;
1500
    } else {
1501
      LOG_D(NR_MAC,
1502
            "%d.%2d UL retransmission RNTI %04x sched %d.%2d HARQ PID %d round %d NDI %d\n",
1503 1504 1505 1506 1507
            frame,
            slot,
            rnti,
            sched_pusch->frame,
            sched_pusch->slot,
1508 1509 1510
            harq_id,
            cur_harq->round,
            cur_harq->ndi);
1511
    }
1512
    UE_info->mac_stats[UE_id].ulsch_current_bytes = sched_pusch->tb_size;
1513 1514
    sched_ctrl->last_ul_frame = sched_pusch->frame;
    sched_ctrl->last_ul_slot = sched_pusch->slot;
1515

rmagueta's avatar
rmagueta committed
1516
    LOG_D(NR_MAC,
Eurecom's avatar
Eurecom committed
1517
          "ULSCH/PUSCH: %4d.%2d RNTI %04x UL sched %4d.%2d DCI L %d start %2d RBS %3d startSymbol %2d nb_symbol %2d dmrs_pos %x MCS %2d TBS %4d HARQ PID %2d round %d RV %d NDI %d est %6d sched %6d est BSR %6d TPC %d\n",
1518 1519 1520 1521 1522
          frame,
          slot,
          rnti,
          sched_pusch->frame,
          sched_pusch->slot,
Eurecom's avatar
Eurecom committed
1523
          sched_ctrl->aggregation_level,
1524 1525
          sched_pusch->rbStart,
          sched_pusch->rbSize,
1526 1527
          ps->startSymbolIndex,
          ps->nrOfSymbols,
1528
          ps->ul_dmrs_symb_pos,
1529 1530 1531 1532
          sched_pusch->mcs,
          sched_pusch->tb_size,
          harq_id,
          cur_harq->round,
1533
          nr_rv_round_map[cur_harq->round],
1534 1535 1536
          cur_harq->ndi,
          sched_ctrl->estimated_ul_buffer,
          sched_ctrl->sched_ul_bytes,
1537 1538
          sched_ctrl->estimated_ul_buffer - sched_ctrl->sched_ul_bytes,
          sched_ctrl->tpc0);
1539

1540

1541
    /* PUSCH in a later slot, but corresponding DCI now! */
Robert Schmidt's avatar
Robert Schmidt committed
1542 1543 1544
    nfapi_nr_ul_tti_request_t *future_ul_tti_req = &RC.nrmac[module_id]->UL_tti_req_ahead[0][sched_pusch->slot];
    AssertFatal(future_ul_tti_req->SFN == sched_pusch->frame
                && future_ul_tti_req->Slot == sched_pusch->slot,
1545 1546 1547 1548
                "%d.%d future UL_tti_req's frame.slot %d.%d does not match PUSCH %d.%d\n",
                frame, slot,
                future_ul_tti_req->SFN,
                future_ul_tti_req->Slot,
Robert Schmidt's avatar
Robert Schmidt committed
1549 1550
                sched_pusch->frame,
                sched_pusch->slot);
1551 1552 1553 1554 1555 1556
    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));
    future_ul_tti_req->n_pdus += 1;

1557
    LOG_D(NR_MAC, "%4d.%2d Scheduling UE specific PUSCH for sched %d.%d, ul_tto_req %d.%d\n", frame, slot,
1558
    sched_pusch->frame,sched_pusch->slot,future_ul_tti_req->SFN,future_ul_tti_req->Slot);
1559 1560 1561 1562 1563

    pusch_pdu->pdu_bit_map = PUSCH_PDU_BITMAP_PUSCH_DATA;
    pusch_pdu->rnti = rnti;
    pusch_pdu->handle = 0; //not yet used

1564
    /* FAPI: BWP */
1565
    NR_BWP_t *genericParameters = sched_ctrl->active_ubwp ? &sched_ctrl->active_ubwp->bwp_Common->genericParameters:&scc->uplinkConfigCommon->initialUplinkBWP->genericParameters;
1566 1567 1568
    pusch_pdu->bwp_size  = NRRIV2BW(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
    pusch_pdu->bwp_start = NRRIV2PRBOFFSET(genericParameters->locationAndBandwidth, MAX_BWP_SIZE);
    pusch_pdu->subcarrier_spacing = genericParameters->subcarrierSpacing;
1569 1570
    pusch_pdu->cyclic_prefix = 0;

1571
    /* FAPI: PUSCH information always included */
1572 1573 1574
    pusch_pdu->target_code_rate = sched_pusch->R;
    pusch_pdu->qam_mod_order = sched_pusch->Qm;
    pusch_pdu->mcs_index = sched_pusch->mcs;
1575 1576
    pusch_pdu->mcs_table = ps->mcs_table;
    pusch_pdu->transform_precoding = ps->transform_precoding;
1577
    if (ps->pusch_Config && ps->pusch_Config->dataScramblingIdentityPUSCH)
1578
      pusch_pdu->data_scrambling_id = *ps->pusch_Config->dataScramblingIdentityPUSCH;
1579 1580 1581 1582
    else
      pusch_pdu->data_scrambling_id = *scc->physCellId;
    pusch_pdu->nrOfLayers = 1;

1583
    /* FAPI: DMRS */
1584 1585
    pusch_pdu->ul_dmrs_symb_pos = ps->ul_dmrs_symb_pos;
    pusch_pdu->dmrs_config_type = ps->dmrs_config_type;
1586
    if (pusch_pdu->transform_precoding) { // transform precoding disabled
1587 1588
      long *scramblingid=NULL;
      if (ps->NR_DMRS_UplinkConfig && pusch_pdu->scid == 0)
1589
        scramblingid = ps->NR_DMRS_UplinkConfig->transformPrecodingDisabled->scramblingID0;
1590
      else if (ps->NR_DMRS_UplinkConfig)
1591
        scramblingid = ps->NR_DMRS_UplinkConfig->transformPrecodingDisabled->scramblingID1;
1592 1593 1594 1595 1596 1597 1598
      if (scramblingid == NULL)
        pusch_pdu->ul_dmrs_scrambling_id = *scc->physCellId;
      else
        pusch_pdu->ul_dmrs_scrambling_id = *scramblingid;
    }
    else {
      pusch_pdu->ul_dmrs_scrambling_id = *scc->physCellId;
1599
      if (ps->NR_DMRS_UplinkConfig && ps->NR_DMRS_UplinkConfig->transformPrecodingEnabled->nPUSCH_Identity != NULL)
1600
        pusch_pdu->pusch_identity = *ps->NR_DMRS_UplinkConfig->transformPrecodingEnabled->nPUSCH_Identity;
1601
      else if (ps->NR_DMRS_UplinkConfig)
1602 1603
        pusch_pdu->pusch_identity = *scc->physCellId;
    }
1604
    pusch_pdu->scid = 0;      // DMRS sequence initialization [TS38.211, sec 6.4.1.1.1]
1605
    pusch_pdu->num_dmrs_cdm_grps_no_data = ps->num_dmrs_cdm_grps_no_data;
1606 1607
    pusch_pdu->dmrs_ports = 1;

1608 1609 1610 1611 1612
    /* FAPI: Pusch Allocation in frequency domain */
    pusch_pdu->resource_alloc = 1; //type 1
    pusch_pdu->rb_start = sched_pusch->rbStart;
    pusch_pdu->rb_size = sched_pusch->rbSize;
    pusch_pdu->vrb_to_prb_mapping = 0;
1613
    if (ps->pusch_Config==NULL || ps->pusch_Config->frequencyHopping==NULL)
1614 1615 1616 1617 1618
      pusch_pdu->frequency_hopping = 0;
    else
      pusch_pdu->frequency_hopping = 1;

    /* FAPI: Resource Allocation in time domain */
1619 1620
    pusch_pdu->start_symbol_index = ps->startSymbolIndex;
    pusch_pdu->nr_of_symbols = ps->nrOfSymbols;
1621 1622 1623 1624 1625

    /* PUSCH PDU */
    pusch_pdu->pusch_data.rv_index = nr_rv_round_map[cur_harq->round];
    pusch_pdu->pusch_data.harq_process_id = harq_id;
    pusch_pdu->pusch_data.new_data_indicator = cur_harq->ndi;
1626
    pusch_pdu->pusch_data.tb_size = sched_pusch->tb_size;
1627 1628
    pusch_pdu->pusch_data.num_cb = 0; //CBG not supported

1629
    LOG_D(NR_MAC,"PUSCH PDU : data_scrambling_identity %x, dmrs_scrambling_id %x\n",pusch_pdu->data_scrambling_id,pusch_pdu->ul_dmrs_scrambling_id);
1630 1631 1632 1633 1634 1635 1636 1637
    /* TRANSFORM PRECODING --------------------------------------------------------*/

    if (pusch_pdu->transform_precoding == NR_PUSCH_Config__transformPrecoder_enabled){

      // U as specified in section 6.4.1.1.1.2 in 38.211, if sequence hopping and group hopping are disabled
      pusch_pdu->dfts_ofdm.low_papr_group_number = pusch_pdu->pusch_identity % 30;

      // V as specified in section 6.4.1.1.1.2 in 38.211 V = 0 if sequence hopping and group hopping are disabled
1638 1639
      if ((ps->NR_DMRS_UplinkConfig==NULL) || ((ps->NR_DMRS_UplinkConfig->transformPrecodingEnabled->sequenceGroupHopping == NULL) &&
					       (ps->NR_DMRS_UplinkConfig->transformPrecodingEnabled->sequenceHopping == NULL)))
1640 1641 1642 1643 1644 1645 1646 1647 1648
        pusch_pdu->dfts_ofdm.low_papr_sequence_number = 0;
      else
        AssertFatal(1==0,"SequenceGroupHopping or sequenceHopping are NOT Supported\n");

      LOG_D(NR_MAC,"TRANSFORM PRECODING IS ENABLED. CDM groups: %d, U: %d MCS table: %d\n", pusch_pdu->num_dmrs_cdm_grps_no_data, pusch_pdu->dfts_ofdm.low_papr_group_number, ps->mcs_table);
    }

    /*-----------------------------------------------------------------------------*/

1649
    /* PUSCH PTRS */
1650
    if (ps->NR_DMRS_UplinkConfig && ps->NR_DMRS_UplinkConfig->phaseTrackingRS != NULL) {
1651
      bool valid_ptrs_setup = false;
1652
      pusch_pdu->pusch_ptrs.ptrs_ports_list   = (nfapi_nr_ptrs_ports_t *) malloc(2*sizeof(nfapi_nr_ptrs_ports_t));
1653 1654 1655 1656 1657 1658 1659 1660
      valid_ptrs_setup = set_ul_ptrs_values(ps->NR_DMRS_UplinkConfig->phaseTrackingRS->choice.setup,
                                            pusch_pdu->rb_size, pusch_pdu->mcs_index, pusch_pdu->mcs_table,
                                            &pusch_pdu->pusch_ptrs.ptrs_freq_density,&pusch_pdu->pusch_ptrs.ptrs_time_density,
                                            &pusch_pdu->pusch_ptrs.ptrs_ports_list->ptrs_re_offset,&pusch_pdu->pusch_ptrs.num_ptrs_ports,
                                            &pusch_pdu->pusch_ptrs.ul_ptrs_power, pusch_pdu->nr_of_symbols);
      if (valid_ptrs_setup==true) {
        pusch_pdu->pdu_bit_map |= PUSCH_PDU_BITMAP_PUSCH_PTRS; // enable PUSCH PTRS
      }
1661 1662 1663 1664
    }
    else{
      pusch_pdu->pdu_bit_map &= ~PUSCH_PDU_BITMAP_PUSCH_PTRS; // disable PUSCH PTRS
    }
1665

1666 1667
    /* look up the PDCCH PDU for this BWP and CORESET. If it does not exist,
     * create it */
1668
    const int bwpid = sched_ctrl->active_bwp ? sched_ctrl->active_bwp->bwp_Id : 0;
1669 1670
    NR_SearchSpace_t *ss = (sched_ctrl->active_bwp || ubwpd) ? sched_ctrl->search_space: RC.nrmac[module_id]->sched_ctrlCommon->search_space;
    NR_ControlResourceSet_t *coreset = (sched_ctrl->active_bwp || ubwpd) ? sched_ctrl->coreset: RC.nrmac[module_id]->sched_ctrlCommon->coreset;
1671
    const int coresetid = coreset->controlResourceSetId;
1672 1673 1674 1675 1676 1677 1678 1679
    nfapi_nr_dl_tti_pdcch_pdu_rel15_t *pdcch_pdu = pdcch_pdu_bwp_coreset[bwpid][coresetid];
    if (!pdcch_pdu) {
      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 = &ul_dci_request_pdu->pdcch_pdu.pdcch_pdu_rel15;
      ul_dci_req->numPdus += 1;
1680
      nr_configure_pdcch(nr_mac, pdcch_pdu, ss, coreset, scc, genericParameters, NULL);
1681 1682
      pdcch_pdu_bwp_coreset[bwpid][coresetid] = pdcch_pdu;
    }
1683

1684
    LOG_D(NR_MAC,"Configuring ULDCI/PDCCH in %d.%d at CCE %d, rnti %x\n", frame,slot,sched_ctrl->cce_index,rnti);
1685

1686 1687 1688 1689
    /* Fill PDCCH DL DCI PDU */
    nfapi_nr_dl_dci_pdu_t *dci_pdu = &pdcch_pdu->dci_pdu[pdcch_pdu->numDlDci];
    pdcch_pdu->numDlDci++;
    dci_pdu->RNTI = rnti;
1690 1691 1692
    if (coreset->pdcch_DMRS_ScramblingID &&
        ss->searchSpaceType->present == NR_SearchSpace__searchSpaceType_PR_ue_Specific) {
      dci_pdu->ScramblingId = *coreset->pdcch_DMRS_ScramblingID;
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
      dci_pdu->ScramblingRNTI = rnti;
    } else {
      dci_pdu->ScramblingId = *scc->physCellId;
      dci_pdu->ScramblingRNTI = 0;
    }
    dci_pdu->AggregationLevel = sched_ctrl->aggregation_level;
    dci_pdu->CceIndex = sched_ctrl->cce_index;
    dci_pdu->beta_PDCCH_1_0 = 0;
    dci_pdu->powerControlOffsetSS = 1;

    dci_pdu_rel15_t uldci_payload;
    memset(&uldci_payload, 0, sizeof(uldci_payload));
1705
    int n_ubwp=1;
1706 1707
    if (cg->spCellConfig->spCellConfigDedicated->uplinkConfig->uplinkBWP_ToAddModList)
        n_ubwp = cg->spCellConfig->spCellConfigDedicated->uplinkConfig->uplinkBWP_ToAddModList->list.count;
1708

1709
    config_uldci(sched_ctrl->active_ubwp,
Eurecom's avatar
Eurecom committed
1710
                 ubwpd,
1711
                 scc,
1712
                 pusch_pdu,
1713
                 &uldci_payload,
1714
                 ps->dci_format,
1715
                 ps->time_domain_allocation,
1716 1717
                 UE_info->UE_sched_ctrl[UE_id].tpc0,
                 n_ubwp,
1718
                 bwpid);
1719
    fill_dci_pdu_rel15(scc,
1720
                       cg,
1721 1722
                       dci_pdu,
                       &uldci_payload,
1723 1724
                       ps->dci_format,
                       rnti_types[0],
1725
                       pusch_pdu->bwp_size,
1726
                       bwpid);
1727

Robert Schmidt's avatar
Robert Schmidt committed
1728
    memset(sched_pusch, 0, sizeof(*sched_pusch));
1729
  }
1730
}