module PCU_Tests {

/* "RAW" PCU tests: Talk directly to the PCU socket of OsmoPCU on the one hand side (emulating
   the BTS/BSC side PCU socket server) and the Gb interface on the other hand side.  No NS/BSSGP
   Emulation is used; rather, we simply use the NS_CodecPort to implement both standard and non-
   standard procedures on the NS and BSSGP level.  The goal of these tests is to test exactly
   those NS and BSSGP implementations on the BSS (PCU) side. */

/* (C) 2018-2019 Harald Welte <laforge@gnumonks.org>
 * (C) 2019-2020 Vadim Yanitskiy <axilirator@gmail.com>
 * All rights reserved.
 *
 * Released under the terms of GNU General Public License, Version 2 or
 * (at your option) any later version.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

friend module PCU_Tests_NS;

import from General_Types all;
import from Osmocom_Types all;
import from GSM_Types all;
import from GSM_RR_Types all;

import from Osmocom_VTY_Functions all;
import from TELNETasp_PortType all;

import from MobileL3_GMM_SM_Types all;
import from RLCMAC_CSN1_Types all;
import from RLCMAC_CSN1_Templates all;
import from RLCMAC_Types all;
import from RLCMAC_Templates all;

import from MobileL3_CommonIE_Types all;
import from L3_Templates all;

import from NS_Types all;
import from BSSGP_Types all;
import from Osmocom_Gb_Types all;

import from BSSGP_Emulation all; /* BssgpConfig */
import from NS_Emulation all; /* NSConfiguration */

import from UD_Types all;
import from PCUIF_Types all;
import from PCUIF_CodecPort all;
import from PCUIF_Components all;
import from IPL4asp_Types all;
import from Native_Functions all;
import from SGSN_Components all;
import from GPRS_Components all;

modulepar {
	charstring mp_pcu_sock_path := PCU_SOCK_DEFAULT;

	float X2002 := 0.2; /* Timer -2002, IMM ASSIGN confirm delay */
}


/* FIXME: make sure to use parameters from mp_gb_cfg.cell_id in the PCU INFO IND */
friend template (value) PCUIF_info_ind ts_PCUIF_INFO_default := {
	version := PCUIF_Types.mp_pcuif_version,
	flags := c_PCUIF_Flags_default,
	trx := f_PCUIF_ver_INFO_Trxs(),
	bsic := 7,
	mcc := 262,
	mnc := 42,
	mnc_3_digits := 0,
	lac := 13135,
	rac := 0,
	nsei := mp_nsconfig.nsei,
	nse_timer := { 3, 3, 3, 3, 30, 3, 10 },
	cell_timer := { 3, 3, 3, 3, 3, 10, 3, 10, 3, 10, 3 },
	cell_id := 20960,
	repeat_time := 5 * 50,
	repeat_count := 3,
	bvci := mp_gb_cfg.bvci,
	t3142 := 20,
	t3169 := 5,
	t3191 := 5,
	t3193_10ms := 160,
	t3195 := 5,
	t3101 := 10,
	t3103 := 4,
	t3105 := 8,
	cv_countdown := 15,
	dl_tbf_ext := 250 * 10, /* ms */
	ul_tbf_ext := 250 * 10, /* ms */
	initial_cs := 2,
	initial_mcs := 6,
	nsvci := { mp_nsconfig.nsvci, 0 },
	local_port := { mp_nsconfig.remote_udp_port, 0 },
	remote_port := { mp_nsconfig.local_udp_port, 0 },
	remote_ip := { f_inet_haddr(mp_nsconfig.local_ip) , '00000000'O }
}

type record lqual_range {
	/* component reference to the IPA_Client component used for RSL */
	uint8_t low,
	uint8_t high
}

type component RAW_PCU_Test_CT extends bssgp_CT, MS_BTS_IFACE_CT {
	/* PCU interface abstraction component */
	var RAW_PCUIF_CT vc_PCUIF;

	/* Connection to the PCUIF component */
	port RAW_PCU_MSG_PT PCUIF;
	/* VTY connection to the PCU */
	port TELNETasp_PT PCUVTY;

	/* Uplink CS/MCS thresholds, default from pcu_main.c: */
	var lqual_range g_cs_lqual_ranges[4] := {{low := 0, high := 6},
						 {low := 5, high := 8},
						 {low := 7, high := 13},
						 {low := 12,high := 35}};
	var lqual_range g_mcs_lqual_ranges[9] := {{low := 0, high := 6},
						 {low := 5, high := 8},
						 {low := 7, high := 13},
						 {low := 12,high := 15},
						 {low := 14, high := 17},
						 {low := 16, high := 18},
						 {low := 17,high := 20},
						 {low := 19, high := 24},
						 {low := 23,high := 35}};
	var uint8_t g_cs_initial_dl := 1;
	var uint8_t g_cs_initial_ul := 1;
	var uint8_t g_mcs_initial_dl := 1;
	var uint8_t g_mcs_initial_ul := 1;
	var uint8_t g_cs_max_dl := 4;
	var uint8_t g_cs_max_ul := 4;
	var uint8_t g_mcs_max_dl := 9;
	var uint8_t g_mcs_max_ul := 9;

	var boolean g_egprs_only := false;
	var boolean g_force_two_phase_access := false;

	/* Guard timeout */
	timer g_T_guard := 60.0;
};

private altstep as_Tguard_RAW() runs on RAW_PCU_Test_CT {
	[] g_T_guard.timeout {
		setverdict(fail, "Timeout of T_guard");
		f_shutdown(__BFILE__, __LINE__);
		}
}

private function f_pcuvty_set_allowed_cs_mcs() runs on RAW_PCU_Test_CT {
	f_vty_config2(PCUVTY, {"pcu"}, "cs " & int2str(g_cs_initial_dl) & " " & int2str(g_cs_initial_ul));
	f_vty_config2(PCUVTY, {"pcu"}, "cs max " & int2str(g_cs_max_dl) & " " & int2str(g_cs_max_ul));

	f_vty_config2(PCUVTY, {"pcu"}, "mcs " & int2str(g_mcs_initial_dl) & " " & int2str(g_mcs_initial_ul));
	f_vty_config2(PCUVTY, {"pcu"}, "mcs max " & int2str(g_mcs_max_dl) & " " & int2str(g_mcs_max_ul));
}

private function f_pcuvty_set_link_quality_ranges() runs on RAW_PCU_Test_CT {
	var charstring cmd;

	cmd := "cs link-quality-ranges" &
	       " cs1 " & int2str(g_cs_lqual_ranges[0].high) &
	       " cs2 " & int2str(g_cs_lqual_ranges[1].low) & " " & int2str(g_cs_lqual_ranges[1].high) &
	       " cs3 " & int2str(g_cs_lqual_ranges[2].low) & " " & int2str(g_cs_lqual_ranges[2].high) &
	       " cs4 " & int2str(g_cs_lqual_ranges[3].low);
	f_vty_config2(PCUVTY, {"pcu"}, cmd);

	cmd := "mcs link-quality-ranges" &
	       " mcs1 " & int2str(g_mcs_lqual_ranges[0].high) &
	       " mcs2 " & int2str(g_mcs_lqual_ranges[1].low) & " " & int2str(g_mcs_lqual_ranges[1].high) &
	       " mcs3 " & int2str(g_mcs_lqual_ranges[2].low) & " " & int2str(g_mcs_lqual_ranges[2].high) &
	       " mcs4 " & int2str(g_mcs_lqual_ranges[3].low) & " " & int2str(g_mcs_lqual_ranges[3].high) &
	       " mcs5 " & int2str(g_mcs_lqual_ranges[4].low) & " " & int2str(g_mcs_lqual_ranges[4].high) &
	       " mcs6 " & int2str(g_mcs_lqual_ranges[5].low) & " " & int2str(g_mcs_lqual_ranges[5].high) &
	       " mcs7 " & int2str(g_mcs_lqual_ranges[6].low) & " " & int2str(g_mcs_lqual_ranges[6].high) &
	       " mcs8 " & int2str(g_mcs_lqual_ranges[7].low) & " " & int2str(g_mcs_lqual_ranges[7].high) &
	       " mcs9 " & int2str(g_mcs_lqual_ranges[8].low);
	f_vty_config2(PCUVTY, {"pcu"}, cmd);
}

private function f_init_vty(charstring id) runs on RAW_PCU_Test_CT {
	map(self:PCUVTY, system:PCUVTY);
	f_vty_set_prompts(PCUVTY);
	f_vty_transceive(PCUVTY, "enable");

	if (g_egprs_only) {
		f_vty_config2(PCUVTY, {"pcu"}, "egprs only");
	} else {
		f_vty_config2(PCUVTY, {"pcu"}, "no egprs");
	}

	if (g_force_two_phase_access) {
		f_vty_config2(PCUVTY, {"pcu"}, "two-phase-access");
	} else {
		f_vty_config2(PCUVTY, {"pcu"}, "no two-phase-access");
	}
}

function f_init_raw(charstring id, template (value) PCUIF_info_ind info_ind := ts_PCUIF_INFO_default)
runs on RAW_PCU_Test_CT {
	/* Start the guard timer */
	g_T_guard.start;
	activate(as_Tguard_RAW());

	/* Init PCU interface component */
	vc_PCUIF := RAW_PCUIF_CT.create("PCUIF-" & id);
	connect(vc_PCUIF:MTC, self:PCUIF);
	map(vc_PCUIF:PCU, system:PCU);

	/* Create one BTS component (we may want more some day) */
	vc_BTS := RAW_PCU_BTS_CT.create("BTS-" & id);
	connect(vc_BTS:PCUIF, vc_PCUIF:BTS);
	connect(vc_BTS:TC, self:BTS);

	f_init_vty(id);

	vc_PCUIF.start(f_PCUIF_CT_handler(mp_pcu_sock_path));
	vc_BTS.start(f_BTS_CT_handler(0, valueof(info_ind)));

	/* Wait until the BTS is ready (SI13 negotiated) */
	BTS.receive(tr_RAW_PCU_EV(BTS_EV_SI13_NEGO));
}

testcase TC_pcuif_suspend() runs on RAW_PCU_Test_CT {
	var octetstring ra_id := enc_RoutingAreaIdentification(mp_gb_cfg.cell_id.ra_id);
	var GprsTlli tlli := 'FFFFFFFF'O;
	timer T;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();

	BTS.send(ts_PCUIF_SUSP_REQ(0, tlli, ra_id, 0));

	T.start(2.0);
	alt {
	[] BSSGP_SIG[0].receive(tr_BSSGP_SUSPEND(tlli, mp_gb_cfg.cell_id.ra_id)) {
		setverdict(pass);
		}
	[] T.timeout {
		setverdict(fail, "Timeout waiting for BSSGP SUSPEND");
		}
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test of correct Timing Advance at the time of TBF establishment
 * (derived from timing offset of the Access Burst). */
testcase TC_ta_rach_imm_ass() runs on RAW_PCU_Test_CT {
	var GprsMS ms;

	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */
	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* We cannot send too many TBF requests in a short time because
	 * at some point the PCU will fail to allocate a new TBF. */
	for (var TimingAdvance ta := 0; ta < 64; ta := ta + 16) {
		/* Establish an Uplink TBF (send RACH.ind with current TA) */
		ms.ta := ta;
		f_ms_establish_ul_tbf(ms);

		/* Make sure Timing Advance IE matches out expectations */
		if (ms.ul_tbf.rr_imm_ass.payload.imm_ass.timing_advance != ta) {
			setverdict(fail, "Timing Advance mismatch: ",
				   ms.ul_tbf.rr_imm_ass.payload.imm_ass.timing_advance,
				   " vs expected ", ta);
			break;
		}
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify Timing Advance value(s) indicated during the packet Downlink assignment
 * procedure as per 3GPP TS 44.018, section 3.5.3. There seems to be a bug in the
 * IUT that causes it to send an unreasonable Timing Advance value > 0 despite
 * no active TBF exists at the moment of establishment (idle mode). */
testcase TC_ta_idle_dl_tbf_ass() runs on RAW_PCU_Test_CT {
	var OCT4 tlli := f_rnd_octstring(4);
	var GsmRrMessage rr_imm_ass;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, tlli);

	/* SGSN sends some DL data, PCU will initiate Packet Downlink
	 * Assignment on CCCH (PCH). We don't care about the payload. */
	BSSGP[0].send(ts_BSSGP_DL_UD(tlli, f_rnd_octstring(10)));
	rr_imm_ass := f_pcuif_rx_imm_ass(PCU_IF_SAPI_PCH, tr_IMM_TBF_ASS(dl := true));

	/* Make sure that Timing Advance is 0 (the actual value is not known yet).
	 * As per 3GPP S 44.018, section 3.5.3.1.2, the network *shall* initiate
	 * the procedures defined in 3GPP TS 44.060 or use the polling mechanism. */
	if (rr_imm_ass.payload.imm_ass.timing_advance != 0) {
		setverdict(fail, "Timing Advance value doesn't match");
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify that the PCU generates valid PTCCH/D messages
 * while neither Uplink nor Downlink TBF is established. */
testcase TC_ta_ptcch_idle() runs on RAW_PCU_Test_CT {
	var PTCCHDownlinkMsg ptcch_msg;
	var PCUIF_Message pcu_msg;
	timer T;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Sent an RTS.req for PTCCH/D */
	BTS.send(ts_PCUIF_RTS_REQ(bts_nr := 0, trx_nr := 0, ts_nr := 7,
				  sapi := PCU_IF_SAPI_PTCCH, fn := 0,
				  arfcn := 871, block_nr := 0));
	T.start(5.0);
	alt {
	[] BTS.receive(tr_PCUIF_DATA_REQ(bts_nr := 0, trx_nr := 0, ts_nr := 7,
					 sapi := PCU_IF_SAPI_PTCCH)) -> value pcu_msg {
		log("Rx DATA.req message: ", pcu_msg);
		setverdict(pass);
		}
	[] BTS.receive(PCUIF_Message:?) { repeat; }
	[] T.timeout {
		setverdict(fail, "Timeout waiting for a PTCCH/D block");
		f_shutdown(__BFILE__, __LINE__);
		}
	}

	ptcch_msg := dec_PTCCHDownlinkMsg(pcu_msg.u.data_req.data);
	log("Decoded PTCCH/D message: ", ptcch_msg);

	/* Make sure the message is encoded correctly
	 * TODO: do we expect all TA values to be equal '1111111'B? */
	if (not match(ptcch_msg, tr_PTCCHDownlinkMsg)) {
		setverdict(fail, "Malformed PTCCH/D message");
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test of correct Timing Advance during an active Uplink TBF.
 *
 * Unlike the circuit-switched domain, Uplink transmissions on PDCH time-slots
 * are not continuous and there can be long time gaps between them. This happens
 * due to a bursty nature of packet data. The actual Timing Advance of a MS may
 * significantly change between such rare Uplink transmissions, so GPRS introduces
 * additional mechanisms to control Timing Advance, and thus reduce interference
 * between neighboring TDMA time-slots.
 *
 * At the moment of Uplink TBF establishment, initial Timing Advance is measured
 * from ToA (Timing of Arrival) of an Access Burst. This is covered by another
 * test case - TC_ta_rach_imm_ass. In response to that Access Burst the network
 * sends Immediate Assignment on AGCH, which _may_ contain Timing Advance Index
 * among with the initial Timing Advance value. And here PTCCH comes to play.
 *
 * PTCCH is a unidirectional channel on which the network can instruct a sub-set
 * of 16 MS (whether TBFs are active or not) to adjust their Timing Advance
 * continuously. To ensure continuous measurements of the signal propagation
 * delay, the MSs shall transmit Access Bursts on Uplink (PTCCH/U) on sub-slots
 * defined by an assigned Timing Advance Index (see 3GPP TS 45.002).
 *
 * The purpose of this test case is to verify the assignment of Timing Advance
 * Index, and the process of Timing Advance notification on PTCCH/D. The MTC
 * first establishes several Uplink TBFs, but does not transmit any Uplink
 * blocks on them. During 4 TDMA multi-frame periods the MTC is sending RACH
 * indications to the PCU, checking the correctness of two received PTCCH/D
 * messages (period of PTCCH/D is two multi-frames).
 */

/* List of ToA values for Access Bursts to be sent on PTCCH/U,
 * each ToA (Timing of Arrival) value is in units of 1/4 of
 * a symbol (i.e. 1 symbol is 4 QTA units). */
type record length(16) of int16_t PTCCH_TAI_ToA_MAP;
const PTCCH_TAI_ToA_MAP ptcch_toa_map_def := {
	0, 0, 0, 0,
	0, 0, 0, 0,
	0, 0, 0, 0,
	0, 0, 0, 0
};

private altstep as_ta_ptcch(uint8_t bts_nr := 0, uint8_t trx_nr := 0, uint8_t ts_nr := 7,
			    in PTCCH_TAI_ToA_MAP toa_map := ptcch_toa_map_def)
runs on RAW_PCU_Test_CT {
	var RAW_PCU_Event event;
	var integer ss;

	/* Send Access Bursts on PTCCH/U for every TA Index */
	[] BTS.receive(tr_RAW_PCU_EV(TDMA_EV_PTCCH_UL_BURST)) -> value event {
		ss := f_tdma_ptcch_fn2ss(event.data.tdma_fn);
		if (ss < 0) { /* Shall not happen */
			f_shutdown(__BFILE__, __LINE__);
		}

		log("Sending an Access Burst on PTCCH/U",
		    ", sub-slot=", ss, " (TAI)",
		    ", fn=", event.data.tdma_fn,
		    ", ToA=", toa_map[ss], " (QTA)");
		/* TODO: do we care about RA and burst format? */
		BTS.send(ts_PCUIF_RACH_IND(bts_nr, trx_nr, ts_nr,
					   ra := oct2int('3A'O),
					   is_11bit := 0,
					   burst_type := BURST_TYPE_0,
					   fn := event.data.tdma_fn,
					   arfcn := 871,
					   qta := toa_map[ss],
					   sapi := PCU_IF_SAPI_PTCCH));
		repeat;
		}
}

private function f_TC_ta_ptcch_ul_multi_tbf(in PTCCH_TAI_ToA_MAP ptcch_toa_map,
					    template PTCCHDownlinkMsg t_ta_msg)
runs on RAW_PCU_Test_CT {
	var PTCCHDownlinkMsg ta_msg;
	var PCUIF_Message pcu_msg;
	timer T;

	/* First, send an RTS.req for the upcoming PTCCH/D block */
	BTS.send(ts_PCUIF_RTS_REQ(bts_nr := 0, trx_nr := 0, ts_nr := 7,
				  sapi := PCU_IF_SAPI_PTCCH, fn := 0,
				  arfcn := 871, block_nr := 0));
	T.start(2.0);
	alt {
	/* Keep sending of Access Bursts during two multi-frames (period of PTCCH/D)
	 * with increasing ToA (Timing of Arrival) values: 0, 7, 14, 28, 35... */
	[] as_ta_ptcch(bts_nr := 0, trx_nr := 0, ts_nr := 7, toa_map := ptcch_toa_map);
	/* In the end of 2nd multi-frame we should receive a PTCCH/D block */
	[] BTS.receive(tr_PCUIF_DATA_REQ(bts_nr := 0, trx_nr := 0, ts_nr := 7,
					 sapi := PCU_IF_SAPI_PTCCH)) -> value pcu_msg {
		ta_msg := dec_PTCCHDownlinkMsg(pcu_msg.u.data_req.data);
		log("Rx PTCCH/D message: ", ta_msg);

		/* Make sure Timing Advance values match our expectations */
		if (not match(ta_msg, t_ta_msg)) {
			setverdict(fail, "PTCCH/D message does not match: ", t_ta_msg);
		}
		}
	[] BTS.receive { repeat; }
	[] T.timeout {
		setverdict(fail, "Timeout waiting for a PTCCH/D block");
		}
	}
}

testcase TC_ta_ptcch_ul_multi_tbf() runs on RAW_PCU_Test_CT {
	var template PacketUlAssign t_ul_tbf_ass;
	var GprsMS ms;

	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Enable forwarding of PTCCH/U TDMA events to us */
	BTS.send(ts_RAW_PCU_CMD(TDMA_CMD_ENABLE_PTCCH_UL_FWD));

	/* Establish 7 Uplink TBFs (USF flag is 3 bits long, '111'B is reserved) */
	for (var integer i := 0; i < 7; i := i + 1) {
		/* Establish an Uplink TBF */
		f_ms_establish_ul_tbf(ms);

		/* We expect incremental TFI/USF assignment (dynamic allocation) */
		t_ul_tbf_ass := tr_PacketUlDynAssign(tfi := i, usf := i);
		if (not match(ms.ul_tbf.ass.ccch, t_ul_tbf_ass)) {
			setverdict(fail, "Failed to match Packet Uplink Assignment for #", i);
			break;
		}

		/* We also expect Timing Advance Index to be a part of the assignment */
		if (ms.ul_tbf.ass.ccch.dynamic.ta_index != i) {
			setverdict(fail, "Failed to match Timing Advance Index for #", i);
			/* Keep going, the current OsmoPCU does not assign TA Index */
		}
	}

	/* Prepare a list of ToA values for Access Bursts to be sent on PTCCH/U */
	var PTCCH_TAI_ToA_MAP toa_map := ptcch_toa_map_def;
	for (var integer i := 0; i < 7; i := i + 1) {
		/* ToA in units of 1/4 of a symbol */
		toa_map[i] := (i + 1) * 7 * 4;
	}

	/* Now we have all 7 TBFs established in one-phase access mode,
	 * however we will not be sending any data on them. Instead, we
	 * will be sending RACH.ind on PTCCH/U during 4 multi-frame
	 * periods (TAI 0..8), and then will check two PTCCH/D blocks.
	 *
	 * Why not 4 TBFs at once? Because Uplink is delayed by 3 TDMA
	 * time-slots, so at the moment of scheduling a PTCCH/D block
	 * the PCU has odd number of PTCCH/U Access Bursts received. */
	f_TC_ta_ptcch_ul_multi_tbf(toa_map, tr_PTCCHDownlinkMsg(
		tai0_ta :=  7, tai1_ta := 14, tai2_ta := 21,
		/* Other values are not known (yet) */
		tai3_ta := ?));
	f_TC_ta_ptcch_ul_multi_tbf(toa_map, tr_PTCCHDownlinkMsg(
		tai0_ta :=  7, tai1_ta := 14, tai2_ta := 21,
		tai3_ta := 28, tai4_ta := 35, tai5_ta := 42,
		/* Other values are out of our interest */
		tai6_ta := ?));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Default link quality adaptation (Coding Scheme) ranges (inclusive).
 * OsmoPCU (VTY): cs link-quality-ranges cs1 6 cs2 5 8 cs3 7 13 cs4 12
 *
 * NOTE: the ranges are intentionally overlapping because OsmoPCU
 * does not change CS/MCS on the range borders (5-6, 7-8, 12-13). */
private template integer CS1_lqual_dB_range := (-infinity .. 6);
private template integer CS2_lqual_dB_range := (5 .. 8);
private template integer CS3_lqual_dB_range := (7 .. 13);
private template integer CS4_lqual_dB_range := (12 .. infinity);

testcase TC_cs_lqual_ul_tbf() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var GprsMS ms;
	var uint32_t unused_fn, sched_fn;
	var uint4_t cv;

	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	f_pcuvty_set_allowed_cs_mcs();
	f_pcuvty_set_link_quality_ranges();

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);


	/* The actual / old link quality values. We need to keep track of the old
	 * (basically previous) link quality value, because OsmoPCU actually
	 * changes the coding scheme if not only the actual, but also the old
	 * value leaves the current link quality range (window). */
	var integer lqual_old;
	ms.lqual_cb := 0;

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine. */
	/* 16 bytes fills the llc block (because TLLI takes 4 bytes) */
	/* Set CV = 15 to signal there's still more than BS_CV_MAX blocks to be sent */
	f_ms_tx_ul_data_block(ms, f_rnd_octstring(16), cv := 15, with_tlli := true)
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* 16 UL blocks (0 .. 15 dB, step = 1 cB) */
	for (var integer i := 150; i >= 0; i := i - 1) {
		/* Update the old / actual link quality */
		lqual_old := ms.lqual_cb;
		ms.lqual_cb := 150 - i;

		/* Enqueue DATA.ind (both TDMA frame and block numbers to be patched) */
		log("Sending DATA.ind with link quality (dB): ", ms.lqual_cb);
		if (i > g_bs_cv_max) {
			cv := 15;
		} else {
			cv := i;
		}

		f_ms_tx_ul_data_block(ms, f_rnd_octstring(10), cv := cv)

		/* we will receive UL ACK/NACK from time to time. In that case, check CdCofing increases */
		f_rx_rlcmac_dl_block(dl_block, unused_fn);
		if (match(dl_block, tr_RLCMAC_DUMMY_CTRL())) {
			continue;
		}
		if (not match(dl_block, tr_RLCMAC_UL_ACK_NACK_GPRS(ul_tfi := ?)) and
		    not match(dl_block, tr_RLCMAC_UL_ACK_NACK_EGPRS(ul_tfi := ?))) {
			setverdict(fail, "Failed to match Packet Uplink ACK / NACK:", dl_block);
			f_shutdown(__BFILE__, __LINE__);
		}

		log("Rx Packet Uplink ACK / NACK with Channel Coding Command: ",
		    dl_block.ctrl.payload.u.ul_ack_nack.gprs.ch_coding_cmd);

		/* Match the received Channel Coding Command. Since we are increasing
		 * the link quality value on each iteration and not decreasing, there
		 * is no need to check the both old and current link quality values. */
		var template ChCodingCommand ch_coding;
		select (lqual_old / 10) {
		case (CS1_lqual_dB_range) { ch_coding := CH_CODING_CS1; }
		case (CS2_lqual_dB_range) { ch_coding := CH_CODING_CS2; }
		case (CS3_lqual_dB_range) { ch_coding := CH_CODING_CS3; }
		case (CS4_lqual_dB_range) { ch_coding := CH_CODING_CS4; }
		}

		if (not match(dl_block.ctrl.payload.u.ul_ack_nack.gprs.ch_coding_cmd, ch_coding)) {
			setverdict(fail, "Channel Coding does not match our expectations: ", ch_coding);
			f_shutdown(__BFILE__, __LINE__);
		}
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test the max UL CS set by VTY works fine */
testcase TC_cs_initial_ul() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var ChCodingCommand last_ch_coding;
	var uint32_t unused_fn, sched_fn;
	var GprsMS ms;

	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Set initial UL CS to 3 */
	g_cs_initial_ul := 3;
	f_pcuvty_set_allowed_cs_mcs();
	f_pcuvty_set_link_quality_ranges();

	/* Take lqual (dB->cB) so that we stay in that CS */
	ms.lqual_cb := g_cs_lqual_ranges[2].low * 10;

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine. */
	/* 16 bytes fills the llc block (because TLLI takes 4 bytes) */
	/* Set CV = 15 to signal there's still more than BS_CV_MAX blocks to be sent */
	f_ms_tx_ul_data_block(ms, f_rnd_octstring(16), cv := 15, with_tlli := true)
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* Send UL blocks, until we receive UL ACK/NACK and check we are in same initial CS: */
	while (true) {
		f_ms_tx_ul_data_block(ms, f_rnd_octstring(10), cv := 15);
		f_rx_rlcmac_dl_block(dl_block, unused_fn);
		if (match(dl_block, tr_RLCMAC_DUMMY_CTRL())) {
			continue;
		}

		if (not match(dl_block, tr_RLCMAC_UL_ACK_NACK_GPRS(ul_tfi := ?)) and
		    not match(dl_block, tr_RLCMAC_UL_ACK_NACK_EGPRS(ul_tfi := ?))) {
			setverdict(fail, "Failed to match Packet Uplink ACK / NACK:", dl_block);
			f_shutdown(__BFILE__, __LINE__);
			break;
		}

		last_ch_coding := dl_block.ctrl.payload.u.ul_ack_nack.gprs.ch_coding_cmd;
		break;
	}
	if (last_ch_coding != CH_CODING_CS3) {
		setverdict(fail, "Channel Coding does not match our expectations (CS-3): ", last_ch_coding);
		f_shutdown(__BFILE__, __LINE__);
	}

	/* Remaining UL blocks are used to make sure regardless of initial
	/* lqual, we can go lower at any time */
	 /* 0 dB, make sure we downgrade CS */
	ms.lqual_cb := 0;
	/* 5 UL blocks, check we are in same initial CS: */
	f_ms_tx_ul_data_block_multi(ms, 5);
	/* Enqueue RTS.req, expect DATA.req with UL ACK from the PCU */
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, unused_fn);
	last_ch_coding := dl_block.ctrl.payload.u.ul_ack_nack.gprs.ch_coding_cmd;

	if (last_ch_coding != CH_CODING_CS1) {
		setverdict(fail, "Channel Coding does not match our expectations (CS-1): ", last_ch_coding);
		f_shutdown(__BFILE__, __LINE__);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test the max UL CS set by VTY works fine */
testcase TC_cs_max_ul() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var ChCodingCommand last_ch_coding;
	var uint32_t unused_fn, sched_fn;
	var GprsMS ms;

	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Set maximum allowed UL CS to 3 */
	g_cs_max_ul := 3;
	f_pcuvty_set_allowed_cs_mcs();
	f_pcuvty_set_link_quality_ranges();

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine. */
	/* 16 bytes fills the llc block (because TLLI takes 4 bytes) */
	/* Set CV = 15 to signal there's still more than BS_CV_MAX blocks to be sent */
	f_ms_tx_ul_data_block(ms, f_rnd_octstring(16), cv := 15, with_tlli := true)
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	ms.lqual_cb :=  40*10; /* 40 dB */
	f_ms_tx_ul_data_block_multi(ms, 16);

	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, unused_fn);
	last_ch_coding := dl_block.ctrl.payload.u.ul_ack_nack.gprs.ch_coding_cmd;

	if (last_ch_coding != CH_CODING_CS3) {
		setverdict(fail, "Channel Coding does not match our expectations (CS-3): ", last_ch_coding);
		f_shutdown(__BFILE__, __LINE__);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify PCU drops TBF after some time of inactivity. */
testcase TC_t3169() runs on RAW_PCU_Test_CT {
	var PCUIF_info_ind info_ind;
	var RlcmacDlBlock dl_block;
	var uint32_t unused_fn;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	info_ind := valueof(ts_PCUIF_INFO_default);
	/* Set timer to 1 sec (default 5) to speedup test: */
	info_ind.t3169 := 1;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename(), info_ind);

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine */
	f_ms_tx_ul_data_block(ms, f_rnd_octstring(10), cv := 1, with_tlli := true)
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, unused_fn);
	/* UL block should NOT be received in SGSN, since we didn't get CV=0 */

	/* Wait until T3169 fires (plus 1 extra sec to make sure) */
	f_sleep(int2float(info_ind.t3169) + 1.0);

	/* Send an UL block once again, the TBF should be gone by now so no ACK */
	f_ms_tx_ul_data_block(ms, f_rnd_octstring(10), cv := 0)
	f_rx_rlcmac_dl_block_exp_dummy(dl_block);

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify that a Downlink TBF can be assigned using PACCH shortly after the
 * release of prev DL TBF due to MS staying in PDCH for a while (T3192, in PCU
 * T3193) after DL TBF release */
testcase TC_t3193() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var boolean ok;
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var GprsMS ms;
	var AckNackDescription ack_nack_desc := valueof(t_AckNackDescription_init);

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS: */
	f_sleep(X2002);
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0);

	/* ACK the DL block */
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc),
			 f_dl_block_ack_fn(dl_block, dl_fn));

	/* Now that final DL block is ACKED and TBF is released, T3193 in PCU
	   (T3192 in MS) was started and until it fires the MS will be available
	   on PDCH in case new data arrives from SGSN. Let's verify it: */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));
	f_ms_rx_pkt_ass_pacch(ms, sched_fn, tr_RLCMAC_DL_PACKET_ASS);

	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* Now that we confirmed the new assignment in the dl-tbf, lets receive the data and ack it */
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0);
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc),
			 f_dl_block_ack_fn(dl_block, dl_fn));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify PCU handles correctly Countdown Procedure based on BS_CV_MAX */
testcase TC_countdown_procedure() runs on RAW_PCU_Test_CT  {
	var RlcmacDlBlock dl_block;
	var uint32_t sched_fn;
	var octetstring total_payload;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine. */
	total_payload := f_rnd_octstring(16); /* 16 bytes fills the llc block (because TLLI takes 4 bytes) */
	/* Set CV = 15 to signal there's still more than BS_CV_MAX blocks to be sent */
	f_ms_tx_ul_data_block(ms, total_payload, cv := 15, with_tlli := true)
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* Send enough blocks to test whole procedure: Until Nth block
	   (N=BS_CV_MAX), CV=15 is sent, and then the decreasing countdown value is sent.
	 */
	total_payload := total_payload & f_ms_tx_ul_data_block_multi(ms, 20);
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* receive one message on BSSGP with all aggregated data in payload: */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, total_payload));
}

/* Verify PCU handles correctly CS1..4 with all possible LLC payload sizes fitting alone in one RLC block */
testcase TC_ul_all_sizes() runs on RAW_PCU_Test_CT  {
	var RlcmacDlBlock dl_block;
	var uint32_t dl_fn, sched_fn;
	var octetstring payload;
	var template (value) RlcmacUlBlock ul_data;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine. */
	payload := f_rnd_octstring(16); /* 16 bytes fills the llc block (because TLLI takes 4 bytes) */
	/* Set CV = 15 to signal there's still more than BS_CV_MAX blocks to be sent */
	ul_data := t_RLCMAC_UL_DATA_TLLI(tfi := ms.ul_tbf.tfi,
				    cv := 15,
				    bsn := ms.ul_tbf.bsn,
				    blocks := { t_RLCMAC_LLCBLOCK(payload,
								  t_RLCMAC_LLCBLOCK_HDR(length_ind := lengthof(payload), more := false, e := true))
					      },
				    tlli := ms.tlli);
	f_ultbf_inc_bsn(ms.ul_tbf);
	f_ms_tx_ul_block(ms, ul_data);

	/* ACK and check it was received fine */
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);
	/* receive one message on BSSGP with all aggregated data in payload: */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, payload));

	/* Test sending LLC PDUS of incrementing size */
	var integer max_size := 49;
	for (var integer i := 1; i <= max_size; i := i + 1) {
		var integer cv;
		/* Enqueue DATA.ind (both TDMA frame and block numbers to be patched) */
		log("Sending DATA.ind with LLC payload size ", i);
		if (i < max_size - g_bs_cv_max) {
			cv := 15;
		} else {
			cv := max_size - i;
		}

		payload := f_rnd_octstring(i);
		/* Set CV = 15 to signal there's still more than BS_CV_MAX blocks to be sent */
		ul_data := t_RLCMAC_UL_DATA(tfi := ms.ul_tbf.tfi,
					    cv := cv,
					    bsn := ms.ul_tbf.bsn,
					    blocks := { t_RLCMAC_LLCBLOCK(payload,
									  t_RLCMAC_LLCBLOCK_HDR(length_ind := lengthof(payload), more := false, e := true))
						      });
		f_ultbf_inc_bsn(ms.ul_tbf);
		f_ms_tx_ul_block(ms, ul_data);

		/* receive one message on BSSGP with all aggregated data in payload: */
		BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, payload));

		/* we will receive UL ACK/NACK from time to time, handle it. */
		f_rx_rlcmac_dl_block(dl_block, dl_fn);
		if (match(dl_block, tr_RLCMAC_DUMMY_CTRL())) {
			continue;
		}
		if (not match(dl_block, tr_RLCMAC_UL_ACK_NACK_GPRS(ul_tfi := ?)) and
		    not match(dl_block, tr_RLCMAC_UL_ACK_NACK_EGPRS(ul_tfi := ?))) {
			setverdict(fail, "Failed to match Packet Uplink ACK / NACK:", dl_block);
			f_shutdown(__BFILE__, __LINE__);
		}

		log("Rx Packet Uplink ACK / NACK");
		sched_fn := f_rrbp_ack_fn(dl_fn, dl_block.ctrl.mac_hdr.rrbp);
		/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
		f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);
	}
	setverdict(pass);
}

function f_TC_ul_data_toolong_fills_padding_cs(inout GprsMS ms, CodingScheme cs, integer cv) runs on RAW_PCU_Test_CT {
	var octetstring payload;
	var template (value) RlcmacUlBlock ul_data;
	var integer block_len, max_valid_data_len;
	timer T;

	block_len := f_rlcmac_cs_mcs2block_len(cs);
	/* We need to send with TLLI since we are in One-Phase Access Contenion
	 * resoultion), so that's -4 bytes of data, -3 for headers, -1 for LI
	 * indicator, -1 for spare bits octet at the end */
	max_valid_data_len := block_len - 4 - 3 - 1 - 1;
	payload := f_rnd_octstring(max_valid_data_len + 1); /* +1 to write LLC data on last padding octet */
	ul_data := t_RLCMAC_UL_DATA_TLLI(tfi := ms.ul_tbf.tfi,
				    cv := cv,
				    bsn := ms.ul_tbf.bsn,
				    blocks := { t_RLCMAC_LLCBLOCK(payload,
								  t_RLCMAC_LLCBLOCK_HDR(length_ind := lengthof(payload), more := false, e := true))
					      },
				    tlli := ms.tlli);
	f_ultbf_inc_bsn(ms.ul_tbf);
	f_ms_tx_data_ind(ms, enc_RlcmacUlBlock(valueof(ul_data)));

	T.start(0.5);
	alt {
	[] BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, ?)) {
		setverdict(fail, "LLC PDU in Malformed RLC block was forwarded");
		f_shutdown(__BFILE__, __LINE__);
	}
	[] T.timeout {
		setverdict(pass);
		}
	}
}
/* Verify PCU finds out incorrectly formated RLC block and discards it. This
   blocks intentionally contain last byte of data placed in last byte of RLC
   containing padding/spare bits, which is incorrect. Spare bits exist and are
   described for CS2..4 in 3GPP TS 44.060 Table 10.2.1: "RLC data block size,
   discounting padding in octet" */
testcase TC_ul_data_toolong_fills_padding() runs on RAW_PCU_Test_CT  {
	var GprsMS ms;
	var integer block_len, max_valid_data_len;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	f_TC_ul_data_toolong_fills_padding_cs(ms, CS_2, 2);
	f_TC_ul_data_toolong_fills_padding_cs(ms, CS_3, 1);
	f_TC_ul_data_toolong_fills_padding_cs(ms, CS_4, 0);

	setverdict(pass);
}

/* Test scenario where MS wants to send some data on PDCH against SGSN and it is
 * answered, so TBFs for uplink and later for downlink are created.
 */
private function f_TC_mo_ping_pong_1phase_access(template (present) CodingScheme exp_cs_mcs := ?) runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := true);
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	/* Now SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS: */
	f_sleep(X2002);
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0, exp_cs_mcs);

	/* ACK the DL block */
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc),
			     f_dl_block_ack_fn(dl_block, dl_fn));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test scenario where MS wants to send some data on PDCH against SGSN and it is
 * answered, so TBFs for uplink and later for downlink are created.
 */
testcase TC_mo_ping_pong() runs on RAW_PCU_Test_CT {
	var CodingScheme exp_cs_mcs := CS_1;
	f_TC_mo_ping_pong_1phase_access(exp_cs_mcs);
}

/* Test scenario where MS wants to send some data on PDCH against SGSN and it is
 * answered, so TBFs for uplink and later for downlink are created.
 */
private function f_TC_mo_ping_pong_2phase_access(template (value) MSRadioAccessCapabilityV ms_racap,
						 template (present) CodingScheme exp_ul_cs_mcs := ?,
						 template (present) CodingScheme exp_dl_cs_mcs := ?)
runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var uint32_t unused_fn;
	var GprsMS ms;

	/* 0111 0xxx: Single block packet access; one block period on a PDCH is needed for two phase packet access or other RR signalling purpose. */
	var uint16_t ra := oct2int('70'O);
	if (g_force_two_phase_access) {
		/* If 2phase access is enforced by the network, then let's
		   request a One phase packet access, we'll receive a single block
		   anyway */
		   ra := bit2int(chan_req_def);
	}

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_use_ra(ms, ra, ra_is_11bit := 0);
	f_ms_establish_ul_tbf(ms);

	/* Make sure we've got an Uplink TBF assignment */
	if (not match(ms.ul_tbf.ass.ccch, tr_PacketUlSglAssign)) {
		setverdict(fail, "Wrong Packet Uplink Assignment received: ", ms.ul_tbf.ass.ccch, " vs exp: ", tr_PacketUlSglAssign);
		f_shutdown(__BFILE__, __LINE__);
	}

	/* Send PACKET RESOURCE REQUEST to upgrade to EGPRS
	 * (see 3GPP TS 04.60 "7.1.3.1 Initiation of the Packet resource request procedure")
	 */
	f_ms_tx_ul_block(ms, ts_RLC_UL_CTRL_ACK(ts_RlcMacUlCtrl_PKT_RES_REQ(ms.tlli, ms_racap)), 0);
	f_ms_rx_pkt_ass_pacch(ms, sched_fn, tr_RLCMAC_UL_PACKET_ASS);
	if (not match(ms.ul_tbf.tx_cs_mcs, exp_ul_cs_mcs)) {
		setverdict(fail, "Wrong CS_MCS ", ms.ul_tbf.tx_cs_mcs, " received vs exp ", exp_ul_cs_mcs);
		f_shutdown(__BFILE__, __LINE__);
	}

	/* Send one UL block (without TLLI since we are in Second-Phase Access)
	   and make sure it is ACKED fine */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := true);  /* TODO: send using cs_mcs */

	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	/* Now SGSN sends some DL data, PCU will page on PACCH */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));
	f_ms_rx_pkt_ass_pacch(ms, sched_fn, tr_RLCMAC_DL_PACKET_ASS);
	/* DL Ass sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* PCU acks the UL data after having received CV=0) */
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, unused_fn);

	/* After acking the dl assignment, dl tbf goes into FLOW state and PCU will provide DL data when BTS asks for it */
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0, exp_dl_cs_mcs);

	/* ACK the DL block */
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.ul_tbf.tfi, ms.dl_tbf.acknack_desc),
			 f_dl_block_ack_fn(dl_block, dl_fn));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

testcase TC_mo_ping_pong_with_ul_racap() runs on RAW_PCU_Test_CT {
	var MultislotCap_GPRS mscap_gprs := {
		gprsmultislotclass := '00011'B,
		gprsextendeddynalloccap := '0'B
	};
	var MSRadioAccessCapabilityV ms_racap := { valueof(ts_RaCapRec('0001'B /* E-GSM */, mscap_gprs, omit)) };
	var CodingScheme exp_ul_cs_mcs := f_rlcmac_block_int2cs_mcs(g_mcs_initial_ul, false);
	var CodingScheme exp_dl_cs_mcs := CS_2;

	f_TC_mo_ping_pong_2phase_access(ms_racap, exp_ul_cs_mcs, exp_dl_cs_mcs);
}

testcase TC_mo_ping_pong_with_ul_racap_egprs_only() runs on RAW_PCU_Test_CT {
	/* Initialize the PCU interface abstraction with EGPRS-only */
	g_egprs_only := true;

	var MultislotCap_GPRS mscap_gprs := {
		gprsmultislotclass := '00011'B,
		gprsextendeddynalloccap := '0'B
	};
	var MultislotCap_EGPRS mscap_egprs := {
		egprsmultislotclass := '00011'B,
		egprsextendeddynalloccap := '0'B
	};
	var MSRadioAccessCapabilityV ms_racap := { valueof(ts_RaCapRec('0001'B /* E-GSM */, mscap_gprs, mscap_egprs)) };
	var CodingScheme exp_ul_cs_mcs := f_rlcmac_block_int2cs_mcs(g_mcs_initial_ul, true);
	var CodingScheme exp_dl_cs_mcs := MCS_1;

	f_TC_mo_ping_pong_2phase_access(ms_racap, exp_ul_cs_mcs, exp_dl_cs_mcs);
}

testcase TC_force_two_phase_access() runs on RAW_PCU_Test_CT {
	/* Configure PCU to force two phase access */
	g_force_two_phase_access := true;

	var MultislotCap_GPRS mscap_gprs := {
		gprsmultislotclass := '00011'B,
		gprsextendeddynalloccap := '0'B
	};
	var MSRadioAccessCapabilityV ms_racap := { valueof(ts_RaCapRec('0001'B /* E-GSM */, mscap_gprs, omit)) };
	var CodingScheme exp_ul_cs_mcs := f_rlcmac_block_int2cs_mcs(g_mcs_initial_ul, false);
	var CodingScheme exp_dl_cs_mcs := CS_2;

	f_TC_mo_ping_pong_2phase_access(ms_racap, exp_ul_cs_mcs, exp_dl_cs_mcs);
}

/* Test scenario where SGSN wants to send some data against MS and it is
 * answered by the MS on PDCH, so TBFs for downlink and later for uplink are created.
 */
private function f_TC_mt_ping_pong(template (omit) MSRadioAccessCapabilityV_BSSGP ms_racap := omit, template (present) CodingScheme exp_cs_mcs := ?) runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data, ms_racap));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS: */
	f_sleep(X2002);
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0, exp_cs_mcs);

	/* ACK the DL block, and request UL TBF at the same time */
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK_CHREQ(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc),
			 f_dl_block_ack_fn(dl_block, dl_fn));

	/* Expect UL ass */
	f_ms_rx_pkt_ass_pacch(ms, sched_fn, tr_RLCMAC_UL_PACKET_ASS);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := true);
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

testcase TC_mt_ping_pong() runs on RAW_PCU_Test_CT {
	var CodingScheme exp_cs_mcs := CS_1;
	f_TC_mt_ping_pong(omit, exp_cs_mcs);
}

/* TC_mt_ping_pong, but DL-UNITDATA contains RA Access capability with (M)CS
/* information about the MS */
testcase TC_mt_ping_pong_with_dl_racap() runs on RAW_PCU_Test_CT {
	var MultislotCap_GPRS_BSSGP mscap_gprs := {
		gprsmultislotclass := '00011'B,
		gprsextendeddynalloccap := '0'B
	} ;
	var MSRadioAccessCapabilityV_BSSGP ms_racap := { valueof(ts_RaCapRec_BSSGP('0001'B /* E-GSM */, mscap_gprs, omit)) };
	var CodingScheme exp_cs_mcs := CS_2;
	f_TC_mt_ping_pong(ms_racap, exp_cs_mcs);
}

/* Verify that if PCU doesn't get one of the intermediate UL data blocks in a UL
 * TBF, it will request retransmission through UL ACK/NACK (with missing block
 * in its bitmap) when CV=0 is received (and hence it knows no more data is to
 * be transferred).
 */
testcase TC_ul_intermediate_retrans() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var template (value) RlcmacUlBlock ul_data;
	var uint32_t sched_fn;
	var octetstring total_payload;
	var octetstring payload;
	var octetstring lost_payload;
	var uint5_t tfi;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);
	tfi := ms.ul_tbf.tfi;

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine. */
	payload := f_rnd_octstring(16); /* 16 bytes fills the llc block (because TLLI takes 4 bytes) */
	f_ms_tx_ul_data_block(ms, payload, cv := 15, with_tlli := true);

	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);
	total_payload := payload;

	/* Send 2 packets, skip 1 (inc bsn) and send another one */
	payload := f_rnd_octstring(20); /* 20 bytes fills the CS-1 llc block */
	f_ms_tx_ul_data_block(ms, payload, cv := 15);
	total_payload := total_payload & payload;

	payload := f_rnd_octstring(20); /* 20 bytes fills the CS-1 llc block */
	f_ms_tx_ul_data_block(ms, payload, cv := 15);
	total_payload := total_payload & payload;

	lost_payload := f_rnd_octstring(20);
	ms.ul_tbf.bsn := ms.ul_tbf.bsn + 1;  /* LOST PAYLOAD bsn=3, will be retransmitted, next bsn is increased +2 */
	total_payload := total_payload & lost_payload;

	payload := f_rnd_octstring(20); /* 20 bytes fills the CS-1 llc block */
	f_ms_tx_ul_data_block(ms, payload, cv := 15);
	total_payload := total_payload & payload;

	/* Send enough blocks to finish the transmission (since we were sending BSN=15, send BS_CV_MAX packets) */
	total_payload := total_payload & f_ms_tx_ul_data_block_multi(ms, g_bs_cv_max);

	/* On CV=0, we'll receive a UL ACK asking about missing block */
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* TODO: check ack ack bitmap (URBB) */
	ul_data := t_RLCMAC_UL_DATA(tfi := tfi, cv := 15, bsn := 3, blocks := {t_RLCMAC_LLCBLOCK(lost_payload)});
	f_ms_tx_ul_block(ms, ul_data);

	/* Now final ack is recieved */
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* receive one message on BSSGP with all aggregated data in payload: */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, total_payload));
}

/* Verify that if PCU doesn't get an ACK for first DL block after IMM ASS, it
 * will retry by retransmitting both the IMM ASS + DL block after poll (ack)
 * timeout occurs (specified by sent RRBP on DL block). */
testcase TC_imm_ass_dl_block_retrans() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t dl_fn;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS: */
	f_sleep(X2002);
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0);

	/* Now we don't ack the dl block (emulate MS failed receiveing IMM ASS
	 * or GPRS DL, or DL ACK was lost for some reason). As a result, PCU
	 * should retrigger IMM ASS + GPRS DL procedure after poll timeout. */
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS: */
	f_sleep(X2002);
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0);

	/* ACK the DL block */
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc),
			 f_dl_block_ack_fn(dl_block, dl_fn));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify scheduling of multiple Downlink data blocks during one RRBP. */
testcase TC_dl_flow_more_blocks() runs on RAW_PCU_Test_CT {
	var AckNackDescription ack_nack_desc := valueof(t_AckNackDescription_init);
	var octetstring data := f_rnd_octstring(16);
	var PacketDlAssign dl_tbf_ass;
	var RlcmacDlBlock dl_block;
	var uint32_t ack_fn;
	var uint32_t fn;
	var GprsMS ms;
	timer T := 5.0;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS */
	f_sleep(X2002);

	/* Expect the first (GPRS DL) block with bsn=0 and rrbp_valid=1 */
	f_rx_rlcmac_dl_block_exp_data(dl_block, fn, data, 0);
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block);

	/* TDMA frame number on which we are supposed to send the ACK */
	ack_fn := f_dl_block_ack_fn(dl_block, fn);

	/* SGSN sends more blocks during the indicated RRBP */
	for (var integer bsn := 1; bsn < 63; bsn := bsn + 1) {
		data := f_rnd_octstring(16); /* Random LLC data */
		BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));

		f_rx_rlcmac_dl_block_exp_data(dl_block, fn, data, bsn);

		/* Make sure this block has the same TFI as was assigned
		 * FIXME: this is only valid for GPRS, not EGPRS. */
		if (dl_block.data.mac_hdr.hdr_ext.tfi != ms.dl_tbf.tfi) {
			setverdict(fail, "Rx DL data block with unexpected TFI: ",
				   dl_block.data.mac_hdr.hdr_ext.tfi);
			f_shutdown(__BFILE__, __LINE__);
		}

		/* Keep Ack/Nack description updated */
		f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block);

		/* Break if this is the end of RRBP */
		if (fn == ack_fn) {
			ms.dl_tbf.acknack_desc.final_ack := '1'B;
			break;
		}
	}

	/* This is the end of RRBP, send Packet Downlink Ack/Nack */
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc), fn := fn);

	/* Make sure that the next block (after the Ack) is dummy */
	f_rx_rlcmac_dl_block_exp_dummy(dl_block);

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify Decoding and segmentation of UL LLC PDUs into RLC data blocks, OS#4559.
 * Check "GPRS from A-Z" slide "Example of LI-Field and E-Bit" page 186.
 * Check "3GPP TS 44.060" Annex B. */
testcase TC_ul_flow_multiple_llc_blocks() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring dataA := f_rnd_octstring(20);
	var octetstring dataB := f_rnd_octstring(13);
	var octetstring dataC := f_rnd_octstring(3);
	var octetstring dataD := f_rnd_octstring(12);
	var uint32_t sched_fn;
	var GprsMS ms;
	var template (value) RlcmacUlBlock ul_data;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Summary of what's transmitted:
	 * 1- UL RlcDataBlock(dataA) [BSN=0, CV=3]
	 * 2- UL RlcDataBlock(dataA finished, dataB starts) [BSN=1, CV=2]
	 * 3- UL RlcDataBlock(dataB finished, dataC starts and finishes, dataD starts) [BSN=2, CV=1]
	 * 4- UL RlcDataBlock(dataD finishes) [BSN=3, CV=0]
	 * And on SGSN we receive 4 packets, one for each LlcBlock dataA..D.
	 * We'll also receive some UL ACK/NACK we need to reply with CTRL ACK.
	 */

	/*  UL RlcDataBlock(dataA) [BSN=0, CV=3] */
	ul_data := t_RLCMAC_UL_DATA_TLLI(tfi := ms.ul_tbf.tfi,
				    cv := 3,
				    bsn := ms.ul_tbf.bsn,
				    blocks := { t_RLCMAC_LLCBLOCK(substr(dataA, 0, 16)) },
				    tlli := ms.tlli);
	/* Indicate no llc header, meaning first LLC block doesn't finish in current
	 * RLCMAC block being sent. */
	ul_data.data.mac_hdr.e := true;
	f_ultbf_inc_bsn(ms.ul_tbf);
	f_ms_tx_ul_block(ms, ul_data);

	/* UL RlcDataBlock(dataA finished, dataB starts) [BSN=1, CV=2] */
	ul_data := t_RLCMAC_UL_DATA_TLLI(tfi := ms.ul_tbf.tfi,
				    cv := 2,
				    bsn := ms.ul_tbf.bsn,
				    blocks := { t_RLCMAC_LLCBLOCK(substr(dataA, 16, 4),
								  t_RLCMAC_LLCBLOCK_HDR(length_ind := 4, more := true, e := true)),
						t_RLCMAC_LLCBLOCK(substr(dataB, 0, 11))
					      },
				    tlli := ms.tlli);
	f_ultbf_inc_bsn(ms.ul_tbf);
	f_ms_tx_ul_block(ms, ul_data);

	/* UL block dataA should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, dataA));

	/* UL RlcDataBlock(dataB finished, dataC starts and finishes, dataD starts) [BSN=2, CV=1] */
	ul_data := t_RLCMAC_UL_DATA_TLLI(tfi := ms.ul_tbf.tfi,
				    cv := 1,
				    bsn := ms.ul_tbf.bsn,
				    blocks := { t_RLCMAC_LLCBLOCK(substr(dataB, 11, 2),
								 t_RLCMAC_LLCBLOCK_HDR(length_ind := 2, more := true, e := false)),
						t_RLCMAC_LLCBLOCK(substr(dataC, 0, 3),
								  t_RLCMAC_LLCBLOCK_HDR(length_ind := 3, more := true, e := true)),
						t_RLCMAC_LLCBLOCK(substr(dataD, 0, 9))
					      },
				    tlli := ms.tlli);
	f_ultbf_inc_bsn(ms.ul_tbf);
	f_ms_tx_ul_block(ms, ul_data);

	/* UL block dataB and dataC should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, dataB));
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, dataC));

	/* UL RlcDataBlock(dataD finishes) [BSN=3, CV=0] */
	ul_data := t_RLCMAC_UL_DATA_TLLI(tfi := ms.ul_tbf.tfi,
				    cv := 0,
				    bsn := ms.ul_tbf.bsn,
				    blocks := { t_RLCMAC_LLCBLOCK(substr(dataD, 9, 3),
								  t_RLCMAC_LLCBLOCK_HDR(length_ind := 3, more := false, e := true))
					      },
				    tlli := ms.tlli);
	f_ultbf_inc_bsn(ms.ul_tbf);
	f_ms_tx_ul_block(ms, ul_data);

	/* UL block dataB and dataD should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id, dataD));

	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test scenario where MS wants to request a new TBF once the current one is
 * ending, by means of sending a Packet Resource Request on ul slot provided by
 * last Pkt Ul ACK's RRBP.
 * See 3GPP TS 44.060 sec 9.3.2.4.2 "Non-extended uplink TBF mode" */
testcase TC_ul_tbf_reestablish_with_pkt_resource_req() runs on RAW_PCU_Test_CT {
	var CodingScheme exp_cs_mcs := CS_1;
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var template RlcmacDlBlock acknack_tmpl;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send one UL block (with TLLI since we are in One-Phase Access
	   contention resoultion) and make sure it is ACKED fine */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := true);

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	acknack_tmpl := tr_RLCMAC_UL_ACK_NACK_GPRS(ms.ul_tbf.tfi,
						   tr_UlAckNackGprs(ms.tlli,
								    tr_AckNackDescription(final_ack := '1'B),
								    tr_UlAckNackGprsAdditionsRel99(tbf_est := true)))
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn, acknack_tmpl);

	/* TODO: verify TBF_EST and FinalACK are both '1' above */

	/* Send PACKET RESOURCE REQUEST to request a new UL TBF */
	f_ms_tx_ul_block(ms, ts_RLC_UL_CTRL_ACK(ts_RlcMacUlCtrl_PKT_RES_REQ(ms.tlli, omit)), sched_fn);
	f_ms_rx_pkt_ass_pacch(ms, sched_fn, tr_RLCMAC_UL_PACKET_ASS);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* Send one UL block (without TLLI since we are in Second-Phase Access)
	   and make sure it is ACKED fine */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := false);  /* TODO: send using cs_mcs */

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn, acknack_tmpl);
	/* ACK the ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	f_shutdown(__BFILE__, __LINE__, final := true);
}

private function f_pkt_paging_match_imsi(in PacketPagingReq req, hexstring imsi)
runs on RAW_PCU_Test_CT {
	var MobileIdentityLV_Paging mi_lv := req.repeated_pageinfo.cs.mobile_identity;
	var MobileIdentityV mi := dec_MobileIdentityV(mi_lv.mobile_id);

	if (mi_lv.len != 8) { /* 8 octets: type of ID (3 bits) + even/odd flag (1 bit) + 15 BCD-encoded digits (60 bits) */
		setverdict(fail, "Mobile Identity length mismatch: ",
			   "expected: 8, got: ", mi_lv.len);
		f_shutdown(__BFILE__, __LINE__);
	}

	/* Make sure MI contains IMSI before referencing it */
	if (mi.typeOfIdentity != '001'B) {
		setverdict(fail, "Mobile Identity must be of type IMSI ('001'B), ",
			   "got: ", mi.typeOfIdentity);
		f_shutdown(__BFILE__, __LINE__);
	} else if (mi.oddEvenInd_identity.imsi.digits != imsi) {
		setverdict(fail, "Mobile Identity contains unexpected IMSI, ",
			   "expected: ", imsi, " got: ", mi.oddEvenInd_identity.imsi.digits);
		f_shutdown(__BFILE__, __LINE__);
	}
}

/* Test CS paging over the BTS<->PCU socket.
 * When a (class B or C, not A) MS has an active TBF (or is on the PDCH), the MS can not react on CS paging over CCCH.
 * Paging should be send on the PACCH.
 *
 * 1. Send a Paging Request over PCU socket.
 * 2. Send a Ready-To-Send message over PCU socket
 * 3. Expect a Paging Frame
 */
testcase TC_paging_cs_from_bts() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var MobileIdentityLV mi;
	var octetstring mi_enc_lv;
	var hexstring imsi := f_gen_imsi(42);
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* build mobile Identity */
	mi := valueof(ts_MI_IMSI_LV(imsi));
	mi_enc_lv := enc_MobileIdentityLV(mi);
	/* Send paging request */
	BTS.send(ts_PCUIF_PAG_REQ(bts_nr := 0, id_lv := mi_enc_lv, chan_needed := 0,
				sapi :=PCU_IF_SAPI_PDTCH));

	/* Receive it on BTS side towards MS */
	f_rx_rlcmac_dl_block_exp_pkt_pag_req(dl_block);

	/* Make sure that Packet Paging Request contains the same IMSI */
	f_pkt_paging_match_imsi(dl_block.ctrl.payload.u.paging, imsi);

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Test CS paging over Gb (SGSN->PCU->BTS[PDCH]).
 */
private function f_tc_paging_cs_from_sgsn(Nsvci bvci, boolean use_ptmsi := false)
runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var hexstring imsi := f_gen_imsi(42);
	var GsmTmsi tmsi;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send paging request with or without TMSI */
	if (use_ptmsi) {
		tmsi := oct2int(f_rnd_octstring(4)); /* Random P-TMSI */
		BSSGP[0].send(ts_BSSGP_CS_PAGING_PTMSI(bvci, imsi, tmsi));
	} else {
		BSSGP[0].send(ts_BSSGP_CS_PAGING_IMSI(bvci, imsi));
	}

	/* Receive it on BTS side towards MS */
	f_rx_rlcmac_dl_block_exp_pkt_pag_req(dl_block);

	/* Make sure that Packet Paging Request contains the same P-TMSI/IMSI */
	if (use_ptmsi) {
		f_pkt_paging_match_tmsi(dl_block.ctrl.payload.u.paging, tmsi);
	} else {
		f_pkt_paging_match_imsi(dl_block.ctrl.payload.u.paging, imsi);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

testcase TC_paging_cs_from_sgsn_sign_ptmsi() runs on RAW_PCU_Test_CT {
	f_tc_paging_cs_from_sgsn(0, true);
}

testcase TC_paging_cs_from_sgsn_sign() runs on RAW_PCU_Test_CT {
	f_tc_paging_cs_from_sgsn(0);
}

testcase TC_paging_cs_from_sgsn_ptp() runs on RAW_PCU_Test_CT {
	f_tc_paging_cs_from_sgsn(mp_gb_cfg.bvci);
}

/* Test PS paging over Gb (SGSN->PCU->BTS[CCCH]).
 */
private function f_tc_paging_ps_from_sgsn(Nsvci bvci, boolean use_ptmsi := false)
runs on RAW_PCU_Test_CT {
	var integer imsi_suff_tx := 423;
	var hexstring imsi := f_gen_imsi(imsi_suff_tx);
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Send BSSGP PAGING-PS (with or without TMSI), wait for RR Paging Request Type 1.
	 * Make sure that both paging group (IMSI suffix) and Mobile Identity match. */
	if (use_ptmsi) {
		var OCT4 tmsi := f_rnd_octstring(4); /* Random P-TMSI */
		BSSGP[0].send(ts_BSSGP_PS_PAGING_PTMSI(bvci, imsi, oct2int(tmsi)));
		f_pcuif_rx_pch_pag_req1(t_MI_TMSI(tmsi), imsi_suff_tx);
	} else {
		BSSGP[0].send(ts_BSSGP_PS_PAGING_IMSI(bvci, imsi));
		f_pcuif_rx_pch_pag_req1(tr_MI_IMSI(imsi), imsi_suff_tx);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

testcase TC_paging_ps_from_sgsn_sign_ptmsi() runs on RAW_PCU_Test_CT {
	f_tc_paging_ps_from_sgsn(0, true);
}

testcase TC_paging_ps_from_sgsn_sign() runs on RAW_PCU_Test_CT {
	f_tc_paging_ps_from_sgsn(0);
}

testcase TC_paging_ps_from_sgsn_ptp() runs on RAW_PCU_Test_CT {
	f_tc_paging_ps_from_sgsn(mp_gb_cfg.bvci);
}

/* Verify osmo-pcu handles DL UNIT_DATA from SGSN with IMSI IE correctly. See OS#4729 */
testcase TC_bssgp_dl_unitdata_with_valid_imsi() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Fake GMM GPRS Attach or similar, PCU doesn't care about upper layers here */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := true);
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	/* Now SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data, imsi := ts_BSSGP_IMSI(ms.imsi)));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	/* Wait timer X2002 and DL block is available after CCCH IMM ASS: */
	f_sleep(X2002);
	f_rx_rlcmac_dl_block_exp_data(dl_block, dl_fn, data, 0);

	/* ACK the DL block */
	f_acknackdesc_ack_block(ms.dl_tbf.acknack_desc, dl_block, '1'B);
	f_ms_tx_ul_block(ms, ts_RLCMAC_DL_ACK_NACK(ms.dl_tbf.tfi, ms.dl_tbf.acknack_desc),
			     f_dl_block_ack_fn(dl_block, dl_fn));

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Verify osmo-pcu acts on incorrect IMSI IE content in DL UNIT_DATA from SGSN. See OS#4729 */
testcase TC_bssgp_dl_unitdata_with_invalid_imsi() runs on RAW_PCU_Test_CT {
	var RlcmacDlBlock dl_block;
	var octetstring data := f_rnd_octstring(10);
	var uint32_t sched_fn;
	var uint32_t dl_fn;
	var GprsMS ms;

	/* Initialize NS/BSSGP side */
	f_init_bssgp();
	/* Initialize GPRS MS side */
	f_init_gprs_ms();
	ms := g_ms[0]; /* We only use first MS in this test */

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Fake GMM GPRS Attach or similar, PCU doesn't care about upper layers here */
	f_ms_tx_ul_data_block_multi(ms, 1, with_tlli := true);
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, sched_fn);
	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), sched_fn);

	/* UL block should be received in SGSN */
	BSSGP[0].receive(tr_BSSGP_UL_UD(ms.tlli, mp_gb_cfg.cell_id));

	/* Now SGSN sends some DL data with an invalid IMSI */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data, imsi := ts_BSSGP_IMSI('1122'H)));

	BSSGP_SIG[0].receive(tr_BSSGP_STATUS(omit, BSSGP_CAUSE_CONDITIONAL_IE_ERROR, ?));

	/* TODO: make sure no data is sent over PCU -> MS */

	f_shutdown(__BFILE__, __LINE__, final := true);
}

private function f_TC_egprs_pkt_chan_req(in EGPRSPktChRequest req,
					 template GsmRrMessage t_imm_ass := ?,
					 PCUIF_BurstType bt := BURST_TYPE_1)
runs on RAW_PCU_Test_CT {
	var GsmRrMessage rr_msg;
	var uint16_t ra11;

	ra11 := enc_EGPRSPktChRequest2uint(req);
	log("Sending EGPRS Packet Channel Request (", ra11, "): ", req);

	rr_msg := f_pcuif_tx_rach_rx_imm_ass(ra := ra11, is_11bit := 1, burst_type := bt);
	if (not match(rr_msg, t_imm_ass)) {
		setverdict(fail, "Immediate Assignment does not match");
		f_shutdown(__BFILE__, __LINE__);
	}

	setverdict(pass);
}

testcase TC_egprs_pkt_chan_req_signalling() runs on RAW_PCU_Test_CT {
	var template GsmRrMessage imm_ass;
	var template IaRestOctets rest;
	var template EgprsUlAss ul_ass;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	var EGPRSPktChRequest req := {
		/* NOTE: other fields are set in the loop */
		signalling := { tag := '110011'B }
	};

	for (var integer i := 0; i < 6; i := i + 1) {
		var BIT5 ext_ra := int2bit(f_rnd_int(32), 5);
		req.signalling.random_bits := ext_ra;

		/* For signalling, do we expect Multiblock UL TBF Assignment? */
		ul_ass  := tr_EgprsUlAssMultiblock(ext_ra := ext_ra);
		rest    := tr_IaRestOctets_EGPRSULAss(ul_ass);
		imm_ass := tr_IMM_TBF_ASS(dl := false, rest := rest);

		f_TC_egprs_pkt_chan_req(req, imm_ass);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

testcase TC_egprs_pkt_chan_req_one_phase() runs on RAW_PCU_Test_CT {
	var template GsmRrMessage imm_ass;
	var template IaRestOctets rest;
	var template EgprsUlAss ul_ass;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	var EGPRSPktChRequest req := {
		/* NOTE: other fields are set in the loop */
		one_phase := { tag := '0'B }
	};

	for (var integer i := 0; i < 6; i := i + 1) {
		var BIT5 ext_ra := int2bit(f_rnd_int(32), 5);
		var BIT5 mslot_class := int2bit(f_rnd_int(32), 5);
		var BIT2 priority := substr(ext_ra, 0, 2);
		var BIT3 rand := substr(ext_ra, 2, 3);

		req.one_phase.multislot_class := mslot_class;
		req.one_phase.priority := priority;
		req.one_phase.random_bits := rand;

		/* For one phase access, do we expect Dynamic UL TBF Assignment? */
		ul_ass  := tr_EgprsUlAssDynamic(ext_ra := ext_ra);
		rest    := tr_IaRestOctets_EGPRSULAss(ul_ass);
		imm_ass := tr_IMM_TBF_ASS(dl := false, rest := rest);

		f_TC_egprs_pkt_chan_req(req, imm_ass);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

testcase TC_egprs_pkt_chan_req_two_phase() runs on RAW_PCU_Test_CT {
	var template GsmRrMessage imm_ass;
	var template IaRestOctets rest;
	var template EgprsUlAss ul_ass;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	var EGPRSPktChRequest req := {
		/* NOTE: other fields are set in the loop */
		two_phase := { tag := '110000'B }
	};

	for (var integer i := 0; i < 6; i := i + 1) {
		var BIT5 ext_ra := int2bit(f_rnd_int(32), 5);
		var BIT2 priority := substr(ext_ra, 0, 2);
		var BIT3 rand := substr(ext_ra, 2, 3);

		req.two_phase.priority := priority;
		req.two_phase.random_bits := rand;

		/* For two phase access, do we expect Multiblock UL TBF Assignment? */
		ul_ass  := tr_EgprsUlAssMultiblock(ext_ra := ext_ra);
		rest    := tr_IaRestOctets_EGPRSULAss(ul_ass);
		imm_ass := tr_IMM_TBF_ASS(dl := false, rest := rest);

		f_TC_egprs_pkt_chan_req(req, imm_ass);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

private function f_TC_egprs_pkt_chan_req_reject(bitstring ra11, uint32_t fn,
						template IARRestOctets rest := ?,
						PCUIF_BurstType bt := BURST_TYPE_1)
runs on RAW_PCU_Test_CT {
	var template ReqRefWaitInd tr_ref;
	var GsmRrMessage rr_msg;

	/* Send RACH.ind with malformed EGPRS Packet Channel Request */
	BTS.send(ts_PCUIF_RACH_IND(bts_nr := 0, trx_nr := 0, ts_nr := 0,
				   ra := bit2int(ra11), is_11bit := 1,
				   burst_type := bt, fn := fn,
				   arfcn := 871));

	/* Abuse f_pcuif_rx_imm_ass(): wait for Immediate Assignment Reject */
	rr_msg := f_pcuif_rx_imm_ass(t_imm_ass := tr_IMM_ASS_REJ);

	/* Just to have a short-name reference to the actual message */
	var ImmediateAssignmentReject iar := rr_msg.payload.imm_ass_rej;

	/* Make sure that Request Reference list contains at least one entry
	 * with our TDMA frame number, and RA is set to 'reserved' value 127. */
	tr_ref := tr_ReqRefWaitInd(f_compute_ReqRef(127, fn));
	if (not match(iar.payload, { *, tr_ref, * })) {
		setverdict(fail, "Request Reference list does not match");
		f_shutdown(__BFILE__, __LINE__);
	}

	/* Match Feature Indicator (must indicate PS domain) */
	if (not match(iar.feature_ind, FeatureIndicator:{?, false, true})) {
		setverdict(fail, "Feature Indicator does not match");
		f_shutdown(__BFILE__, __LINE__);
	}

	/* Match IAR Rest Octets */
	if (not match(iar.rest_octets, rest)) {
		setverdict(fail, "IAR Rest Octets does not match: ",
			   iar.rest_octets, " vs expected ", rest);
		f_shutdown(__BFILE__, __LINE__);
	}

	setverdict(pass);
}

/* Verify the contents of RR Immediate Assignment Reject message and its
 * Rest Octets sent in response to EGPRS Packet Channel Request (11 bit). */
testcase TC_egprs_pkt_chan_req_reject_content() runs on RAW_PCU_Test_CT {
	var template IARRestOctets rest;
	var BIT5 ext_ra;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	for (var integer i := 0; i < 6; i := i + 1) {
		ext_ra := int2bit(f_rnd_int(32), 5); /* 5 LSB's of RA11 */
		rest := tr_IARRestOctets({ *, tr_ExtRAOpt(ext_ra), * });

		/* Intentionally incorrect message (see table 11.2.5a.2) */
		f_TC_egprs_pkt_chan_req_reject('111111'B & ext_ra, 1337 + i, rest);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* At the moment, the IUT does not support any emergency services. Make sure
 * that EGPRS Packet Channel Request for an emergency call is properly rejected. */
testcase TC_egprs_pkt_chan_req_reject_emergency() runs on RAW_PCU_Test_CT {
	var template IARRestOctets rest;
	var BIT5 ext_ra;
	var BIT11 ra11;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	var EGPRSPktChRequest req := {
		/* NOTE: other fields are set in the loop */
		emergency := { tag := '110111'B }
	};

	for (var integer i := 0; i < 6; i := i + 1) {
		ext_ra := int2bit(f_rnd_int(32), 5); /* 5 LSB's of RA11 */
		rest := tr_IARRestOctets({ *, tr_ExtRAOpt(ext_ra), * });

		req.emergency.random_bits := ext_ra;
		ra11 := enc_EGPRSPktChRequest2bits(req);

		/* Intentionally incorrect message (see table 11.2.5a.2) */
		f_TC_egprs_pkt_chan_req_reject(ra11, 1337 + i, rest);
	}

	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Make sure that IUT responds with RR Immediate Assignment Reject due to exhaustion. */
testcase TC_egprs_pkt_chan_req_reject_exhaustion() runs on RAW_PCU_Test_CT {
	var template IARRestOctets rest;
	var BIT11 ra11;

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename());

	var EGPRSPktChRequest req := {
		one_phase := {
			tag := '0'B,
			multislot_class := '10101'B,
			priority := '01'B,
			random_bits := '101'B
		}
	};

	/* We send 7 requests, the IUT gives us all available USFs (0..6).
	 * TODO: make it configurable: usf_max := mp_pdch_ts_num * 7. */
	for (var integer i := 0; i < 7; i := i + 1) {
		req.one_phase.random_bits := int2bit(f_rnd_int(8), 3);
		f_TC_egprs_pkt_chan_req(req, tr_IMM_TBF_ASS);
	}

	ra11 := enc_EGPRSPktChRequest2bits(req);
	rest := tr_IARRestOctets({ *, tr_ExtRAOpt(substr(ra11, 6, 5)), * });

	/* At this point, the IUT should run out of free USFs */
	f_TC_egprs_pkt_chan_req_reject(ra11, 1870, rest);

	f_shutdown(__BFILE__, __LINE__, final := true);
}

private function f_TC_pcuif_fh_check_imm_ass(in PCUIF_info_ind info_ind,
					     in GsmRrMessage rr_msg)
{
	var ImmediateAssignment ia := rr_msg.payload.imm_ass;
	var PCUIF_InfoTrxTs ts := info_ind.trx.v10[0].ts[ia.pkt_chan_desc.tn];

	var template PacketChannelDescription tr_pkt_chan_desc := {
		channel_Type_spare := ?,
		tn := ?,
		tsc := ts.tsc,
		presence := '1'B,
		zero := omit,
		one := {
			maio := ts.maio,
			hsn := ts.hsn
		}
	};

	if (not match(ia.pkt_chan_desc, tr_pkt_chan_desc)) {
		setverdict(fail, "Packet Channel Description does not match: ",
			   ia.pkt_chan_desc, " vs ", tr_pkt_chan_desc);
	}

	var MobileAllocationLV tr_ma := { len := 0, ma := ''B };
	var octetstring ma_oct := bit2oct(ts.ma);

	/* Calculate length of the useful part of Mobile Allocation */
	for (var integer i := 0; i < lengthof(ma_oct); i := i + 1) {
		if (ma_oct[i] != '00'O) {
			tr_ma.len := i + 1;
		}
	}

	/* Strip zero bytes from the right side of MA */
	tr_ma.ma := substr(ts.ma, 0, tr_ma.len * 8);

	if (not match(ia.mobile_allocation, tr_ma)) {
		setverdict(fail, "Mobile Allocation does not match: ",
			   ia.mobile_allocation, " vs ", tr_ma);
	}

	setverdict(pass);
}

/* Make sure that Immediate (UL EGPRS TBF) Assignment contains hopping parameters */
testcase TC_pcuif_fh_imm_ass_ul_egprs() runs on RAW_PCU_Test_CT {
	var template PCUIF_info_ind info_ind := ts_PCUIF_INFO_default;
	var GprsMS ms := valueof(t_GprsMS_def);

	/* Enable frequency hopping of TRX0/TS7 */
	info_ind.trx.v10[0].ts[7] := ts_PCUIF_InfoTrxTsH1(
		tsc := f_rnd_int(7),
		hsn := f_rnd_int(63),
		maio := f_rnd_int(63),
		ma := f_rnd_bitstring(32));

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename(), info_ind);

	/* EGPRS Packet Channel Request (cause=Signalling) */
	f_ms_use_ra(ms, bit2int('11001101010'B), ra_is_11bit := 1);

	/* Establish an Uplink EGPRS TBF */
	f_ms_establish_ul_tbf(ms);

	f_TC_pcuif_fh_check_imm_ass(valueof(info_ind), ms.ul_tbf.rr_imm_ass);
	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Make sure that Immediate (UL TBF) Assignment contains hopping parameters */
testcase TC_pcuif_fh_imm_ass_ul() runs on RAW_PCU_Test_CT {
	var template PCUIF_info_ind info_ind := ts_PCUIF_INFO_default;
	var GprsMS ms := valueof(t_GprsMS_def);

	/* Enable frequency hopping of TRX0/TS7 */
	info_ind.trx.v10[0].ts[7] := ts_PCUIF_InfoTrxTsH1(
		tsc := f_rnd_int(7),
		hsn := f_rnd_int(63),
		maio := f_rnd_int(63),
		ma := f_rnd_bitstring(32));

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename(), info_ind);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	f_TC_pcuif_fh_check_imm_ass(valueof(info_ind), ms.ul_tbf.rr_imm_ass);
	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Make sure that Immediate (DL TBF) Assignment contains hopping parameters */
testcase TC_pcuif_fh_imm_ass_dl() runs on RAW_PCU_Test_CT {
	var template PCUIF_info_ind info_ind := ts_PCUIF_INFO_default;
	var GprsMS ms := valueof(t_GprsMS_def);

	/* Enable frequency hopping of TRX0/TS7 */
	info_ind.trx.v10[0].ts[7] := ts_PCUIF_InfoTrxTsH1(
		tsc := f_rnd_int(7),
		hsn := f_rnd_int(63),
		maio := f_rnd_int(63),
		ma := f_rnd_bitstring(16));

	/* Initialize NS/BSSGP side */
	f_init_bssgp();

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename(), info_ind);

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* SGSN sends some DL data, PCU will page on CCCH (PCH) */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, f_rnd_octstring(12)));
	f_ms_exp_dl_tbf_ass_ccch(ms, PCU_IF_SAPI_PCH);

	f_TC_pcuif_fh_check_imm_ass(valueof(info_ind), ms.dl_tbf.rr_imm_ass);
	f_shutdown(__BFILE__, __LINE__, final := true);
}

private function f_TC_pcuif_fh_check_pkt_ass(in PCUIF_info_ind info_ind,
					     in FrequencyParameters fp)
{
	/* FIXME: TRX0/TS7 is a hard-coded expectation, make it configurable */
	var PCUIF_InfoTrxTs ts := info_ind.trx.v10[0].ts[7];
	var integer ma_bit_len := 0;

	/* Calculate length of the useful part of Mobile Allocation */
	for (var integer i := 0; i < lengthof(ts.ma); i := i + 1) {
		if (ts.ma[i] == '1'B) {
			ma_bit_len := i + 1;
		}
	}

	/* Table 12.8.1: Frequency Parameters information elements */
	var template FrequencyParameters tr_fp := {
		tsc := ts.tsc,
		presence := '10'B, /* Direct encoding 1 */
		arfcn := omit,
		indirect := omit,
		direct1 := {
			maio := ts.maio,
			/* Table 12.10a.1: GPRS Mobile Allocation information elements */
			mobile_allocation := {
				hsn := ts.hsn,
				rfl_number_list_present := '0'B,
				rfl_number_list := omit,
				ma_present := '0'B, /* inverted logic */
				ma_length := ma_bit_len,
				ma_bitmap := substr(ts.ma, 0, ma_bit_len)
			}
		},
		direct2 := omit
	};

	if (not match(fp, tr_fp)) {
		setverdict(fail, "Frequency Parameters IE does not match: ",
			   fp, " vs ", tr_fp);
	}

	setverdict(pass);
}

/* Make sure that Packet Uplink Assignment contains hopping parameters */
testcase TC_pcuif_fh_pkt_ass_ul() runs on RAW_PCU_Test_CT {
	var template PCUIF_info_ind info_ind := ts_PCUIF_INFO_default;
	var GprsMS ms := valueof(t_GprsMS_def);
	var uint32_t poll_fn;

	/* Enable frequency hopping of TRX0/TS7 */
	info_ind.trx.v10[0].ts[7] := ts_PCUIF_InfoTrxTsH1(
		tsc := f_rnd_int(7),
		hsn := f_rnd_int(63),
		maio := f_rnd_int(63),
		ma := f_rnd_bitstring(33));

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename(), info_ind);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send Packet Resource Request, so the network will allocate an Uplink resource */
	f_ms_tx_ul_block(ms, ts_RLC_UL_CTRL_ACK(ts_RlcMacUlCtrl_PKT_RES_REQ(ms.tlli, omit)));

	/* Expect an RLC/MAC block with Packet Uplink Assignment on PACCH (see 11.2.29) */
	var RlcmacDlBlock blk := f_ms_rx_pkt_ass_pacch(ms, poll_fn, tr_RLCMAC_UL_PACKET_ASS);
	var PacketUlAssignment ua := blk.ctrl.payload.u.ul_assignment;

	/* 3GPP TS 44.060, section 12.8 "Frequency Parameters" */
	var template (omit) FrequencyParameters fp;
	if (ua.is_egprs == '1'B) {
		fp := ua.egprs.freq_par;
	} else {
		fp := ua.gprs.freq_par;
	}

	/* This is an optional IE, so it's worth to check its presence */
	if (istemplatekind(fp, "omit")) {
		setverdict(fail, "Frequency Parameters IE is not present");
		f_shutdown(__BFILE__, __LINE__);
	}

	f_TC_pcuif_fh_check_pkt_ass(valueof(info_ind), valueof(fp));
	f_shutdown(__BFILE__, __LINE__, final := true);
}

/* Make sure that Packet Downlink Assignment contains hopping parameters */
testcase TC_pcuif_fh_pkt_ass_dl() runs on RAW_PCU_Test_CT {
	var template PCUIF_info_ind info_ind := ts_PCUIF_INFO_default;
	var octetstring data := f_rnd_octstring(10);
	var GprsMS ms := valueof(t_GprsMS_def);
	var RlcmacDlBlock dl_block;
	var uint32_t poll_fn;

	/* Enable frequency hopping of TRX0/TS7 */
	info_ind.trx.v10[0].ts[7] := ts_PCUIF_InfoTrxTsH1(
		tsc := f_rnd_int(7),
		hsn := f_rnd_int(63),
		maio := f_rnd_int(63),
		ma := f_rnd_bitstring(33));

	/* Initialize NS/BSSGP side */
	f_init_bssgp();

	/* Initialize the PCU interface abstraction */
	f_init_raw(testcasename(), info_ind);

	/* Establish BSSGP connection to the PCU */
	f_bssgp_establish();
	f_bssgp_client_llgmm_assign('FFFFFFFF'O, ms.tlli);

	/* Establish an Uplink TBF */
	f_ms_establish_ul_tbf(ms);

	/* Send an Uplink block, so this TBF becomes "active" */
	f_ms_tx_ul_data_block(ms, data, with_tlli := true);

	/* DL ACK/NACK sets poll+rrbp requesting PACKET CONTROL ACK */
	f_rx_rlcmac_dl_block_exp_ack_nack(dl_block, poll_fn);
	f_ms_tx_ul_block(ms, ts_RLCMAC_CTRL_ACK(ms.tlli), poll_fn);

	/* SGSN sends some DL data, PCU will assign Downlink resource on PACCH */
	BSSGP[0].send(ts_BSSGP_DL_UD(ms.tlli, data));

	/* Expect an RLC/MAC block with Packet Downlink Assignment on PACCH (see 11.2.29) */
	dl_block := f_ms_rx_pkt_ass_pacch(ms, poll_fn, tr_RLCMAC_DL_PACKET_ASS);
	var PacketDlAssignment da := dl_block.ctrl.payload.u.dl_assignment;

	/* This is an optional IE, so it's worth to check its presence */
	if (not ispresent(da.freq_par)) {
		setverdict(fail, "Frequency Parameters IE is not present");
		f_shutdown(__BFILE__, __LINE__);
	}

	f_TC_pcuif_fh_check_pkt_ass(valueof(info_ind), da.freq_par);
	f_shutdown(__BFILE__, __LINE__, final := true);
}

control {
	execute( TC_pcuif_suspend() );
	execute( TC_ta_ptcch_idle() );
	execute( TC_ta_rach_imm_ass() );
	execute( TC_ta_idle_dl_tbf_ass() );
	execute( TC_ta_ptcch_ul_multi_tbf() );
	execute( TC_cs_lqual_ul_tbf() );
	execute( TC_cs_initial_ul() );
	execute( TC_cs_max_ul() );
	execute( TC_t3169() );
	execute( TC_t3193() );
	execute( TC_countdown_procedure() );
	execute( TC_ul_all_sizes() );
	execute( TC_ul_data_toolong_fills_padding() );
	execute( TC_mo_ping_pong() );
	execute( TC_mo_ping_pong_with_ul_racap() );
	execute( TC_force_two_phase_access() );
	execute( TC_mt_ping_pong() );
	execute( TC_mt_ping_pong_with_dl_racap() );
	execute( TC_ul_intermediate_retrans() );
	execute( TC_imm_ass_dl_block_retrans() );
	execute( TC_dl_flow_more_blocks() );
	execute( TC_ul_flow_multiple_llc_blocks() );
	execute( TC_paging_cs_from_bts() );
	execute( TC_paging_cs_from_sgsn_sign_ptmsi() );
	execute( TC_paging_cs_from_sgsn_sign() );
	execute( TC_paging_cs_from_sgsn_ptp() );
	execute( TC_paging_ps_from_sgsn_sign_ptmsi() );
	execute( TC_paging_ps_from_sgsn_sign() );
	execute( TC_paging_ps_from_sgsn_ptp() );
	execute( TC_bssgp_dl_unitdata_with_valid_imsi() );
	execute( TC_bssgp_dl_unitdata_with_invalid_imsi() );

	/* EGPRS specific test cases */
	execute( TC_egprs_pkt_chan_req_signalling() );
	execute( TC_egprs_pkt_chan_req_one_phase() );
	execute( TC_egprs_pkt_chan_req_two_phase() );
	execute( TC_egprs_pkt_chan_req_reject_content() );
	execute( TC_egprs_pkt_chan_req_reject_emergency() );
	execute( TC_egprs_pkt_chan_req_reject_exhaustion() );

	execute( TC_mo_ping_pong_with_ul_racap_egprs_only() );

	/* Frequency hopping specific test cases */
	if (PCUIF_Types.mp_pcuif_version >= 10) {
		/* Immediate Assignment on AGCH/PCH */
		execute( TC_pcuif_fh_imm_ass_ul_egprs() );
		execute( TC_pcuif_fh_imm_ass_ul() );
		execute( TC_pcuif_fh_imm_ass_dl() );
		/* Packet Uplink/Downlink Assignment on PACCH */
		execute( TC_pcuif_fh_pkt_ass_ul() );
		execute( TC_pcuif_fh_pkt_ass_dl() );
	}
}






}
