Skip to content
Snippets Groups Projects
lte-ru.c 123 KiB
Newer Older
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 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 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
  RU_proc_t *proc = (RU_proc_t *)&ru->proc;
  // set default return value
  ru_thread_prach_status = 0;
  thread_top_init("ru_thread_prach_br",1,500000,1000000,20000000);
  //wait_sync("ru_thread_prach_br");

  while (!oai_exit) {
    if (wait_on_condition(&proc->mutex_prach_br,&proc->cond_prach_br,&proc->instance_cnt_prach_br,"ru_prach_thread_br") < 0) break;

    if (oai_exit) break;

    rx_prach(NULL,
             ru,
             NULL,
             NULL,
             NULL,
             NULL,
             proc->frame_prach_br,
             0,
             1);

    if (release_thread(&proc->mutex_prach_br,&proc->instance_cnt_prach_br,"ru_prach_thread_br") < 0) break;
  }

  LOG_I(PHY, "Exiting RU thread PRACH BR\n");
  ru_thread_prach_status = 0;
  return &ru_thread_prach_status;
}


int wakeup_synch(RU_t *ru) {
  int ret;
  struct timespec wait;
  int time_ns = 5000000L;
  // wake up synch thread
  // lock the synch mutex and make sure the thread is readif (pthread_mutex_timedlock(&ru->proc.mutex_synch,&wait) != 0) {
  clock_gettime(CLOCK_REALTIME,&wait);
  wait.tv_nsec += time_ns;

  if(wait.tv_nsec >= 1000*1000*1000) {
    wait.tv_nsec -= 1000*1000*1000;
    wait.tv_sec  += 1;
  }

  AssertFatal((ret=pthread_mutex_timedlock(&ru->proc.mutex_synch,&wait)) == 0,"[RU] ERROR pthread_mutex_lock for RU synch thread (IC %d)\n", ru->proc.instance_cnt_synch );
  ++ru->proc.instance_cnt_synch;

  // the thread can now be woken up
  if (pthread_cond_signal(&ru->proc.cond_synch) != 0) {
    LOG_E( PHY, "[RU] ERROR pthread_cond_signal for RU synch thread\n");
    exit_fun( "ERROR pthread_cond_signal" );
    return(-1);
  }

  AssertFatal((ret=pthread_mutex_unlock( &ru->proc.mutex_synch ))==0,"mutex_unlock returns %d\n",ret);
  return(0);
}


static void do_ru_synch(RU_t *ru) {
  LTE_DL_FRAME_PARMS *fp  = ru->frame_parms;
  RU_proc_t *proc         = &ru->proc;
  int rxs, ic, ret, i;
  void *rxp[2],*rxp2[2];
  int32_t dummy_rx[ru->nb_rx][fp->samples_per_tti] __attribute__((aligned(32)));

  // initialize the synchronization buffer to the common_vars.rxdata
  for (int i=0; i<ru->nb_rx; i++)
    rxp[i] = &ru->common.rxdata[i][0];

  double temp_freq1 = ru->rfdevice.openair0_cfg->rx_freq[0];

  for (i=0; i<4; i++) {
    ru->rfdevice.openair0_cfg->rx_freq[i] = ru->rfdevice.openair0_cfg->tx_freq[i];
    ru->rfdevice.openair0_cfg->tx_freq[i] = temp_freq1;
  }

  ru->rfdevice.trx_set_freq_func(&ru->rfdevice,ru->rfdevice.openair0_cfg);

  while ((ru->in_synch ==0)&&(!oai_exit)) {
    // read in frame
    rxs = ru->rfdevice.trx_read_func(&ru->rfdevice,
                                     &(proc->timestamp_rx),
                                     rxp,
                                     fp->samples_per_tti*10,
                                     ru->nb_rx);

    if (rxs != fp->samples_per_tti*10) LOG_E(PHY,"requested %d samples, got %d\n",fp->samples_per_tti*10,rxs);

    // wakeup synchronization processing thread
    wakeup_synch(ru);
    ic=0;

    while ((ic>=0)&&(!oai_exit)) {
      // continuously read in frames, 1ms at a time,
      // until we are done with the synchronization procedure
      for (i=0; i<ru->nb_rx; i++)
        rxp2[i] = (void *)&dummy_rx[i][0];

      for (i=0; i<10; i++)
        rxs = ru->rfdevice.trx_read_func(&ru->rfdevice,
                                         &(proc->timestamp_rx),
                                         rxp2,
                                         fp->samples_per_tti,
                                         ru->nb_rx);

      AssertFatal((ret=pthread_mutex_lock(&ru->proc.mutex_synch))==0,"mutex_lock returns %d\n",ret);
      ic = ru->proc.instance_cnt_synch;
      AssertFatal((ret=pthread_mutex_unlock(&ru->proc.mutex_synch))==0,"mutex_unlock returns %d\n",ret);
    } // ic>=0
  } // in_synch==0

  // read in rx_offset samples
  LOG_I(PHY,"Resynchronizing by %d samples\n",ru->rx_offset);
  rxs = ru->rfdevice.trx_read_func(&ru->rfdevice,
                                   &(proc->timestamp_rx),
                                   rxp,
                                   ru->rx_offset,
                                   ru->nb_rx);
  // Verification of synchronization procedure
  ru->state = RU_CHECK_SYNC;
  LOG_I(PHY,"Exiting synch routine\n");
}


int check_sync(RU_t *ru, RU_t *ru_master, int subframe) {
  if (labs(ru_master->proc.t[subframe].tv_nsec - ru->proc.t[subframe].tv_nsec) > 500000)
    return 0;

  return 1;
}


void wakeup_L1s(RU_t *ru) {
  PHY_VARS_eNB **eNB_list = ru->eNB_list;
  PHY_VARS_eNB *eNB       = eNB_list[0];
  L1_proc_t *proc         = &eNB->proc;
  struct timespec t;
  LOG_D(PHY, "wakeup_L1s (num %d) for RU %d (%d.%d) ru->eNB_top:%p\n", ru->num_eNB, ru->idx, ru->proc.frame_rx, ru->proc.tti_rx, ru->eNB_top);
  char string[20];
  sprintf(string, "Incoming RU %d", ru->idx);

  // call eNB function directly
  VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_FRAME_NUMBER_WAKEUP_L1S_RU+ru->idx, ru->proc.frame_rx);
  VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_SUBFRAME_NUMBER_WAKEUP_L1S_RU+ru->idx, ru->proc.tti_rx);
  AssertFatal(0==pthread_mutex_lock(&proc->mutex_RU),"");
  VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME(VCD_SIGNAL_DUMPER_FUNCTIONS_LOCK_MUTEX_RU+ru->idx, 1);
  //LOG_I(PHY,"wakeup_L1s: Frame %d, Subframe %d: RU %d done (wait_cnt %d),RU_mask[%d] %x\n",
  //          ru->proc.frame_rx,ru->proc.tti_rx,ru->idx,ru->wait_cnt,ru->proc.tti_rx,proc->RU_mask[ru->proc.tti_rx]);
  //VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_FRAME_NUMBER_WAKEUP_L1S_RU+ru->idx, ru->proc.frame_rx);
  //VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_SUBFRAME_NUMBER_WAKEUP_L1S_RU+ru->idx, ru->proc.tti_rx);
  clock_gettime(CLOCK_MONOTONIC, &ru->proc.t[ru->proc.tti_rx]);

  if (proc->RU_mask[ru->proc.tti_rx] == 0) {
    //clock_gettime(CLOCK_MONOTONIC,&proc->t[ru->proc.tti_rx]);
    proc->t[ru->proc.tti_rx] = ru->proc.t[ru->proc.tti_rx];
    //start_meas(&proc->ru_arrival_time);
    LOG_D(PHY,"RU %d starting timer for frame %d subframe %d\n", ru->idx, ru->proc.frame_rx, ru->proc.tti_rx);
  }

  for (int i=0; i<eNB->num_RU; i++) {
    if (eNB->RU_list[i]->wait_cnt==1 && ru->proc.tti_rx!=9) eNB->RU_list[i]->wait_cnt=0;

    LOG_D(PHY,"RU %d has frame %d and subframe %d, state %s\n",
          eNB->RU_list[i]->idx, eNB->RU_list[i]->proc.frame_rx, eNB->RU_list[i]->proc.tti_rx, ru_states[eNB->RU_list[i]->state]);

    if (ru == eNB->RU_list[i] && eNB->RU_list[i]->wait_cnt == 0) {
      //AssertFatal((proc->RU_mask&(1<<i)) == 0, "eNB %d frame %d, subframe %d : previous information from RU %d (num_RU %d,mask %x) has not been served yet!\n", eNB->Mod_id,ru->proc.frame_rx,ru->proc.tti_rx,ru->idx,eNB->num_RU,proc->RU_mask);
      proc->RU_mask[ru->proc.tti_rx] |= (1<<i);
    } else if (eNB->RU_list[i]->state == RU_SYNC ||(eNB->RU_list[i]->is_slave==1 && eNB->RU_list[i]->wait_cnt>0 && ru!=eNB->RU_list[i] /*&& ru->is_slave==0*/) ) {
      proc->RU_mask[ru->proc.tti_rx] |= (1<<i);
    }

    //LOG_I(PHY,"RU %d, RU_mask[%d] %d, i %d, frame %d, slave %d, ru->cnt %d, i->cnt %d\n",ru->idx,ru->proc.tti_rx,proc->RU_mask[ru->proc.tti_rx],i,ru->proc.frame_rx,ru->is_slave,ru->wait_cnt,eNB->RU_list[i]->wait_cnt);
    VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_MASK_RU, proc->RU_mask[ru->proc.tti_rx]);

    if (ru->is_slave == 0 && ( (proc->RU_mask[ru->proc.tti_rx]&(1<<i)) == 1 ) && eNB->RU_list[i]->state == RU_RUN) { //This is master & the RRU has already been received
      if (check_sync(eNB->RU_list[i],eNB->RU_list[0],ru->proc.tti_rx) == 0)
        LOG_E(PHY,"RU %d is not SYNC, subframe %d, time  %ld this is master\n",
              eNB->RU_list[i]->idx, ru->proc.tti_rx, labs(eNB->RU_list[i]->proc.t[ru->proc.tti_rx].tv_nsec - eNB->RU_list[0]->proc.t[ru->proc.tti_rx].tv_nsec));
    } else if (ru->is_slave == 1 && ru->state == RU_RUN && ( (proc->RU_mask[ru->proc.tti_rx]&(1<<0)) == 1)) { // master already received. TODO: we assume that RU0 is master.
      if (check_sync(ru,eNB->RU_list[0],ru->proc.tti_rx) == 0)
        LOG_E(PHY,"RU %d is not SYNC time, subframe %d, time  %ld\n",
              ru->idx, ru->proc.tti_rx, labs(ru->proc.t[ru->proc.tti_rx].tv_nsec - eNB->RU_list[0]->proc.t[ru->proc.tti_rx].tv_nsec));
    }
  }

  //clock_gettime(CLOCK_MONOTONIC,&t);
  //LOG_I(PHY,"RU mask is now %x, time is %lu\n",proc->RU_mask[ru->proc.tti_rx], t.tv_nsec - proc->t[ru->proc.tti_rx].tv_nsec);

  if (proc->RU_mask[ru->proc.tti_rx] == (1<<eNB->num_RU)-1) { // all RUs have provided their information so continue on and wakeup eNB top
    LOG_D(PHY,"ru_mask is %d \n ", proc->RU_mask[ru->proc.tti_rx]);
    LOG_D(PHY,"the number of RU is %d, the current ru is RU %d \n ", (1<<eNB->num_RU)-1, ru->idx);
    LOG_D(PHY,"ru->proc.tti_rx is %d \n", ru->proc.tti_rx);
    LOG_D(PHY,"Resetting mask frame %d, subframe %d, this is RU %d\n", ru->proc.frame_rx, ru->proc.tti_rx, ru->idx);
    proc->RU_mask[ru->proc.tti_rx] = 0;
    VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_MASK_RU, proc->RU_mask[ru->proc.tti_rx]);
    clock_gettime(CLOCK_MONOTONIC,&t);
    //stop_meas(&proc->ru_arrival_time);
    /*AssertFatal(t.tv_nsec < proc->t[ru->proc.tti_rx].tv_nsec+5000000, "Time difference for subframe %d (Frame %d) => %lu > 5ms, this is RU %d\n",
                  ru->proc.tti_rx, ru->proc.frame_rx, t.tv_nsec - proc->t[ru->proc.tti_rx].tv_nsec, ru->idx);*/
    //VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_FRAME_NUMBER_WAKEUP_L1S_RU+ru->idx, ru->proc.frame_rx);
    //VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_SUBFRAME_NUMBER_WAKEUP_L1S_RU+ru->idx, ru->proc.tti_rx);
    AssertFatal(0==pthread_mutex_unlock(&proc->mutex_RU),"");
    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_LOCK_MUTEX_RU+ru->idx, 0 );
    // unlock RUs that are waiting for eNB processing to be completed
    LOG_D(PHY,"RU %d wakeup eNB top for subframe %d\n", ru->idx, ru->proc.tti_rx);

    if (ru->wait_cnt == 0) {
      if (ru->num_eNB==1 && ru->eNB_top!=0 && get_thread_parallel_conf() == PARALLEL_SINGLE_THREAD) {
        LOG_D(PHY,"RU %d Call eNB_top\n", ru->idx);
        ru->eNB_top(eNB_list[0], proc->frame_rx, proc->subframe_rx, string, ru);
      } else {
        for (int i=0; i<ru->num_eNB; i++) {
          LOG_D(PHY,"ru->wakeup_rxtx:%p\n", ru->wakeup_rxtx);
          eNB_list[i]->proc.ru_proc = &ru->proc;

          if (ru->wakeup_rxtx!=0 && ru->wakeup_rxtx(eNB_list[i],ru) < 0) LOG_E(PHY,"could not wakeup eNB rxtx process for subframe %d\n", ru->proc.tti_rx);
        }
      }
    }

    /*
      AssertFatal(0==pthread_mutex_lock(&ruproc->mutex_eNBs),"");
      LOG_D(PHY,"RU %d sending signal to unlock waiting ru_threads\n", ru->idx);
      AssertFatal(0==pthread_cond_broadcast(&ruproc->cond_eNBs),"");
      if (ruproc->instance_cnt_eNBs==-1) ruproc->instance_cnt_eNBs++;
      AssertFatal(0==pthread_mutex_unlock(&ruproc->mutex_eNBs),"");
    */
  } else { // not all RUs have provided their information
    AssertFatal(0==pthread_mutex_unlock(&proc->mutex_RU),"");
    VCD_SIGNAL_DUMPER_DUMP_FUNCTION_BY_NAME( VCD_SIGNAL_DUMPER_FUNCTIONS_LOCK_MUTEX_RU+ru->idx, 0 );
  }

  //      pthread_mutex_unlock(&proc->mutex_RU);
  //      LOG_D(PHY,"wakeup eNB top for for subframe %d\n", ru->proc.tti_rx);
  //      ru->eNB_top(eNB_list[0],ru->proc.frame_rx,ru->proc.tti_rx,string);
  ru->proc.emulate_rf_busy = 0;
}


void wakeup_prach_ru(RU_t *ru) {
  struct timespec wait;
  int time_ns = 5000000L, ret;
  clock_gettime(CLOCK_REALTIME,&wait);
  wait.tv_nsec += time_ns;

  if(wait.tv_nsec >= 1000*1000*1000) {
    wait.tv_nsec -= 1000*1000*1000;
    wait.tv_sec  += 1;
  }

  AssertFatal((ret=pthread_mutex_timedlock(&ru->proc.mutex_prach,&wait)) == 0,"[RU] ERROR pthread_mutex_lock for RU prach thread (IC %d)\n", ru->proc.instance_cnt_prach);

  if (ru->proc.instance_cnt_prach==-1) {
    ++ru->proc.instance_cnt_prach;
    ru->proc.frame_prach    = ru->proc.frame_rx;
    ru->proc.subframe_prach = ru->proc.tti_rx;

    // DJP - think prach_procedures() is looking at eNB frame_prach
    if (ru->eNB_list[0]) {
      ru->eNB_list[0]->proc.frame_prach = ru->proc.frame_rx;
      ru->eNB_list[0]->proc.subframe_prach = ru->proc.tti_rx;
    }

    LOG_D(PHY,"RU %d: waking up PRACH thread\n",ru->idx);
    // the thread can now be woken up
    AssertFatal(pthread_cond_signal(&ru->proc.cond_prach) == 0, "ERROR pthread_cond_signal for RU prach thread\n");
  } else LOG_W(PHY,"RU prach thread busy, skipping\n");

  AssertFatal((ret=pthread_mutex_unlock( &ru->proc.mutex_prach ))==0,"mutex_unlock returns %d\n",ret);
}


void wakeup_prach_ru_br(RU_t *ru) {
  struct timespec wait;
  int time_ns = 5000000L, ret;
  clock_gettime(CLOCK_REALTIME,&wait);
  wait.tv_nsec += time_ns;

  if(wait.tv_nsec >= 1000*1000*1000) {
    wait.tv_nsec -= 1000*1000*1000;
    wait.tv_sec  += 1;
  }

  AssertFatal((ret=pthread_mutex_timedlock(&ru->proc.mutex_prach_br,&wait))==0,"[RU] ERROR pthread_mutex_lock for RU prach thread BR (IC %d)\n", ru->proc.instance_cnt_prach_br);

  if (ru->proc.instance_cnt_prach_br==-1) {
    ++ru->proc.instance_cnt_prach_br;
    ru->proc.frame_prach_br    = ru->proc.frame_rx;
    ru->proc.subframe_prach_br = ru->proc.tti_rx;
    LOG_D(PHY,"RU %d: waking up PRACH thread\n",ru->idx);
    // the thread can now be woken up
    AssertFatal(pthread_cond_signal(&ru->proc.cond_prach_br) == 0, "ERROR pthread_cond_signal for RU prach thread BR\n");
  } else LOG_W(PHY,"RU prach thread busy, skipping\n");

  AssertFatal((ret=pthread_mutex_unlock( &ru->proc.mutex_prach_br ))==0,"mutex_unlock returns %d\n",ret);
}


// this is for RU with local RF unit
void fill_rf_config(RU_t *ru,
                    char *rf_config_file) {
  LTE_DL_FRAME_PARMS *fp   = ru->frame_parms;
  openair0_config_t *cfg   = &ru->openair0_cfg;
  //LOG_I(PHY,"////////////////numerology in config = %d\n",numerology);
  int numerology = get_softmodem_params()->numerology;

  if(fp->N_RB_DL == 100) {
    if(ru->numerology == 0) {
      if (fp->threequarter_fs) {
        cfg->sample_rate=23.04e6;
        cfg->samples_per_frame = 230400;
        cfg->tx_bw = 20e6;
        cfg->rx_bw = 20e6;
      } else {
        cfg->sample_rate=30.72e6;
        cfg->samples_per_frame = 307200;
        cfg->tx_bw = 20e6;
        cfg->rx_bw = 20e6;
      }
    } else if(ru->numerology == 1) {
      cfg->sample_rate=61.44e6;
      cfg->samples_per_frame = 307200;
      cfg->tx_bw = 20e6;
      cfg->rx_bw = 20e6;
    } else if(ru->numerology == 2) {
      cfg->sample_rate=122.88e6;
      cfg->samples_per_frame = 307200;
      cfg->tx_bw = 40e6;
      cfg->rx_bw = 40e6;
    } else {
      LOG_I(PHY,"Wrong input for numerology %d\n setting to 20MHz normal CP configuration",numerology);
      cfg->sample_rate=30.72e6;
      cfg->samples_per_frame = 307200;
      cfg->tx_bw = 10e6;
      cfg->rx_bw = 10e6;
    }
  } else if(fp->N_RB_DL == 50) {
    cfg->sample_rate=15.36e6;
    cfg->samples_per_frame = 153600;
    cfg->tx_bw = 10e6;
    cfg->rx_bw = 10e6;
  } else if (fp->N_RB_DL == 25) {
    cfg->sample_rate=7.68e6;
    cfg->samples_per_frame = 76800;
    cfg->tx_bw = 5e6;
    cfg->rx_bw = 5e6;
  } else if (fp->N_RB_DL == 6) {
    cfg->sample_rate=1.92e6;
    cfg->samples_per_frame = 19200;
    cfg->tx_bw = 1.5e6;
    cfg->rx_bw = 1.5e6;
  } else AssertFatal(1==0,"Unknown N_RB_DL %d\n",fp->N_RB_DL);

  if (fp->frame_type==TDD)
    cfg->duplex_mode = duplex_mode_TDD;
  else //FDD
    cfg->duplex_mode = duplex_mode_FDD;

  cfg->Mod_id = 0;
  cfg->num_rb_dl=fp->N_RB_DL;
  cfg->tx_num_channels=ru->nb_tx;
  cfg->rx_num_channels=ru->nb_rx;

  for (int i=0; i<ru->nb_tx; i++) {
    cfg->tx_freq[i] = (double)fp->dl_CarrierFreq;
    cfg->rx_freq[i] = (double)fp->ul_CarrierFreq;
    cfg->tx_gain[i] = (double)ru->att_tx;
    cfg->rx_gain[i] = ru->max_rxgain-(double)ru->att_rx;
    cfg->configFilename = rf_config_file;
    LOG_I(PHY,"channel %d, Setting tx_gain offset %.0f, rx_gain offset %.0f, tx_freq %.0f, rx_freq %.0f, tune_offset %.0f Hz\n",
           i, cfg->tx_gain[i],
           cfg->rx_gain[i],
           cfg->tx_freq[i],
           cfg->rx_freq[i],
           cfg->tune_offset);
  }
}


/* this function maps the RU tx and rx buffers to the available rf chains.
   Each rf chain is is addressed by the card number and the chain on the card. The
   rf_map specifies for each antenna port, on which rf chain the mapping should start. Multiple
   antennas are mapped to successive RF chains on the same card. */
int setup_RU_buffers(RU_t *ru) {
  int i,j;
  int card,ant;
  //uint16_t N_TA_offset = 0;
  LTE_DL_FRAME_PARMS *frame_parms;

  if (ru) {
    frame_parms = ru->frame_parms;
    LOG_I(PHY,"setup_RU_buffers: frame_parms = %p\n",frame_parms);
  } else {
    LOG_I(PHY,"RU not initialized (NULL pointer)\n");
    return(-1);
  }

  if (frame_parms->frame_type == TDD) {
    if      (frame_parms->N_RB_DL == 100) ru->N_TA_offset = 624;
    else if (frame_parms->N_RB_DL == 50)  ru->N_TA_offset = 624/2;
    else if (frame_parms->N_RB_DL == 25)  ru->N_TA_offset = 624/4;

    if      (frame_parms->N_RB_DL == 100) /* no scaling to do */;
    else if (frame_parms->N_RB_DL == 50) {
      ru->sf_extension       /= 2;
      ru->end_of_burst_delay /= 2;
    } else if (frame_parms->N_RB_DL == 25) {
      ru->sf_extension       /= 4;
      ru->end_of_burst_delay /= 4;
    } else {
      LOG_I(PHY,"not handled, todo\n");
      exit(1);
    }
  } else {
    ru->N_TA_offset = 0;
    ru->sf_extension = 0;
    ru->end_of_burst_delay = 0;
  }

  if (ru->openair0_cfg.mmapped_dma == 1) {
    // replace RX signal buffers with mmaped HW versions
    for (i=0; i<ru->nb_rx; i++) {
      card = i/4;
      ant = i%4;
      LOG_I(PHY,"Mapping RU id %d, rx_ant %d, on card %d, chain %d\n",ru->idx,i,ru->rf_map.card+card, ru->rf_map.chain+ant);
      free(ru->common.rxdata[i]);
      ru->common.rxdata[i] = ru->openair0_cfg.rxbase[ru->rf_map.chain+ant];
      LOG_I(PHY,"rxdata[%d] @ %p\n",i,ru->common.rxdata[i]);

      for (j=0; j<16; j++) {
        LOG_I(PHY,"rxbuffer %d: %x\n",j,ru->common.rxdata[i][j]);
        ru->common.rxdata[i][j] = 16-j;
      }
    }

    for (i=0; i<ru->nb_tx; i++) {
      card = i/4;
      ant = i%4;
      LOG_I(PHY,"Mapping RU id %d, tx_ant %d, on card %d, chain %d\n",ru->idx,i,ru->rf_map.card+card, ru->rf_map.chain+ant);
      free(ru->common.txdata[i]);
      ru->common.txdata[i] = ru->openair0_cfg.txbase[ru->rf_map.chain+ant];
      LOG_I(PHY,"txdata[%d] @ %p\n",i,ru->common.txdata[i]);

      for (j=0; j<16; j++) {
        LOG_I(PHY,"txbuffer %d: %x\n",j,ru->common.txdata[i][j]);
        ru->common.txdata[i][j] = 16-j;
      }
    }
  } else { // not memory-mapped DMA
    //nothing to do, everything already allocated in lte_init
  }

  return(0);
}


static void *ru_stats_thread(void *param) {
  RU_t *ru = (RU_t *)param;
  wait_sync("ru_stats_thread");

  while (!oai_exit) {
    sleep(1);

    if (opp_enabled) {
      if (ru->feprx) print_meas(&ru->ofdm_demod_stats,"feprx_ru",NULL,NULL);

      if (ru->feptx_ofdm) print_meas(&ru->ofdm_mod_stats,"feptx_ofdm_ru",NULL,NULL);

      if (ru->fh_north_asynch_in) print_meas(&ru->rx_fhaul,"rx_fhaul_ru",NULL,NULL);

      if (ru->fh_north_out) {
        print_meas(&ru->tx_fhaul,"tx_fhaul",NULL,NULL);
        print_meas(&ru->compression,"compression",NULL,NULL);
        print_meas(&ru->transport,"transport",NULL,NULL);
        LOG_I(PHY,"ru->north_out_cnt = %d\n",ru->north_out_cnt);
      }

      if (ru->fh_south_out) LOG_I(PHY,"ru->south_out_cnt = %d\n",ru->south_out_cnt);

      if (ru->fh_north_asynch_in) LOG_I(PHY,"ru->north_in_cnt = %d\n",ru->north_in_cnt);
    }
  }

  return(NULL);
}

#ifdef PHY_TX_THREAD
  int first_phy_tx = 1;
  volatile int16_t phy_tx_txdataF_end;
  volatile int16_t phy_tx_end;
#endif


static void *ru_thread_tx( void *param ) {
  RU_t *ru         = (RU_t *)param;
  RU_proc_t *proc  = &ru->proc;
  __attribute__((unused))
  LTE_DL_FRAME_PARMS *fp = ru->frame_parms;
  PHY_VARS_eNB *eNB;
  L1_proc_t *eNB_proc;
  L1_rxtx_proc_t *L1_proc;
  cpu_set_t cpuset;
  CPU_ZERO(&cpuset);
  char filename[256];
  thread_top_init("ru_thread_tx",1,400000,500000,500000);
  //CPU_SET(5, &cpuset);
  //pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
  //wait_sync("ru_thread_tx");
  wait_on_condition(&proc->mutex_FH1,&proc->cond_FH1,&proc->instance_cnt_FH1,"ru_thread_tx");
  int ret;

  while (!oai_exit) {
    VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_CPUID_RU_THREAD_TX,sched_getcpu());

    if (oai_exit) break;

    LOG_D(PHY,"ru_thread_tx (ru %d): Waiting for TX processing\n",ru->idx);
    // wait until eNBs are finished subframe RX n and TX n+4
    wait_on_condition(&proc->mutex_eNBs,&proc->cond_eNBs,&proc->instance_cnt_eNBs,"ru_thread_tx");
    ret = pthread_mutex_lock(&proc->mutex_eNBs);
    AssertFatal(ret == 0,"mutex_lock return %d\n",ret);
    int frame_tx=proc->frame_tx;
    int tti_tx  =proc->tti_tx;
    uint64_t timestamp_tx = proc->timestamp_tx;
    ret = pthread_mutex_unlock(&proc->mutex_eNBs);
    AssertFatal(ret == 0,"mutex_lock returns %d\n",ret);


    if (oai_exit) break;

    // do TX front-end processing if needed (precoding and/or IDFTs)
    if (ru->feptx_prec) ru->feptx_prec(ru,frame_tx,tti_tx);

    // do OFDM if needed
    if ((ru->fh_north_asynch_in == NULL) && (ru->feptx_ofdm)) ru->feptx_ofdm(ru,frame_tx,tti_tx);

    if(!(ru->emulate_rf)) { //if(!emulate_rf){
      // do outgoing fronthaul (south) if needed
      if ((ru->fh_north_asynch_in == NULL) && (ru->fh_south_out)) ru->fh_south_out(ru,frame_tx,tti_tx,timestamp_tx);

      if (ru->fh_north_out) ru->fh_north_out(ru);
    } else {
      for (int i=0; i<ru->nb_tx; i++) {
        if(frame_tx == 2) {
          sprintf(filename,"txdataF%d_frame%d_sf%d.m",i,frame_tx,tti_tx);
          LOG_M(filename,"txdataF_frame",ru->common.txdataF_BF[i],fp->symbols_per_tti*fp->ofdm_symbol_size, 1, 1);
        }

        if(frame_tx == 2 && tti_tx==0) {
          sprintf(filename,"txdata%d_frame%d.m",i,frame_tx);
          LOG_M(filename,"txdata_frame",ru->common.txdata[i],fp->samples_per_tti*10, 1, 1);
        }
      }
    }

    LOG_D(PHY,"ru_thread_tx: releasing RU TX in %d.%d\n", frame_tx, tti_tx);
    release_thread(&proc->mutex_eNBs,&proc->instance_cnt_eNBs,"ru_thread_tx");

    for(int i = 0; i<ru->num_eNB; i++) {
      eNB       = ru->eNB_list[i];
      eNB_proc  = &eNB->proc;
      L1_proc   = (get_thread_parallel_conf() == PARALLEL_RU_L1_TRX_SPLIT)? &eNB_proc->L1_proc_tx : &eNB_proc->L1_proc;
      AssertFatal((ret=pthread_mutex_lock(&eNB_proc->mutex_RU_tx))==0,"mutex_lock returns %d\n",ret);

      for (int j=0; j<eNB->num_RU; j++) {
        if (ru == eNB->RU_list[j]) {
          if ((eNB_proc->RU_mask_tx&(1<<j)) > 0)
            LOG_E(PHY,"eNB %d frame %d, subframe %d : previous information from RU tx %d (num_RU %d,mask %x) has not been served yet!\n",
                  eNB->Mod_id,eNB_proc->frame_rx,eNB_proc->subframe_rx,ru->idx,eNB->num_RU,eNB_proc->RU_mask_tx);

          eNB_proc->RU_mask_tx |= (1<<j);
        } else if (eNB->RU_list[j]->state==RU_SYNC ||(eNB->RU_list[j]->is_slave==1 && eNB->RU_list[j]->wait_cnt>0 && ru!=eNB->RU_list[j])) {
          eNB_proc->RU_mask_tx |= (1<<j);
        }

        VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_MASK_TX_RU, eNB_proc->RU_mask_tx);
      }

      if (eNB_proc->RU_mask_tx != (1<<eNB->num_RU)-1) {  // not all RUs have provided their information so return
        //LOG_I(PHY,"Not all RUs have provided their info (mask = %d), RU %d, num_RUs %d\n", eNB_proc->RU_mask_tx,ru->idx,eNB->num_RU);
        AssertFatal((ret=pthread_mutex_unlock(&eNB_proc->mutex_RU_tx))==0,"mutex_unlock returns %d\n",ret);
      } else { // all RUs TX are finished so send the ready signal to eNB processing
        eNB_proc->RU_mask_tx = 0;
        VCD_SIGNAL_DUMPER_DUMP_VARIABLE_BY_NAME(VCD_SIGNAL_DUMPER_VARIABLES_MASK_TX_RU, eNB_proc->RU_mask_tx);
        AssertFatal((ret=pthread_mutex_unlock(&eNB_proc->mutex_RU_tx))==0,"mutex_unlock returns %d\n",ret);
        AssertFatal((ret=pthread_mutex_lock( &L1_proc->mutex_RUs))==0,"mutex_lock returns %d\n",ret);
        L1_proc->instance_cnt_RUs = 0;
        LOG_D(PHY,"ru_thread_tx: Signaling RU TX done in %d.%d\n", frame_tx, tti_tx);
        // the thread can now be woken up
        LOG_D(PHY,"ru_thread_tx: clearing mask and Waking up L1 thread\n");

        if (pthread_cond_signal(&L1_proc->cond_RUs) != 0) {
          LOG_E( PHY, "[eNB] ERROR pthread_cond_signal for eNB TXnp4 thread\n");
          exit_fun( "ERROR pthread_cond_signal" );
        }

        AssertFatal((ret=pthread_mutex_unlock( &L1_proc->mutex_RUs))==0,"mutex_unlock returns %d\n",ret);
      }
    }

    //LOG_I(PHY,"ru_thread_tx: Frame %d, Subframe %d: RU %d done (wait_cnt %d),RU_mask_tx %d\n",
    //eNB_proc->frame_rx,eNB_proc->subframe_rx,ru->idx,ru->wait_cnt,eNB_proc->RU_mask_tx);
  }

  release_thread(&proc->mutex_FH1,&proc->instance_cnt_FH1,"ru_thread_tx");
  return 0;
}


static void *ru_thread( void *param ) {
  RU_t *ru         = (RU_t *)param;
  RU_proc_t *proc  = &ru->proc;
  int subframe = 9;
  int frame = 1023;
  int resynch_done = 0;
  int ret;
  cpu_set_t cpuset;
  CPU_ZERO(&cpuset);
  char filename[256];
  // set default return value
#if defined(PRE_SCD_THREAD)
  dlsch_ue_select_tbl_in_use = 1;
#endif
  // set default return value
  thread_top_init("ru_thread",1,400000,500000,500000);
  //CPU_SET(1, &cpuset);
  //pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
  pthread_setname_np( pthread_self(),"ru thread");
  LOG_I(PHY,"thread ru created id=%ld\n", syscall(__NR_gettid));
  LOG_I(PHY,"Starting RU %d (%s,%s),\n", ru->idx, NB_functions[ru->function], NB_timing[ru->if_timing]);

  if(get_softmodem_params()->emulate_rf) {
    phy_init_RU(ru);

    if (setup_RU_buffers(ru)!=0) {
      LOG_I(PHY,"Exiting, cannot initialize RU Buffers\n");
      exit(-1);
    }

    LOG_I(PHY, "Signaling main thread that RU %d is ready\n",ru->idx);
    AssertFatal((ret=pthread_mutex_lock(ru->ru_mutex))==0,"mutex_lock returns %d\n",ret);
    *ru->ru_mask &= ~(1<<ru->idx);
    pthread_cond_signal(ru->ru_cond);
    AssertFatal((ret=pthread_mutex_unlock(ru->ru_mutex))==0,"mutex_unlock returns %d\n",ret);
    ru->state = RU_RUN;
  } else if (ru->has_ctrl_prt == 0) {
    // There is no control port: start everything here
    LOG_I(PHY, "RU %d has no OAI ctrl port\n",ru->idx);

    fill_rf_config(ru,ru->rf_config_file);
    init_frame_parms(ru->frame_parms,1);
    ru->frame_parms->nb_antennas_rx = ru->nb_rx;

    if (ru->if_south == LOCAL_RF)       openair0_device_load(&ru->rfdevice,&ru->openair0_cfg);

    phy_init_RU(ru);
      
      
    if (setup_RU_buffers(ru)!=0) {
        LOG_I(PHY,"Exiting, cannot initialize RU Buffers\n");
	      exit(-1);
    }

    AssertFatal((ret=pthread_mutex_lock(ru->ru_mutex))==0,"mutex_lock returns %d\n",ret);
    *ru->ru_mask &= ~(1<<ru->idx);
    pthread_cond_signal(ru->ru_cond);
    AssertFatal((ret=pthread_mutex_unlock(ru->ru_mutex))==0,"mutex_unlock returns %d\n",ret);
    ru->state = RU_RUN;
  }

  AssertFatal((ret=pthread_mutex_lock(&proc->mutex_FH1))==0,"mutex_lock returns %d\n",ret);
  proc->instance_cnt_FH1 = 0;
  pthread_cond_signal(&proc->cond_FH1);
  AssertFatal((ret=pthread_mutex_unlock(&proc->mutex_FH1))==0,"mutex_unlock returns %d\n",ret);

  if(usrp_tx_thread == 1){
     if (ru->start_write_thread){
        if(ru->start_write_thread(ru) != 0){
            LOG_E(HW,"Could not start tx write thread\n");
        }
        else{
            LOG_I(PHY,"tx write thread ready\n");
        }
     }
  }

  while (!oai_exit) {
    if (ru->if_south != LOCAL_RF && ru->is_slave==1) {
      ru->wait_cnt = 100;
    } else {
      ru->wait_cnt = 0;
      ru->wait_check = 0;
    }

    // wait to be woken up
    if (ru->function!=eNodeB_3GPP && ru->has_ctrl_prt == 1) {
      LOG_D(PHY,"RU %d: Waiting for control thread to say go\n",ru->idx);
      if (wait_on_condition(&ru->proc.mutex_ru,&ru->proc.cond_ru_thread,&ru->proc.instance_cnt_ru,"ru_thread")<0) break;
    } else wait_sync("ru_thread"); 
    LOG_D(PHY,"RU %d: Got start from control thread\n",ru->idx);

    if(!(ru->emulate_rf)) {
      if (ru->is_slave == 0) AssertFatal(ru->state == RU_RUN,"ru-%d state = %s != RU_RUN\n",ru->idx,ru_states[ru->state]);
      else if (ru->is_slave == 1) AssertFatal(ru->state == RU_SYNC || ru->state == RU_RUN ||
                                                ru->state == RU_CHECK_SYNC,"ru %d state = %s != RU_SYNC or RU_RUN or RU_CHECK_SYNC\n",ru->idx,ru_states[ru->state]);

      // Start RF device if any
      if (ru->start_rf) {
	if (ru->start_rf(ru) != 0)
	  AssertFatal(1==0,"Could not start the RF device\n");
	else LOG_I(PHY,"RU %d rf device ready\n",ru->idx);
      } else LOG_D(PHY,"RU %d no rf device\n",ru->idx);
    }

    // if an asnych_rxtx thread exists
    // wakeup the thread because the devices are ready at this point

    if ((ru->fh_south_asynch_in)||(ru->fh_north_asynch_in)) {
      AssertFatal((ret=pthread_mutex_lock(&proc->mutex_asynch_rxtx))==0,"mutex_lock returns %d\n",ret);
      proc->instance_cnt_asynch_rxtx=0;
      pthread_cond_signal(&proc->cond_asynch_rxtx);
      AssertFatal((ret=pthread_mutex_unlock(&proc->mutex_asynch_rxtx))==0,"mutex_unlock returns %d\n",ret);
    } else LOG_D(PHY,"RU %d no asynch_south interface\n",ru->idx);

    // if this is a slave RRU, try to synchronize on the DL frequency
    if ((ru->is_slave == 1) && (ru->if_south == LOCAL_RF)) do_ru_synch(ru);

    if (ru->state == RU_RUN || ru->state == RU_CHECK_SYNC) LOG_I(PHY,"RU %d Starting steady-state operation\n",ru->idx);

    // This is a forever while loop, it loops over subframes which are scheduled by incoming samples from HW devices
    while (ru->state == RU_RUN || ru->state == RU_CHECK_SYNC) {
      // these are local subframe/frame counters to check that we are in synch with the fronthaul timing.
      // They are set on the first rx/tx in the underly FH routines.
      if (subframe==9) {
        subframe=0;
        frame++;
        frame&=1023;
      } else {
        subframe++;
      }

      // synchronization on input FH interface, acquire signals/data and block
      if (ru->fh_south_in) ru->fh_south_in(ru,&frame,&subframe);
      else AssertFatal(1==0, "No fronthaul interface at south port");
#ifdef PHY_TX_THREAD

      if(first_phy_tx == 0) {
        phy_tx_end = 0;
        phy_tx_txdataF_end = 0;
        AssertFatal((ret=pthread_mutex_lock(&ru->proc.mutex_phy_tx))==0,"[RU] ERROR pthread_mutex_lock for phy tx thread (IC %d)\n", ru->proc.instance_cnt_phy_tx);

        if (ru->proc.instance_cnt_phy_tx==-1) {
          ++ru->proc.instance_cnt_phy_tx;
          // the thread can now be woken up
          AssertFatal(pthread_cond_signal(&ru->proc.cond_phy_tx) == 0, "ERROR pthread_cond_signal for phy_tx thread\n");
        } else {
          LOG_E(PHY,"phy tx thread busy, skipping\n");
          ++ru->proc.instance_cnt_phy_tx;
        }

        AssertFatal((ret=pthread_mutex_unlock( &ru->proc.mutex_phy_tx ))==0,"mutex_unlock returns %d\n",ret);
      } else {
        phy_tx_end = 1;
        phy_tx_txdataF_end = 1;
      }

      first_phy_tx = 0;
#endif

      if (ru->stop_rf && ru->cmd == STOP_RU) {
        ru->stop_rf(ru);
        ru->state = RU_IDLE;
        ru->cmd   = EMPTY;
        LOG_I(PHY,"RU %d rf device stopped\n",ru->idx);
        break;
      } else if (ru->cmd == STOP_RU) {
        ru->state = RU_IDLE;
        ru->cmd   = EMPTY;
        LOG_I(PHY,"RU %d stopped\n",ru->idx);
        break;
      }

      if (oai_exit == 1) break;

      if (ru->wait_cnt > 0) {
        ru->wait_cnt--;
        LOG_D(PHY,"RU thread %d, frame %d, subframe %d, wait_cnt %d \n",ru->idx, frame, subframe, ru->wait_cnt);

        if (ru->if_south!=LOCAL_RF && ru->wait_cnt <=20 && subframe == 5 && frame != ru->ru0->proc.frame_rx && resynch_done == 0) {
          // Send RRU_frame adjust
          RRU_CONFIG_msg_t rru_config_msg;
          rru_config_msg.type = RRU_frame_resynch;
          rru_config_msg.len  = sizeof(RRU_CONFIG_msg_t); // TODO: set to correct msg len
          ((uint16_t *)&rru_config_msg.msg[0])[0] = ru->ru0->proc.frame_rx;
          ru->cmd=WAIT_RESYNCH;
          LOG_I(PHY,"Sending Frame Resynch %d to RRU %d\n", ru->ru0->proc.frame_rx,ru->idx);
          AssertFatal((ru->ifdevice.trx_ctlsend_func(&ru->ifdevice,&rru_config_msg,rru_config_msg.len)!=-1),"Failed to send msg to RAU\n");
          resynch_done=1;
        }

        wakeup_L1s(ru);
      } else {
        LOG_D(PHY,"RU thread %d, frame %d, subframe %d (do_prach %d, is_prach_subframe %d)\n",
              ru->idx, frame, subframe, ru->do_prach, is_prach_subframe(ru->frame_parms, proc->frame_rx, proc->tti_rx));

        if ((ru->do_prach>0) && (is_prach_subframe(ru->frame_parms, proc->frame_rx, proc->tti_rx)==1)) {
          LOG_D(PHY,"Waking up prach for %d.%d\n", proc->frame_rx, proc->tti_rx);
          wakeup_prach_ru(ru);
        } else if ((ru->do_prach>0) && (is_prach_subframe(ru->frame_parms, proc->frame_rx, proc->tti_rx)>1)) {
          wakeup_prach_ru_br(ru);
        }

        // adjust for timing offset between RU
        if (ru->idx!=0) proc->frame_tx = (proc->frame_tx+proc->frame_offset)&1023;

        // At this point, all information for subframe has been received on FH interface
        // If this proc is to provide synchronization, do so
        wakeup_slaves(proc);

        // do RX front-end processing (frequency-shift, dft) if needed
        if (ru->feprx) ru->feprx(ru, proc->tti_rx);

        // wakeup all eNB processes waiting for this RU
        AssertFatal((ret=pthread_mutex_lock(&proc->mutex_eNBs))==0,"mutex_lock returns %d\n",ret);

        if (proc->instance_cnt_eNBs==0) proc->instance_cnt_eNBs--;

        AssertFatal((ret=pthread_mutex_unlock(&proc->mutex_eNBs))==0,"mutex_unlock returns %d\n",ret);
#if defined(PRE_SCD_THREAD)
        new_dlsch_ue_select_tbl_in_use = dlsch_ue_select_tbl_in_use;
        dlsch_ue_select_tbl_in_use = !dlsch_ue_select_tbl_in_use;
        memcpy(&pre_scd_eNB_UE_stats,&RC.mac[ru->eNB_list[0]->Mod_id]->UE_info.eNB_UE_stats, sizeof(eNB_UE_STATS)*MAX_NUM_CCs*NUMBER_OF_UE_MAX);
        memcpy(&pre_scd_activeUE, &RC.mac[ru->eNB_list[0]->Mod_id]->UE_info.active, sizeof(bool)*NUMBER_OF_UE_MAX);
        AssertFatal((ret=pthread_mutex_lock(&ru->proc.mutex_pre_scd))==0,"[eNB] error locking proc mutex for eNB pre scd\n");
        ru->proc.instance_pre_scd++;

        if (ru->proc.instance_pre_scd == 0) {
          if (pthread_cond_signal(&ru->proc.cond_pre_scd) != 0) {
            LOG_E( PHY, "[eNB] ERROR pthread_cond_signal for eNB pre scd\n" );
            exit_fun( "ERROR pthread_cond_signal cond_pre_scd" );
          }
        } else {
          LOG_E( PHY, "[eNB] frame %d subframe %d rxtx busy instance_pre_scd %d\n",
                 frame,subframe,ru->proc.instance_pre_scd );
        }

        AssertFatal((ret=pthread_mutex_unlock(&ru->proc.mutex_pre_scd))==0,"[eNB] error unlocking mutex_pre_scd mutex for eNB pre scd\n");
#endif
	// wakeup all eNB processes waiting for this RU
	if (ru->num_eNB>0) wakeup_L1s(ru);

#ifdef MBMS_EXPERIMENTAL
	//Workaround ... this must be properly handled
	if(ru->if_south==LOCAL_RF && ru->function==eNodeB_3GPP && ru->eNB_list[0]!=NULL){
		if(ru->frame_parms->num_MBSFN_config!=ru->eNB_list[0]->frame_parms.num_MBSFN_config){
			ru->frame_parms = &ru->eNB_list[0]->frame_parms;//->frame_parms;
			LOG_W(PHY,"RU MBSFN SF PARAMS Updated\n");
		}
	}
#endif
	
#ifndef PHY_TX_THREAD

        if(get_thread_parallel_conf() == PARALLEL_SINGLE_THREAD || ru->num_eNB==0) {
          // do TX front-end processing if needed (precoding and/or IDFTs)
          if (ru->feptx_prec) ru->feptx_prec(ru, proc->frame_tx, proc->tti_tx);

          // do OFDM if needed
          if ((ru->fh_north_asynch_in == NULL) && (ru->feptx_ofdm)) ru->feptx_ofdm(ru, proc->frame_tx, proc->tti_tx);

          if(!(ru->emulate_rf)) { //if(!emulate_rf){
            // do outgoing fronthaul (south) if needed
            if ((ru->fh_north_asynch_in == NULL) && (ru->fh_south_out)) ru->fh_south_out(ru, proc->frame_tx, proc->tti_tx, proc->timestamp_tx);

            if ((ru->fh_north_out) && (ru->state!=RU_CHECK_SYNC)) ru->fh_north_out(ru);
          } else {
            for (int i=0; i<ru->nb_tx; i++) {
              if(proc->frame_tx == 2) {
                sprintf(filename,"txdataF%d_frame%d_sf%d.m",i,proc->frame_tx,proc->tti_tx);
                LOG_M(filename,"txdataF_frame",ru->common.txdataF_BF[i],ru->frame_parms->symbols_per_tti*ru->frame_parms->ofdm_symbol_size, 1, 1);
              }

              if(proc->frame_tx == 2 && proc->tti_tx==0) {
                sprintf(filename,"txdata%d_frame%d.m",i,proc->frame_tx);
                LOG_M(filename,"txdata_frame",ru->common.txdata[i],ru->frame_parms->samples_per_tti*10, 1, 1);
              }
            }
          }

          proc->emulate_rf_busy = 0;
        }

#else
        struct timespec time_req, time_rem;
        time_req.tv_sec = 0;
        time_req.tv_nsec = 10000;

        while((!oai_exit)&&(phy_tx_end == 0)) {
          nanosleep(&time_req,&time_rem);
          continue;
        }

#endif
      } // else wait_cnt == 0
    } // ru->state = RU_RUN || RU_CHECK_SYNC
  } // while !oai_exit

  LOG_I(PHY, "Exiting ru_thread \n");

  if (!(ru->emulate_rf)) {
    if (ru->stop_rf != NULL) {
      if (ru->stop_rf(ru) != 0)
        LOG_E(HW,"Could not stop the RF device\n");
      else LOG_I(PHY,"RU %d rf device stopped\n",ru->idx);
    }
  }

  return NULL;
}


// This thread run the initial synchronization like a UE
static void *ru_thread_synch(void *arg) {
  RU_t *ru = (RU_t *)arg;
  __attribute__((unused))
  LTE_DL_FRAME_PARMS *fp = ru->frame_parms;
  int64_t peak_val, avg;
  static int ru_thread_synch_status = 0;
  int cnt=0;
  thread_top_init("ru_thread_synch",0,5000000,10000000,10000000);
  wait_sync("ru_thread_synch");
  // initialize variables for PSS detection
  ru_sync_time_init(ru); //lte_sync_time_init(ru->frame_parms);

  fp = ru->frame_parms;
  int last_rxoff=0;
  while (!oai_exit) {
    // wait to be woken up
    if (wait_on_condition(&ru->proc.mutex_synch,&ru->proc.cond_synch,&ru->proc.instance_cnt_synch,"ru_thread_synch")<0) break;

    // if we're not in synch, then run initial synch
    if (ru->in_synch == 0) {
      // run intial synch like UE
      LOG_I(PHY,"Running initial synchronization\n");
      ru->rx_offset = ru_sync_time(ru,
                                   &peak_val,
                                   &avg);
      LOG_I(PHY,"RU synch cnt %d: %d, val %llu (%d dB,%d dB)\n",cnt,ru->rx_offset,(unsigned long long)peak_val,dB_fixed64(peak_val),dB_fixed64(avg));
      cnt++;
      int abs_diff= ru->rx_offset - last_rxoff;
      if (abs_diff<0) abs_diff=-abs_diff;
      if (ru->rx_offset >= 0 && abs_diff<6 && avg>0 && dB_fixed(peak_val/avg)>=15 && cnt>10) {
        LOG_I(PHY,"Estimated peak_val %d dB, avg %d => timing offset %llu\n",dB_fixed(peak_val),dB_fixed(avg),(unsigned long long int)ru->rx_offset);
        ru->in_synch = 1;
       /* 
                LOG_M("ru_sync_rx.m","rurx",&ru->common.rxdata[0][0],LTE_NUMBER_OF_SUBFRAMES_PER_FRAME*fp->samples_per_tti,1,1);
                LOG_M("ru_sync_corr.m","sync_corr",ru->dmrs_corr,LTE_NUMBER_OF_SUBFRAMES_PER_FRAME*fp->samples_per_tti,1,6);
                LOG_M("ru_dmrs.m","rudmrs",&ru->dmrssync[0],fp->ofdm_symbol_size,1,1);
          
        exit(-1);
       */
      } // sync_pos > 0
      else { //AssertFatal(cnt<1000,"Cannot find synch reference\n");
        if (cnt>200) {
          LOG_M("ru_sync_rx.m","rurx",&ru->common.rxdata[0][0],LTE_NUMBER_OF_SUBFRAMES_PER_FRAME*fp->samples_per_tti,1,1);
          LOG_M("ru_sync_corr.m","sync_corr",ru->dmrs_corr,LTE_NUMBER_OF_SUBFRAMES_PER_FRAME*fp->samples_per_tti,1,6);
          LOG_M("ru_dmrs.m","rudmrs",&ru->dmrssync[0],fp->ofdm_symbol_size,1,1);
          exit(-1);
        }
      }
      last_rxoff=ru->rx_offset;
    } // ru->in_synch==0

    if (release_thread(&ru->proc.mutex_synch,&ru->proc.instance_cnt_synch,"ru_synch_thread") < 0) break;
  } // oai_exit

  ru_sync_time_free(ru);
  ru_thread_synch_status = 0;
  return &ru_thread_synch_status;
}


#if defined(PRE_SCD_THREAD)
void *pre_scd_thread( void *param ) {
  void rlc_tick(int, int);
  static int              eNB_pre_scd_status;
  protocol_ctxt_t         ctxt;
  int                     frame;
  int                     subframe;
  int                     min_rb_unit[MAX_NUM_CCs];
  int                     CC_id;
  int                     Mod_id;
  RU_t               *ru      = (RU_t *)param;
  int                     ret;

  // L2-emulator can work only one eNB
  if( NFAPI_MODE==NFAPI_MODE_VNF)
    Mod_id = 0;