WIP: Support ANR procedures on MS with active TBF

TODO:
* General clean up
* Find out and fix why MS not resetting Neighbour List to BA(GPRS) when
  empty NC_Frequency_List is sent in Packet Measurement Order.
* Fix MS most of the time not sending Neighbour report for cells not
  present in SI2, probably due to waiting not enough time (increasing
  NC_REPORTING_PERIOD_T may help, but then problem in previous point above
  may show up more). Also maybe waiting for several reports before
  continuing may also help.
* Configurable/dynamic chunk list size currently hardcoded to 5.

Improvements/optimizations:
* Use FREQUENCY_DIFF in Add_Frequency for NC_Frequency_List to make
  it smaller and hence require less PAcketMeasurementOrder messages.
* Support Enchanced Packet Report message (need to signal support for it
  too).

Related: SYS#5303
Change-Id: I051d4fa90fe4ccc44ea691f8a3a487e97868e52c
diff --git a/include/osmocom/pcu/pcuif_proto.h b/include/osmocom/pcu/pcuif_proto.h
index 23b7a2c..94b9b07 100644
--- a/include/osmocom/pcu/pcuif_proto.h
+++ b/include/osmocom/pcu/pcuif_proto.h
@@ -26,6 +26,10 @@
 #define PCU_IF_MSG_TXT_IND	0x70	/* Text indication for BTS */
 #define PCU_IF_MSG_CONTAINER	0x80	/* Transparent container message */
 
+/* msg_type coming from BSC (inside PCU_IF_MSG_CONTAINER) */
+#define PCU_IF_MSG_ANR_REQ	0x81	/* Automatic Neighbor Registration Request */
+#define PCU_IF_MSG_ANR_CNF	0x82	/* Automatic Neighbor Registration Confirmation (meas results) */
+
 /* sapi */
 #define PCU_IF_SAPI_RACH	0x01	/* channel request on CCCH */
 #define PCU_IF_SAPI_AGCH	0x02	/* assignment on AGCH */
@@ -228,6 +232,19 @@
 	uint8_t		data[0];
 } __attribute__ ((packed));
 
+/* Used inside container: */
+struct gsm_pcu_if_anr_req {
+	uint8_t		num_cells;
+	uint16_t	cell_list[96];  /* struct gsm48_cell_desc */
+} __attribute__ ((packed));
+
+/* PCU confirms back with measurements of target cells */
+struct gsm_pcu_if_anr_cnf {
+	uint8_t		num_cells;
+	uint16_t	cell_list[32];  /* struct gsm48_cell_desc */
+	uint8_t		rxlev_list[32]; /* value 0xff: invalid */
+} __attribute__ ((packed));
+
 struct gsm_pcu_if {
 	/* context based information */
 	uint8_t		msg_type;	/* message type */
diff --git a/src/Makefile.am b/src/Makefile.am
index 8070fda..699a180 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -62,6 +62,8 @@
 	tbf_ul.cpp \
 	tbf_dl.cpp \
 	bts.cpp \
+	bts_anr_fsm.c \
+	ms_anr_fsm.c \
 	pdch.cpp \
 	pdch_ul_controller.c \
 	encoding.cpp \
@@ -101,6 +103,8 @@
 	tbf_ul.h \
 	tbf_dl.h \
 	bts.h \
+	bts_anr_fsm.h \
+	ms_anr_fsm.h \
 	pdch.h \
 	pdch_ul_controller.h \
 	encoding.h \
diff --git a/src/bts.cpp b/src/bts.cpp
index 95dde04..30037bc 100644
--- a/src/bts.cpp
+++ b/src/bts.cpp
@@ -148,6 +148,7 @@
 	{ "pkt:cell_chg_notification",	"Packet Cell Change Notification"},
 	{ "pkt:cell_chg_continue",	"Packet Cell Change Continue"},
 	{ "pkt:neigh_cell_data",	"Packet Neighbour Cell Data"},
+	{ "pkt:meas_order", 		"Packet Measurement Order" },
 	{ "ul:control",			"UL control Block     "},
 	{ "ul:assignment_poll_timeout",	"UL Assign Timeout    "},
 	{ "ul:assignment_failed",	"UL Assign Failed     "},
@@ -280,6 +281,8 @@
 	bts->statg = osmo_stat_item_group_alloc(tall_pcu_ctx, &bts_statg_desc, 0);
 	OSMO_ASSERT(bts->statg);
 
+	bts->anr = bts_anr_fsm_alloc(bts);
+
 	llist_add_tail(&bts->list, &pcu->bts_list);
 
 	return bts;
diff --git a/src/bts.h b/src/bts.h
index a2f4598..d742c60 100644
--- a/src/bts.h
+++ b/src/bts.h
@@ -40,6 +40,7 @@
 #include "mslot_class.h"
 #include "gsm_rlcmac.h"
 #include "gprs_pcu.h"
+#include "bts_anr_fsm.h"
 #ifdef __cplusplus
 }
 #endif
@@ -141,6 +142,7 @@
 	CTR_PKT_CELL_CHG_NOTIFICATION,
 	CTR_PKT_CELL_CHG_CONTINUE,
 	CTR_PKT_NEIGH_CELL_DATA,
+	CTR_PKT_MEAS_ORDER,
 	CTR_RLC_RECV_CONTROL,
 	CTR_PUA_POLL_TIMEDOUT,
 	CTR_PUA_POLL_FAILED,
@@ -262,6 +264,8 @@
 	struct osmo_stat_item_group *statg;
 
 	struct GprsMsStorage *ms_store;
+
+	struct bts_anr_fsm_ctx *anr;
 };
 
 #ifdef __cplusplus
diff --git a/src/bts_anr_fsm.c b/src/bts_anr_fsm.c
new file mode 100644
index 0000000..c8ef8af
--- /dev/null
+++ b/src/bts_anr_fsm.c
@@ -0,0 +1,388 @@
+/* bts_anr_fsm.c
+ *
+ * Copyright (C) 2021 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
+ * Author: Pau Espin Pedrol <pespin@sysmocom.de>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+
+#include <unistd.h>
+
+#include <talloc.h>
+
+#include <osmocom/core/rate_ctr.h>
+#include <osmocom/ctrl/control_cmd.h>
+#include <osmocom/ctrl/control_if.h>
+
+#include <osmocom/gsm/gsm48.h>
+#include <osmocom/gprs/gprs_bssgp.h>
+#include <osmocom/gprs/gprs_bssgp_rim.h>
+
+#include <bts_anr_fsm.h>
+#include <ms_anr_fsm.h>
+#include <gprs_rlcmac.h>
+#include <gprs_debug.h>
+#include <gprs_ms.h>
+#include <encoding.h>
+#include <bts.h>
+#include <neigh_cache.h>
+
+#define X(s) (1 << (s))
+
+/* Ask the MS to measure up to 5 neighbors at a time */
+#define ANR_MAX_NEIGH_SUBSET 5
+
+static const struct osmo_tdef_state_timeout bts_anr_fsm_timeouts[32] = {
+	[BTS_ANR_ST_DISABLED] = {},
+	[BTS_ANR_ST_ENABLED] = { .T = PCU_TDEF_ANR_SCHED_TBF },
+};
+
+/* Transition to a state, using the T timer defined in assignment_fsm_timeouts.
+ * The actual timeout value is in turn obtained from conn->T_defs.
+ * Assumes local variable fi exists. */
+
+#define bts_anr_fsm_state_chg(fi, NEXT_STATE) \
+	osmo_tdef_fsm_inst_state_chg(fi, NEXT_STATE, \
+				     bts_anr_fsm_timeouts, \
+				     ((struct bts_anr_fsm_ctx*)(fi->priv))->bts->pcu->T_defs, \
+				     -1)
+
+const struct value_string bts_anr_fsm_event_names[] = {
+	{ BTS_ANR_EV_RX_ANR_REQ, "RX_ANR_REQ" },
+	{ BTS_ANR_EV_SCHED_MS_MEAS, "SCHED_MS_MEAS" },
+	{ BTS_ANR_EV_MS_MEAS_COMPL, "MS_MEAS_COMPL" },
+	{ BTS_ANR_EV_MS_MEAS_ABORTED, "MS_MEAS_ABORTED" },
+	{ 0, NULL }
+};
+
+static void copy_sort_arfcn_bsic(struct bts_anr_fsm_ctx *ctx, const struct gsm48_cell_desc *cell_list, unsigned int num_cells)
+{
+	OSMO_ASSERT(num_cells <= ARRAY_SIZE(ctx->cell_list));
+	uint16_t last_min_arfcn = 0;
+	uint8_t last_min_bsic = 0;
+	ctx->num_cells = 0;
+	struct gprs_rlcmac_bts *bts = ctx->bts;
+
+	/* Copy over ARFCN+BSIC in an ARFCN then BSIC ascending ordered way */
+	while (ctx->num_cells < num_cells) {
+		bool found = false;
+		uint16_t curr_min_arfcn = 0xffff;
+		uint8_t curr_min_bsic = 0xff;
+		int i;
+		for (i = 0; i < num_cells; i++) {
+			uint16_t arfcn = (cell_list[i].arfcn_hi << 8) | cell_list[i].arfcn_lo;
+			uint8_t bsic = (cell_list[i].ncc << 3) | cell_list[i].bcc;
+			if ((arfcn > last_min_arfcn || (arfcn == last_min_arfcn && bsic > last_min_bsic)) &&
+			    (arfcn < curr_min_arfcn || (arfcn == curr_min_arfcn && bsic < curr_min_bsic))) {
+				found = true;
+				curr_min_arfcn = arfcn;
+				curr_min_bsic = bsic;
+			}
+		}
+		if (!found)
+			break; /* we are done before copying all, probably due to duplicated arfcn in list */
+
+		/* Copy lower ARFCN+BSIC to dst */
+		if (curr_min_arfcn != bts->trx[0].arfcn || curr_min_bsic != bts->bsic) {
+			ctx->cell_list[ctx->num_cells] = (struct arfcn_bsic){
+				.arfcn = curr_min_arfcn,
+				.bsic =  curr_min_bsic,
+			};
+			ctx->num_cells++;
+			LOGPFSML(ctx->fi, LOGL_DEBUG, "Added neigh cell to ANR list: ARFCN=%u BSIC=%u\n",
+				 curr_min_arfcn, curr_min_bsic);
+		} else {
+			LOGPFSML(ctx->fi, LOGL_DEBUG, "Skip neigh cell to ANR list (itself): ARFCN=%u BSIC=%u\n",
+				 curr_min_arfcn, curr_min_bsic);
+		}
+		last_min_arfcn = curr_min_arfcn;
+		last_min_bsic = curr_min_bsic;
+	}
+}
+
+static void rx_new_cell_list(struct bts_anr_fsm_ctx *ctx, const struct gsm_pcu_if_anr_req *anr_req)
+{
+	unsigned int num_cells = anr_req->num_cells;
+	if (anr_req->num_cells > ARRAY_SIZE(anr_req->cell_list)) {
+		LOGPFSML(ctx->fi, LOGL_ERROR, "Too many cells received %u > %zu (max), trimming it\n",
+			 anr_req->num_cells, ARRAY_SIZE(anr_req->cell_list));
+		num_cells = ARRAY_SIZE(anr_req->cell_list);
+	}
+	copy_sort_arfcn_bsic(ctx, (const struct gsm48_cell_desc *)anr_req->cell_list, num_cells);
+}
+
+static struct GprsMs *select_candidate_ms(struct gprs_rlcmac_bts *bts)
+{
+	struct llist_head *tmp;
+	/* prio top to bottom: 0,1,2: */
+	struct GprsMs *ms_dl_tbf_assign = NULL;
+
+	/* We'll need a DL TBF. Take with higher priority an MS which already
+	 * has one, otherwise one in process of acquiring one. In last place an
+	 * MS which has no DL-TBF yet. */
+	llist_for_each(tmp, bts_ms_list(bts)) {
+		struct GprsMs *ms = llist_entry(tmp, typeof(*ms), list);
+		if (ms->anr) /* Don't pick MS already busy doing ANR */
+			continue;
+		if (!ms->dl_tbf)
+			continue;
+		switch (tbf_state((struct gprs_rlcmac_tbf*)ms->dl_tbf)) {
+		case TBF_ST_FLOW: /* Pick active DL-TBF as best option, early return: */
+			return ms;
+		case TBF_ST_ASSIGN:
+			ms_dl_tbf_assign = ms;
+			break;
+		default:
+			continue;
+		}
+	}
+
+	if (ms_dl_tbf_assign)
+		return ms_dl_tbf_assign;
+
+	llist_for_each(tmp, bts_ms_list(bts)) {
+		struct GprsMs *ms = llist_entry(tmp, typeof(*ms), list);
+		if (ms->anr) /* Don't pick MS already busy doing ANR */
+			continue;
+		if (!ms->dl_tbf) {
+			/* Trigger a Pkt Dl Assignment and do ANR procedure once it is active: */
+			struct gprs_rlcmac_dl_tbf *new_dl_tbf;
+			int rc;
+			rc = tbf_new_dl_assignment(ms->bts, ms, &new_dl_tbf);
+			if (rc < 0)
+				continue;
+			/* Fill the TBF with some LLC Dummy Command, since everyone expectes we send something to that DL TBF... */
+			uint16_t delay_csec = 0xffff;
+			/* The shortest dummy command (the spec requests at least 6 octets) */
+			const uint8_t llc_dummy_command[] = {
+			0x43, 0xc0, 0x01, 0x2b, 0x2b, 0x2b
+			};
+			dl_tbf_append_data(new_dl_tbf, delay_csec, &llc_dummy_command[0], ARRAY_SIZE(llc_dummy_command));
+			return ms;
+		}
+	}
+	return NULL;
+}
+
+/* Build up cell list subset for this MS to measure: */
+static size_t take_next_cell_list_chunk(struct bts_anr_fsm_ctx *ctx, struct arfcn_bsic ms_cell_li[MAX_NEIGH_LIST_LEN])
+{
+	unsigned int subset_len = ANR_MAX_NEIGH_SUBSET;
+	if (ctx->num_cells <= subset_len) {
+		memcpy(ms_cell_li, ctx->cell_list, ctx->num_cells * sizeof(ctx->cell_list[0]));
+		subset_len = ctx->num_cells;
+	} else if ((ctx->num_cells - ctx->next_cell) >= subset_len) {
+		memcpy(ms_cell_li, &ctx->cell_list[ctx->next_cell], subset_len * sizeof(ctx->cell_list[0]));
+		ctx->next_cell = (ctx->next_cell + subset_len) % ctx->num_cells;
+	} else {
+		unsigned int len = (ctx->num_cells - ctx->next_cell);
+		memcpy(ms_cell_li, &ctx->cell_list[ctx->next_cell], len * sizeof(ctx->cell_list[0]));
+		memcpy(&ms_cell_li[len], &ctx->cell_list[0], subset_len - len);
+		ctx->next_cell = subset_len - len;
+	}
+	return subset_len;
+}
+
+static void sched_ms_meas_report(struct bts_anr_fsm_ctx *ctx, const struct arfcn_bsic* cell_list,
+				unsigned int num_cells)
+{
+	struct gprs_rlcmac_bts *bts = ctx->bts;
+	struct GprsMs *ms;
+	struct arfcn_bsic ms_cell_li[MAX_NEIGH_LIST_LEN];
+	/* HERE we'll:
+	 * 1- Select a TBF candidate in the BTS
+	 * 2- Pick a subset from ctx->cell_list (increasing index round buffer in array)
+	 * 3- Send event to it to schedule the meas report [osmo_fsm_inst_dispatch(ms->meas_rep_fsm, MEAS_REP_EV_SCHEDULE, cell_sublist)]
+	 * 4- Wait for event BTS_ANR_EV_MEAS_REP containing "Packet Measurement Report" as data
+	 * 5- Filter out the list and submit it back over PCUIF */
+
+	/* First poor-man impl: pick first MS having a FLOW TBF: */
+	ms = select_candidate_ms(bts);
+	if (!ms) {
+		LOGPFSML(ctx->fi, LOGL_INFO, "Unable to find MS to start ANR measurements\n");
+		return;
+	}
+	LOGPMS(ms, DANR, LOGL_DEBUG, "Selected for ANR measurements\n");
+
+	/* Build up cell list subset for this MS to measure: */
+	if (!cell_list) {
+		num_cells = take_next_cell_list_chunk(ctx, &ms_cell_li[0]);
+		cell_list = &ms_cell_li[0];
+	}
+
+	if (ms_anr_start(ms, cell_list, num_cells) < 0)
+		LOGPFSML(ctx->fi, LOGL_ERROR, "Unable to start ANR measurements on MS\n");
+}
+
+static void handle_ms_meas_report(struct bts_anr_fsm_ctx *ctx, const struct ms_anr_ev_meas_compl* result)
+{
+	struct gprs_rlcmac_bts *bts = ctx->bts;
+	pcu_tx_anr_cnf(bts, result->cell_list, result->meas_list, result->num_cells);
+}
+
+////////////////
+// FSM states //
+////////////////
+
+static void st_disabled_on_enter(struct osmo_fsm_inst *fi, uint32_t prev_state)
+{
+	struct bts_anr_fsm_ctx *ctx = (struct bts_anr_fsm_ctx *)fi->priv;
+	struct llist_head *tmp;
+
+	/* Abort ongoing scheduled ms_anr_fsm: */
+	llist_for_each(tmp, bts_ms_list(ctx->bts)) {
+		struct GprsMs *ms = llist_entry(tmp, typeof(*ms), list);
+		/* Remark: ms_anr_fsm_abort does NOT send BTS_ANR_EV_MS_MEAS_ABORTED back at us */
+		if (ms->anr)
+			ms_anr_fsm_abort(ms->anr);
+	}
+}
+
+static void st_disabled(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct bts_anr_fsm_ctx *ctx = (struct bts_anr_fsm_ctx *)fi->priv;
+	const struct gsm_pcu_if_anr_req *anr_req;
+
+	switch (event) {
+	case BTS_ANR_EV_RX_ANR_REQ:
+		anr_req = (const struct gsm_pcu_if_anr_req *)data;
+		rx_new_cell_list(ctx, anr_req);
+		if (ctx->num_cells > 0)
+			bts_anr_fsm_state_chg(fi, BTS_ANR_ST_ENABLED);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_enabled_on_enter(struct osmo_fsm_inst *fi, uint32_t prev_state)
+{
+	struct bts_anr_fsm_ctx *ctx = (struct bts_anr_fsm_ctx *)fi->priv;
+	sched_ms_meas_report(ctx, NULL, 0);
+}
+
+static void st_enabled(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct bts_anr_fsm_ctx *ctx = (struct bts_anr_fsm_ctx *)fi->priv;
+	const struct gsm_pcu_if_anr_req *anr_req;
+	struct ms_anr_ev_abort *ev_abort_data;
+
+	switch (event) {
+	case BTS_ANR_EV_RX_ANR_REQ:
+		anr_req = (const struct gsm_pcu_if_anr_req *)data;
+		rx_new_cell_list(ctx, anr_req);
+		if (ctx->num_cells == 0)
+			bts_anr_fsm_state_chg(fi, BTS_ANR_ST_DISABLED);
+		break;
+	case BTS_ANR_EV_SCHED_MS_MEAS:
+		sched_ms_meas_report(ctx, NULL, 0);
+		break;
+	case BTS_ANR_EV_MS_MEAS_ABORTED:
+		ev_abort_data = (struct ms_anr_ev_abort*)data;
+		sched_ms_meas_report(ctx, ev_abort_data->cell_list, ev_abort_data->num_cells);
+		break;
+	case BTS_ANR_EV_MS_MEAS_COMPL:
+		handle_ms_meas_report(ctx, (const struct ms_anr_ev_meas_compl*)data);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+/*TODO: we need to track how many chunks are created, how many are in progress, how many are completed, etc. */
+static int bts_anr_fsm_timer_cb(struct osmo_fsm_inst *fi)
+{
+	unsigned long timeout;
+
+	switch (fi->T) {
+	case PCU_TDEF_ANR_SCHED_TBF:
+		/* Re-schedule the timer */
+		timeout = osmo_tdef_get(((struct bts_anr_fsm_ctx*)(fi->priv))->bts->pcu->T_defs,
+					fi->T, OSMO_TDEF_S, -1);
+		osmo_timer_schedule(&fi->timer, timeout, 0);
+		/* Dispatch the schedule TBF MEAS event */
+		osmo_fsm_inst_dispatch(fi, BTS_ANR_EV_SCHED_MS_MEAS, NULL);
+		break;
+	}
+	return 0;
+}
+
+static struct osmo_fsm_state bts_anr_fsm_states[] = {
+	[BTS_ANR_ST_DISABLED] = {
+		.in_event_mask =
+			X(BTS_ANR_EV_RX_ANR_REQ),
+		.out_state_mask =
+			X(BTS_ANR_ST_ENABLED),
+		.name = "DISABLED",
+		.onenter = st_disabled_on_enter,
+		.action = st_disabled,
+	},
+	[BTS_ANR_ST_ENABLED] = {
+		.in_event_mask =
+			X(BTS_ANR_EV_RX_ANR_REQ) |
+			X(BTS_ANR_EV_SCHED_MS_MEAS) |
+			X(BTS_ANR_EV_MS_MEAS_COMPL) |
+			X(BTS_ANR_EV_MS_MEAS_ABORTED),
+		.out_state_mask =
+			X(BTS_ANR_ST_DISABLED),
+		.name = "ENABLED",
+		.onenter = st_enabled_on_enter,
+		.action = st_enabled,
+	},
+};
+
+static struct osmo_fsm bts_anr_fsm = {
+	.name = "BTS_ANR",
+	.states = bts_anr_fsm_states,
+	.num_states = ARRAY_SIZE(bts_anr_fsm_states),
+	.timer_cb = bts_anr_fsm_timer_cb,
+	.log_subsys = DANR,
+	.event_names = bts_anr_fsm_event_names,
+};
+
+static __attribute__((constructor)) void bts_anr_fsm_init(void)
+{
+	OSMO_ASSERT(osmo_fsm_register(&bts_anr_fsm) == 0);
+}
+
+static int bts_anr_fsm_ctx_talloc_destructor(struct bts_anr_fsm_ctx *ctx)
+{
+	if (ctx->fi) {
+		osmo_fsm_inst_free(ctx->fi);
+		ctx->fi = NULL;
+	}
+
+	return 0;
+}
+
+struct bts_anr_fsm_ctx *bts_anr_fsm_alloc(struct gprs_rlcmac_bts* bts)
+{
+	struct bts_anr_fsm_ctx *ctx = talloc_zero(bts, struct bts_anr_fsm_ctx);
+	char buf[64];
+
+	talloc_set_destructor(ctx, bts_anr_fsm_ctx_talloc_destructor);
+
+	ctx->bts = bts;
+
+	snprintf(buf, sizeof(buf), "BTS-%u", bts->nr);
+	ctx->fi = osmo_fsm_inst_alloc(&bts_anr_fsm, ctx, ctx, LOGL_INFO, buf);
+	if (!ctx->fi)
+		goto free_ret;
+
+	return ctx;
+free_ret:
+	talloc_free(ctx);
+	return NULL;
+}
diff --git a/src/bts_anr_fsm.h b/src/bts_anr_fsm.h
new file mode 100644
index 0000000..36726ed
--- /dev/null
+++ b/src/bts_anr_fsm.h
@@ -0,0 +1,65 @@
+/* bts_anr_fsm.h
+ *
+ * Copyright (C) 2021 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
+ * Author: Pau Espin Pedrol <pespin@sysmocom.de>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+#pragma once
+
+#include <osmocom/core/fsm.h>
+#include <osmocom/gsm/gsm23003.h>
+
+#include <pcu_utils.h>
+
+#define MAX_NEIGH_LIST_LEN 96
+
+struct gprs_rlcmac_bts;
+
+enum bts_anr_fsm_event {
+	BTS_ANR_EV_RX_ANR_REQ, /* data: struct gsm_pcu_if_anr_req* */
+	BTS_ANR_EV_SCHED_MS_MEAS,
+	BTS_ANR_EV_MS_MEAS_COMPL, /* data: struct ms_anr_ev_meas_compl* */
+	BTS_ANR_EV_MS_MEAS_ABORTED, /* data: struct ms_anr_ev_meas_abort* */
+};
+
+enum bts_anr_fsm_states {
+	BTS_ANR_ST_DISABLED,
+	BTS_ANR_ST_ENABLED
+};
+
+struct bts_anr_fsm_ctx {
+	struct osmo_fsm_inst *fi;
+	struct gprs_rlcmac_bts *bts; /* back pointer */
+	struct arfcn_bsic cell_list[MAX_NEIGH_LIST_LEN]; /* ordered by ascending ARFCN */
+	unsigned int num_cells;
+	unsigned int next_cell; /* Next cell list subset starts from this index */
+};
+
+/* passed as data in BTS_ANR_EV_MS_MEAS_COMPL */
+
+struct ms_anr_ev_meas_compl {
+	const struct arfcn_bsic *cell_list; /* len() = num_cells */
+	const uint8_t *meas_list; /* len() = num_cells, value 0xff means invalid */
+	unsigned int num_cells;
+};
+
+/* passed as data in BTS_ANR_EV_MS_MEAS_ABORT */
+struct ms_anr_ev_abort {
+	const struct arfcn_bsic* cell_list;
+	unsigned int num_cells;
+};
+
+struct bts_anr_fsm_ctx *bts_anr_fsm_alloc(struct gprs_rlcmac_bts* bts);
diff --git a/src/encoding.cpp b/src/encoding.cpp
index 0a4050f..3ece292 100644
--- a/src/encoding.cpp
+++ b/src/encoding.cpp
@@ -1815,3 +1815,46 @@
 	}
 	block->u.Packet_Cell_Change_Continue.CONTAINER_ID = container_id;
 }
+
+void write_packet_measurement_order(RlcMacDownlink_t *block, uint8_t poll, uint8_t rrbp,
+				    bool tfi_assigned, bool tfi_is_dl, uint8_t tfi,
+				    uint32_t tlli, uint8_t pmo_idx, uint8_t pmo_count,
+				    uint8_t nco, bool exist_nc, uint8_t non_drx_period,
+				    uint8_t nc_report_period_i, uint8_t nc_report_period_t,
+				    const NC_Frequency_list_t *NC_Frequency_list)
+{
+
+	block->PAYLOAD_TYPE = 0x1;  // RLC/MAC control block that does not include the optional octets of the RLC/MAC control header
+	block->RRBP         = rrbp;  // 0: N+13
+	block->SP           = poll; // RRBP field is valid?
+	block->USF          = 0x0;  // Uplink state flag
+
+	block->u.Packet_Measurement_Order.MESSAGE_TYPE = MT_PACKET_MEASUREMENT_ORDER;
+	block->u.Packet_Measurement_Order.PAGE_MODE    = 0x0;  // Normal Paging
+
+	if (!tfi_assigned) {
+		block->u.Packet_Measurement_Order.ID.UnionType = 0x01; // TLLI
+		block->u.Packet_Measurement_Order.ID.u.TLLI = tlli;
+	} else {
+		block->u.Packet_Measurement_Order.ID.UnionType = 0x00; // Global_TFI
+		block->u.Packet_Measurement_Order.ID.u.Global_TFI.UnionType = tfi_is_dl; // 0=UPLINK TFI, 1=DL TFI
+		if (tfi_is_dl)
+			block->u.Packet_Measurement_Order.ID.u.Global_TFI.u.DOWNLINK_TFI = tfi;
+		else
+			block->u.Packet_Measurement_Order.ID.u.Global_TFI.u.UPLINK_TFI = tfi;
+	}
+	block->u.Packet_Measurement_Order.PMO_INDEX = pmo_idx;
+	block->u.Packet_Measurement_Order.PMO_COUNT = pmo_count;
+	block->u.Packet_Measurement_Order.Exist_NC_Measurement_Parameters = 1;
+
+	block->u.Packet_Measurement_Order.NC_Measurement_Parameters.NETWORK_CONTROL_ORDER = nco;
+	block->u.Packet_Measurement_Order.NC_Measurement_Parameters.Exist_NC = exist_nc;
+	if (exist_nc) {
+		block->u.Packet_Measurement_Order.NC_Measurement_Parameters.NC_NON_DRX_PERIOD = non_drx_period;
+		block->u.Packet_Measurement_Order.NC_Measurement_Parameters.NC_REPORTING_PERIOD_I = nc_report_period_i;
+		block->u.Packet_Measurement_Order.NC_Measurement_Parameters.NC_REPORTING_PERIOD_T = nc_report_period_t;
+	}
+	block->u.Packet_Measurement_Order.NC_Measurement_Parameters.Exist_NC_FREQUENCY_LIST = NC_Frequency_list ? 1 : 0;
+	if (NC_Frequency_list)
+		block->u.Packet_Measurement_Order.NC_Measurement_Parameters.NC_Frequency_list = *NC_Frequency_list;
+}
diff --git a/src/encoding.h b/src/encoding.h
index 665bd77..1b579b2 100644
--- a/src/encoding.h
+++ b/src/encoding.h
@@ -129,6 +129,13 @@
 				       bool tfi_is_dl, uint8_t tfi, bool exist_id,
 				       uint16_t arfcn, uint8_t bsic, uint8_t container_id);
 
+void write_packet_measurement_order(RlcMacDownlink_t *block, uint8_t poll, uint8_t rrbp,
+				    bool tfi_assigned, bool tfi_is_dl, uint8_t tfi,
+				    uint32_t tlli, uint8_t pmo_idx, uint8_t pmo_count,
+				    uint8_t nco, bool exist_nc, uint8_t non_drx_period,
+				    uint8_t nc_report_period_i, uint8_t nc_report_period_t,
+				    const NC_Frequency_list_t *NC_Frequency_list);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/src/gprs_debug.cpp b/src/gprs_debug.cpp
index 0cbc488..90af621 100644
--- a/src/gprs_debug.cpp
+++ b/src/gprs_debug.cpp
@@ -133,6 +133,13 @@
 		.loglevel = LOGL_NOTICE,
 		.enabled = 1,
 	},
+	[DANR] = {
+		.name = "DANR",
+		.color = "\033[1;37m",
+		.description = "Automatic Neighbor Registration (ANR)",
+		.loglevel = LOGL_NOTICE,
+		.enabled = 1,
+	},
 };
 
 static int filter_fn(const struct log_context *ctx,
diff --git a/src/gprs_debug.h b/src/gprs_debug.h
index cebeabc..c6e5dea 100644
--- a/src/gprs_debug.h
+++ b/src/gprs_debug.h
@@ -48,6 +48,7 @@
 	DPCU,
 	DNACC,
 	DRIM,
+	DANR,
 	aDebug_LastEntry
 };
 
diff --git a/src/gprs_ms.c b/src/gprs_ms.c
index 0d6be4d..ce9a2df 100644
--- a/src/gprs_ms.c
+++ b/src/gprs_ms.c
@@ -27,6 +27,7 @@
 #include "gprs_codel.h"
 #include "pcu_utils.h"
 #include "nacc_fsm.h"
+#include "ms_anr_fsm.h"
 
 #include <time.h>
 
@@ -368,6 +369,12 @@
 	LOGPMS(ms, DRLCMAC, LOGL_INFO, "Detaching TBF: %s\n",
 	       tbf_name(tbf));
 
+	if (ms->anr && ms->anr->tbf == tbf) {
+		/* TODO: restart it on the other dir tbf if still avaialble? */
+		talloc_free(ms->anr);
+		ms->anr = NULL;
+	}
+
 	if (tbf_ms(tbf) == ms)
 		tbf_set_ms(tbf, NULL);
 
@@ -974,3 +981,60 @@
 		return NULL;
 	return data_ctx.msg;
 }
+
+int ms_anr_start(struct GprsMs *ms, const struct arfcn_bsic* cell_list, unsigned int num_cells)
+{
+	if (!ms->anr)
+		ms->anr = ms_anr_fsm_alloc(ms);
+	if (!ms->anr)
+		return -EINVAL;
+	struct ms_anr_ev_start ev_data = {
+		.tbf = (struct gprs_rlcmac_tbf*) ms->dl_tbf,
+		.cell_list = cell_list,
+		.num_cells = num_cells,
+	};
+	return osmo_fsm_inst_dispatch(ms->anr->fi, MS_ANR_EV_START, &ev_data);
+}
+
+bool ms_anr_rts(const struct GprsMs *ms, struct gprs_rlcmac_tbf *tbf)
+{
+	if (!ms->anr)
+		return false;
+	if (ms->anr->fi->state != MS_ANR_ST_TX_PKT_MEAS_ORDER &&
+	    ms->anr->fi->state != MS_ANR_ST_TX_PKT_MEAS_RESET1 &&
+	    ms->anr->fi->state != MS_ANR_ST_TX_PKT_MEAS_RESET2)
+		return false;
+	/* If TBF doesn't match, skip */
+	if (ms->anr->tbf && ms->anr->tbf != tbf)
+		return false;
+	/* Wait until TBF is in state FLOW to start transmitting ANR */
+	if (tbf_state((struct gprs_rlcmac_tbf*)ms->dl_tbf) != TBF_ST_FLOW)
+		return false;
+	return true;
+}
+
+struct msgb *ms_anr_create_rlcmac_msg(struct GprsMs *ms, struct gprs_rlcmac_tbf *tbf, uint32_t fn, uint8_t ts)
+{
+	int rc;
+	struct ms_anr_ev_create_rlcmac_msg_ctx data_ctx;
+	OSMO_ASSERT(ms->anr->tbf == tbf);
+
+	data_ctx = (struct ms_anr_ev_create_rlcmac_msg_ctx) {
+			//.tbf = tbf,
+			.fn = fn,
+			.ts = ts,
+			.msg = NULL,
+	};
+
+	rc = osmo_fsm_inst_dispatch(ms->anr->fi, MS_ANR_EV_CREATE_RLCMAC_MSG, &data_ctx);
+	if (rc != 0 || !data_ctx.msg)
+		return NULL;
+	return data_ctx.msg;
+}
+
+bool ms_anr_tbf_keep_open(const struct GprsMs *ms, const struct gprs_rlcmac_tbf *tbf)
+{
+	if (ms->anr && ms->anr->tbf == tbf)
+		return true;
+	return false;
+}
diff --git a/src/gprs_ms.h b/src/gprs_ms.h
index 4438a4c..5e2c74e 100644
--- a/src/gprs_ms.h
+++ b/src/gprs_ms.h
@@ -41,6 +41,7 @@
 
 #include "coding_scheme.h"
 #include <gsm_rlcmac.h>
+#include "pcu_utils.h"
 
 #include <stdint.h>
 #include <stddef.h>
@@ -102,6 +103,7 @@
 
 	struct rate_ctr_group *ctrs;
 	struct nacc_fsm_ctx *nacc;
+	struct ms_anr_fsm_ctx *anr;
 };
 
 struct GprsMs *ms_alloc(struct gprs_rlcmac_bts *bts, uint32_t tlli);
@@ -146,6 +148,11 @@
 bool ms_nacc_rts(const struct GprsMs *ms);
 struct msgb *ms_nacc_create_rlcmac_msg(struct GprsMs *ms, struct gprs_rlcmac_tbf *tbf, uint32_t fn, uint8_t ts);
 
+int ms_anr_start(struct GprsMs *ms, const struct arfcn_bsic* cell_list, unsigned int num_cells);
+bool ms_anr_rts(const struct GprsMs *ms, struct gprs_rlcmac_tbf *tbf);
+struct msgb *ms_anr_create_rlcmac_msg(struct GprsMs *ms, struct gprs_rlcmac_tbf *tbf, uint32_t fn, uint8_t ts);
+bool ms_anr_tbf_keep_open(const struct GprsMs *ms, const struct gprs_rlcmac_tbf *tbf);
+
 static inline bool ms_is_idle(const struct GprsMs *ms)
 {
 	return !ms->ul_tbf && !ms->dl_tbf && !ms->ref && llist_empty(&ms->old_tbfs);
@@ -186,6 +193,11 @@
 	return ms->imsi;
 }
 
+static inline bool ms_imsi_valid(const struct GprsMs *ms)
+{
+	return ms->imsi[0] != '\0';
+}
+
 static inline uint8_t ms_ta(const struct GprsMs *ms)
 {
 	return ms->ta;
diff --git a/src/gprs_pcu.c b/src/gprs_pcu.c
index 37563ec..1ebc2ed 100644
--- a/src/gprs_pcu.c
+++ b/src/gprs_pcu.c
@@ -36,6 +36,8 @@
 	{ .T=PCU_TDEF_SI_RESOLVE_TO,	   .default_val=1000,  .unit=OSMO_TDEF_MS,   .desc="RIM RAN-INFO response timeout (ms)",	    .val=0 },
 	{ .T=PCU_TDEF_NEIGH_CACHE_ALIVE,   .default_val=5,  .unit=OSMO_TDEF_S,   .desc="[ARFCN+BSIC]->[RAC+CI] resolution cache entry storage timeout (s)", .val=0 },
 	{ .T=PCU_TDEF_SI_CACHE_ALIVE,      .default_val=5,  .unit=OSMO_TDEF_S,   .desc="[RAC+CI]->[SI] resolution cache entry storage timeout (s)", .val=0 },
+	{ .T=PCU_TDEF_ANR_SCHED_TBF,      .default_val=10,  .unit=OSMO_TDEF_S,   .desc="[ANR] Frequency to schedule a new Measurement Report on any MS (s)", .val=0 },
+	{ .T=PCU_TDEF_ANR_MS_TIMEOUT, .default_val=60, .unit=OSMO_TDEF_S, .desc="[ANR] Time to wait for Packet Measurement Report (s)",  .val=0 },
 	{ .T=-101,  .default_val=30,  .unit=OSMO_TDEF_S,  .desc="BSSGP (un)blocking procedures timer (s)",  .val=0 },
 	{ .T=-102,  .default_val=30,  .unit=OSMO_TDEF_S,  .desc="BSSGP reset procedure timer (s)",          .val=0 },
 	{ .T=-2000, .default_val=2,   .unit=OSMO_TDEF_MS, .desc="Delay release of UL TBF after tx Packet Access Reject (PACCH) (ms)", .val=0 },
diff --git a/src/gprs_pcu.h b/src/gprs_pcu.h
index 86fe8eb..9b8ce64 100644
--- a/src/gprs_pcu.h
+++ b/src/gprs_pcu.h
@@ -41,6 +41,8 @@
 #define PCU_TDEF_SI_RESOLVE_TO (-2)
 #define PCU_TDEF_NEIGH_CACHE_ALIVE (-10)
 #define PCU_TDEF_SI_CACHE_ALIVE    (-11)
+#define PCU_TDEF_ANR_SCHED_TBF	(-20)
+#define PCU_TDEF_ANR_MS_TIMEOUT	(-21)
 
 /* see bts->gsmtap_categ_mask */
 enum pcu_gsmtap_category {
diff --git a/src/gprs_rlcmac_meas.cpp b/src/gprs_rlcmac_meas.cpp
index b9a324f..d9b280f 100644
--- a/src/gprs_rlcmac_meas.cpp
+++ b/src/gprs_rlcmac_meas.cpp
@@ -27,6 +27,7 @@
 #include <tbf.h>
 #include <tbf_dl.h>
 #include <gprs_ms.h>
+#include <ms_anr_fsm.h>
 
 #include <string.h>
 #include <errno.h>
@@ -42,6 +43,7 @@
 	NC_Measurement_Report_t *ncr;
 	NC_Measurements_t *nc;
 	int i;
+	int rc = 0;
 
 	LOGPMS(ms, DRLCMACMEAS, LOGL_INFO, "Rx Measurement Report:");
 
@@ -65,7 +67,9 @@
 		break;
 	}
 
-	return 0;
+	if (ms->anr && ms->anr->fi->state == MS_ANR_ST_WAIT_PKT_MEAS_REPORT)
+		rc = osmo_fsm_inst_dispatch(ms->anr->fi, MS_ANR_EV_RX_PKT_MEAS_REPORT, pmr);
+	return rc;
 }
 
 
diff --git a/src/gprs_rlcmac_sched.cpp b/src/gprs_rlcmac_sched.cpp
index 2adf1f3..070694c 100644
--- a/src/gprs_rlcmac_sched.cpp
+++ b/src/gprs_rlcmac_sched.cpp
@@ -38,6 +38,7 @@
 	struct gprs_rlcmac_tbf *ul_ass;
 	struct gprs_rlcmac_tbf *dl_ass;
 	struct gprs_rlcmac_tbf *nacc;
+	struct gprs_rlcmac_tbf *anr;
 	struct gprs_rlcmac_ul_tbf *ul_ack;
 };
 
@@ -64,6 +65,7 @@
 		/* NACC ready to send. TFI assigned is needed to send messages */
 		if (ul_tbf->is_tfi_assigned() && ms_nacc_rts(ul_tbf->ms()))
 			tbf_cand->nacc = ul_tbf;
+		/* Don't pick ->anr here, only DL TBFs are useful */
 /* FIXME: Is this supposed to be fair? The last TBF for each wins? Maybe use llist_add_tail and skip once we have all
 states? */
 	}
@@ -81,6 +83,8 @@
 		/* NACC ready to send. TFI assigned is needed to send messages */
 		if (dl_tbf->is_tfi_assigned() && ms_nacc_rts(dl_tbf->ms()))
 			tbf_cand->nacc = dl_tbf;
+		if (ms_anr_rts(dl_tbf->ms(), dl_tbf))
+			tbf_cand->anr = dl_tbf;
 	}
 }
 
@@ -151,7 +155,8 @@
 	struct gprs_rlcmac_tbf *next_list[] = { tbfs->ul_ass,
 						tbfs->dl_ass,
 						tbfs->ul_ack,
-						tbfs->nacc };
+						tbfs->nacc,
+						tbfs->anr };
 	uint8_t ts = pdch->ts_no;
 
 	/* Send Packet Application Information first (ETWS primary notifications) */
@@ -176,9 +181,10 @@
 				msg = tbfs->dl_ass->create_dl_ass(fn, ts);
 			else if (tbf == tbfs->ul_ack)
 				msg = tbfs->ul_ack->create_ul_ack(fn, ts);
-			else if (tbf == tbfs->nacc) {
+			else if (tbf == tbfs->nacc)
 				msg = ms_nacc_create_rlcmac_msg(tbf->ms(), tbf, fn, ts);
-			}
+			else if (tbf == tbfs->anr)
+				msg = ms_anr_create_rlcmac_msg(tbf->ms(), tbf, fn, ts);
 
 			if (!msg) {
 				tbf = NULL;
diff --git a/src/gsm_rlcmac.h b/src/gsm_rlcmac.h
index 01e2ee6..1d70f25 100644
--- a/src/gsm_rlcmac.h
+++ b/src/gsm_rlcmac.h
@@ -3259,7 +3259,7 @@
 
 typedef struct
 {
-  guint8 FREQ_DIFF_LENGTH;
+  guint8 FREQ_DIFF_LENGTH; //THIS DOESN?T BELONG HERE!
   guint8 FREQUENCY_DIFF;
   guint8 BSIC;
 
diff --git a/src/ms_anr_fsm.c b/src/ms_anr_fsm.c
new file mode 100644
index 0000000..6ed4bed
--- /dev/null
+++ b/src/ms_anr_fsm.c
@@ -0,0 +1,757 @@
+/* ms_anr_fsm.c
+ *
+ * Copyright (C) 2021 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
+ * Author: Pau Espin Pedrol <pespin@sysmocom.de>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+
+#include <unistd.h>
+#include <talloc.h>
+
+#include <osmocom/core/rate_ctr.h>
+#include <osmocom/ctrl/control_cmd.h>
+#include <osmocom/ctrl/control_if.h>
+
+#include <osmocom/gsm/gsm48.h>
+#include <osmocom/gprs/gprs_bssgp.h>
+#include <osmocom/gprs/gprs_bssgp_rim.h>
+
+#include <ms_anr_fsm.h>
+#include <gprs_rlcmac.h>
+#include <gprs_debug.h>
+#include <gprs_ms.h>
+#include <encoding.h>
+#include <bts.h>
+
+#define X(s) (1 << (s))
+
+/* We add safety timer to any FSM since ending up into some unexpected scenario
+ * can keep the FSM alive and hence the TBF kept open forever */
+static const struct osmo_tdef_state_timeout ms_anr_fsm_timeouts[32] = {
+	[MS_ANR_ST_INITIAL] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_TX_PKT_MEAS_RESET1] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_WAIT_CTRL_ACK1] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_TX_PKT_MEAS_ORDER] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_WAIT_PKT_MEAS_REPORT] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_TX_PKT_MEAS_RESET2] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_WAIT_CTRL_ACK2] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+	[MS_ANR_ST_DONE] = { .T = PCU_TDEF_ANR_MS_TIMEOUT },
+};
+
+/* Transition to a state, using the T timer defined in assignment_fsm_timeouts.
+ * The actual timeout value is in turn obtained from conn->T_defs.
+ * Assumes local variable fi exists. */
+#define ms_anr_fsm_state_chg(fi, NEXT_STATE) \
+	osmo_tdef_fsm_inst_state_chg(fi, NEXT_STATE, \
+				     ms_anr_fsm_timeouts, \
+				     ((struct ms_anr_fsm_ctx*)(fi->priv))->ms->bts->pcu->T_defs, \
+				     -1)
+
+const struct value_string ms_anr_fsm_event_names[] = {
+	{ MS_ANR_EV_START, "START" },
+	{ MS_ANR_EV_CREATE_RLCMAC_MSG, "CREATE_RLCMAC_MSG" },
+	{ MS_ANR_EV_RX_PKT_MEAS_REPORT, "RX_PKT_MEAS_REPORT" },
+	{ MS_ANR_EV_RX_PKT_CTRL_ACK_MSG, "RX_PKT_CTRL_ACK_MSG" },
+	{ MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT, "RX_PKT_CTRL_ACK_TIMEOUT" },
+	{ 0, NULL }
+};
+
+/* TS 44 060 11.2.9b Packet Measurement Order */
+static struct msgb *create_packet_meas_order(struct ms_anr_fsm_ctx *ctx,
+					     const struct gprs_rlcmac_tbf *tbf,
+					     uint8_t nco, uint8_t pmo_idx, uint8_t pmo_count,
+					     const NC_Frequency_list_t *freq_li)
+{
+	struct msgb *msg;
+	int rc;
+	RlcMacDownlink_t *mac_control_block;
+	struct GprsMs *ms = tbf_ms(tbf);
+	bool tfi_asigned, tfi_is_dl;
+	uint8_t tfi;
+	bool exist_nc;
+	uint8_t non_drx_period, nc_report_period_i, nc_report_period_t;
+
+	if (tbf_is_tfi_assigned(tbf)) {
+		tfi_asigned = true;
+		tfi_is_dl = tbf_direction(tbf) == GPRS_RLCMAC_DL_TBF;
+		tfi = tbf_tfi(tbf);
+	} else {
+		tfi_asigned = false;
+		tfi_is_dl = false;
+		tfi = 0;
+	}
+
+
+	msg = msgb_alloc(GSM_MACBLOCK_LEN, "pkt_meas_order");
+	if (!msg)
+		return NULL;
+
+	/* Initialize a bit vector that uses allocated msgb as the data buffer. */
+	struct bitvec bv = {
+		.data = msgb_put(msg, GSM_MACBLOCK_LEN),
+		.data_len = GSM_MACBLOCK_LEN,
+	};
+	bitvec_unhex(&bv, DUMMY_VEC);
+
+	mac_control_block = (RlcMacDownlink_t *)talloc_zero(ctx->ms, RlcMacDownlink_t);
+
+	/* First message, set NC Meas Params. As per spec:
+	 * "If parameters for the NC measurements are not included, a previous
+	 * Packet Measurement Order message belonging to the same set of messages
+	 * shall still be valid." */
+	exist_nc = pmo_idx == 0;
+	non_drx_period = 2; /* default value, still need to check */
+	nc_report_period_i = 5;//0;
+	nc_report_period_t = 5;//0;
+
+
+	write_packet_measurement_order(mac_control_block, 0, 0, tfi_asigned, tfi_is_dl,tfi, ms_tlli(ms),
+				       pmo_idx, pmo_count, nco, exist_nc, non_drx_period,
+				       nc_report_period_i, nc_report_period_t, freq_li);
+	LOGP(DANR, LOGL_DEBUG, "+++++++++++++++++++++++++ TX : Packet Measurement Order +++++++++++++++++++++++++\n");
+	rc = encode_gsm_rlcmac_downlink(&bv, mac_control_block);
+	if (rc < 0) {
+		LOGP(DANR, LOGL_ERROR, "Encoding of Packet Measurement Order Data failed (%d)\n", rc);
+		goto free_ret;
+	}
+	LOGP(DANR, LOGL_DEBUG, "------------------------- TX : Packet Measurement Order -------------------------\n");
+	rate_ctr_inc(&bts_rate_counters(ms->bts)->ctr[CTR_PKT_MEAS_ORDER]);
+	talloc_free(mac_control_block);
+
+	return msg;
+
+free_ret:
+	talloc_free(mac_control_block);
+	msgb_free(msg);
+	return NULL;
+}
+
+#define MAX_REMOVE_FREQ_PER_MSG 16
+#define MAX_ADD_FREQ_PER_MSG 5
+static void build_nc_freq_list(struct ms_anr_fsm_ctx *ctx, NC_Frequency_list_t *freq_li,
+			       const uint16_t *freq_to_remove, unsigned *freq_to_remove_idx, unsigned freq_to_remove_cnt,
+			       const struct arfcn_bsic *freq_to_add, unsigned *freq_to_add_idx, unsigned freq_to_add_cnt)
+{
+	int i;
+	unsigned to_remove_this_message;
+	LOGP(DANR, LOGL_DEBUG, "Build NC Frequency List:\n");
+
+	/* First, remove all ARFCNs from BS(GPRS): */
+	if (*freq_to_remove_idx < freq_to_remove_cnt) {
+		to_remove_this_message = OSMO_MIN(freq_to_remove_cnt - *freq_to_remove_idx, MAX_REMOVE_FREQ_PER_MSG);
+		freq_li->Exist_REMOVED_FREQ = 1;
+		freq_li->NR_OF_REMOVED_FREQ = to_remove_this_message; /* offset of 1 applied already by CSN1 encoder */
+		for (i = 0; i < to_remove_this_message; i++) {
+			LOGP(DANR, LOGL_DEBUG, "Remove_Frequency[%d] INDEX=%u\n", i, freq_to_remove[*freq_to_remove_idx]);
+			freq_li->Removed_Freq_Index[i].REMOVED_FREQ_INDEX = freq_to_remove[(*freq_to_remove_idx)++];
+		}
+		/* We want in general to first remove all frequencies, and only once we
+		 * are done removing, starting adding new ones */
+		if (*freq_to_remove_idx < freq_to_remove_cnt) {
+			freq_li->Count_Add_Frequency = 0;
+			return;
+		}
+	} else {
+		to_remove_this_message = 0;
+		freq_li->Exist_REMOVED_FREQ = 0;
+	}
+
+	/* Then, add selected ones for ANR. ctx->cell_list has ARFCNs stored in ascending order */
+	freq_li->Count_Add_Frequency = OSMO_MIN(freq_to_add_cnt - *freq_to_add_idx,
+						MAX_ADD_FREQ_PER_MSG - to_remove_this_message/4);
+	for (i = 0; i < freq_li->Count_Add_Frequency; i++) {
+		freq_li->Add_Frequency[i].START_FREQUENCY = freq_to_add[*freq_to_add_idx].arfcn;
+		freq_li->Add_Frequency[i].BSIC = freq_to_add[*freq_to_add_idx].bsic;
+		freq_li->Add_Frequency[i].Exist_Cell_Selection = 0;
+		freq_li->Add_Frequency[i].NR_OF_FREQUENCIES = 0; /* TODO: optimize here checking if we can fit more with DIFF */
+		freq_li->Add_Frequency[i].FREQ_DIFF_LENGTH = 0;
+		LOGP(DANR, LOGL_DEBUG, "Add_Frequency[%d] START_FREQ=%u BSIC=%u\n", i,
+			freq_li->Add_Frequency[i].START_FREQUENCY,
+			freq_li->Add_Frequency[i].BSIC);
+		(*freq_to_add_idx)++;
+	}
+}
+
+static int build_multipart_packet_meas_order(struct ms_anr_fsm_ctx *ctx)
+{
+	struct gprs_rlcmac_bts *bts = ctx->ms->bts;
+	unsigned int i, j;
+	/* TODO: decide early whether to use si2 or si5, and pick is related BA-IND */
+	struct gsm_sysinfo_freq *bcch_freq_list = bts->si2_bcch_cell_list;
+	unsigned int bcch_freq_list_len = ARRAY_SIZE(bts->si2_bcch_cell_list);
+	unsigned int bcch_freq_list_cnt = 0; // Number of freqs in Neigh List */
+
+	unsigned int freq_to_remove_cnt = 0, freq_to_add_cnt = 0;
+	uint16_t freq_to_remove[1024]; /* freq list index */
+	struct arfcn_bsic freq_to_add[1024];
+
+	/* First calculate amount of REMOVE and ADD freq entries, to calculate
+	 * required number of bits and hence number of RLCMAC messages */
+	ctx->nc_measurement_list_len = 0;
+	for (i = 0; i < bcch_freq_list_len; i++) {
+		bool bcch_freq_marked = !!bcch_freq_list[i].mask;
+
+		if (bcch_freq_marked) {
+			/* Freqs from BCCH list occupy one slot in the Neighbour
+			 * List, even if removed later by NC_FreqList in Pkt
+			 * Meas Order */
+			if (ctx->nc_measurement_list_len < ARRAY_SIZE(ctx->nc_measurement_list)) {
+				ctx->nc_measurement_list[ctx->nc_measurement_list_len] = i;
+				ctx->nc_measurement_list_len++;
+			}
+
+			/* Check if the ARFCN is in our target ANR subset,
+			 * otherwise mark it from removal using Pkt Meas Order */
+			bcch_freq_list_cnt++;
+			bool found = false;
+			for (j = 0; j < ctx->num_cells; j++) {
+				/* early termination, arfcns are in ascending order */
+				if (ctx->cell_list[j].arfcn > i)
+					break;
+				if (ctx->cell_list[j].arfcn == i) {
+					found = true;
+					break;
+				}
+			}
+			if (!found) {
+				freq_to_remove[freq_to_remove_cnt] = bcch_freq_list_cnt - 1;
+				freq_to_remove_cnt++;
+			}
+		} else {
+			for (j = 0; j < ctx->num_cells; j++) {
+				/* early termination, arfcns are in ascending order */
+				if (ctx->cell_list[j].arfcn > i)
+					break;
+				if (ctx->cell_list[j].arfcn == i) {
+					freq_to_add[freq_to_add_cnt] = ctx->cell_list[j];
+					freq_to_add_cnt++;
+					/* Don't break here, there may be several ARFCN=N with different BSIC */
+				}
+			}
+		}
+	}
+
+	LOGPFSML(ctx->fi, LOGL_DEBUG, "NC_freq_list to_remove=%u to_add=%u\n", freq_to_remove_cnt, freq_to_add_cnt);
+
+	/* Added frequency through Pkt Meas Order NC Freq list are indexed after existing arfcns from BA(GPRS) */
+	for (i = 0; i < freq_to_add_cnt; i++) {
+		if (ctx->nc_measurement_list_len >= ARRAY_SIZE(ctx->nc_measurement_list))
+			break;
+		ctx->nc_measurement_list[ctx->nc_measurement_list_len] = freq_to_add[i].arfcn;
+		ctx->nc_measurement_list_len++;
+	}
+
+	uint8_t pmo_index;
+	uint8_t pmo_count = 0;
+	unsigned int freq_to_remove_idx = 0, freq_to_add_idx = 0;
+	NC_Frequency_list_t freq_li[8];
+	do {
+		OSMO_ASSERT(pmo_count < ARRAY_SIZE(freq_li)); /* TODO: print something here*/
+		build_nc_freq_list(ctx, &freq_li[pmo_count],
+				   freq_to_remove, &freq_to_remove_idx, freq_to_remove_cnt,
+				   freq_to_add, &freq_to_add_idx, freq_to_add_cnt);
+		pmo_count++;
+	} while (freq_to_remove_idx < freq_to_remove_cnt || freq_to_add_idx < freq_to_add_cnt);
+
+	/* Now build messages */
+	for (pmo_index = 0; pmo_index < pmo_count; pmo_index++) {
+		struct msgb *msg = create_packet_meas_order(ctx, ctx->tbf, NC_1, pmo_index, pmo_count - 1, &freq_li[pmo_index]);
+		llist_add_tail(&msg->list, &ctx->meas_order_queue);
+	}
+	return 0;
+}
+
+/* TS 44 060 11.2.9b Packet Measurement Order */
+static struct msgb *create_packet_meas_order_reset(struct ms_anr_fsm_ctx *ctx,
+						   struct ms_anr_ev_create_rlcmac_msg_ctx *data,
+						   uint32_t *new_poll_fn)
+{
+	struct msgb *msg;
+	int rc;
+	RlcMacDownlink_t *mac_control_block;
+	struct gprs_rlcmac_tbf *tbf = ctx->tbf;
+	struct GprsMs *ms = tbf_ms(tbf);
+	bool tfi_asigned, tfi_is_dl;
+	uint8_t tfi;
+	uint8_t pmo_idx = 0, pmo_count = 0;
+	uint8_t nco = NC_RESET;
+	unsigned int rrbp;
+
+	if (tbf_is_tfi_assigned(tbf)) {
+		tfi_asigned = true;
+		tfi_is_dl = tbf_direction(tbf) == GPRS_RLCMAC_DL_TBF;
+		tfi = tbf_tfi(tbf);
+	} else {
+		tfi_asigned = false;
+		tfi_is_dl = false;
+		tfi = 0;
+	}
+
+	rc = tbf_check_polling(tbf, data->fn, data->ts, new_poll_fn, &rrbp);
+	if (rc < 0) {
+		LOGP(DANR, LOGL_ERROR, "Failed registering poll for Packet Measurement Order (reset) (%d)\n", rc);
+		return NULL;
+	}
+
+	msg = msgb_alloc(GSM_MACBLOCK_LEN, "pkt_meas_order");
+	if (!msg)
+		return NULL;
+
+	/* Initialize a bit vector that uses allocated msgb as the data buffer. */
+	struct bitvec bv = {
+		.data = msgb_put(msg, GSM_MACBLOCK_LEN),
+		.data_len = GSM_MACBLOCK_LEN,
+	};
+	bitvec_unhex(&bv, DUMMY_VEC);
+
+	mac_control_block = (RlcMacDownlink_t *)talloc_zero(ctx->ms, RlcMacDownlink_t);
+
+	write_packet_measurement_order(mac_control_block, 1, rrbp, tfi_asigned, tfi_is_dl,tfi, ms_tlli(ms),
+					    pmo_idx, pmo_count, nco, false, 0, 0, 0, NULL);
+	LOGP(DANR, LOGL_DEBUG, "+++++++++++++++++++++++++ TX : Packet Measurement Order (reset) FN=%" PRIu32 " +++++++++++++++++++++++++\n", data->fn);
+	rc = encode_gsm_rlcmac_downlink(&bv, mac_control_block);
+	if (rc < 0) {
+		LOGP(DANR, LOGL_ERROR, "Encoding of Packet Measurement Order Data failed (%d)\n", rc);
+		goto free_ret;
+	}
+	LOGP(DANR, LOGL_DEBUG, "------------------------- TX : Packet Measurement Order (reset) POLL_FN=%" PRIu32 "-------------------------\n", *new_poll_fn);
+	rate_ctr_inc(&bts_rate_counters(ms->bts)->ctr[CTR_PKT_MEAS_ORDER]);
+	talloc_free(mac_control_block);
+
+	tbf_set_polling(tbf, *new_poll_fn, data->ts, PDCH_ULC_POLL_MEAS_ORDER);
+	return msg;
+
+free_ret:
+	talloc_free(mac_control_block);
+	msgb_free(msg);
+	return NULL;
+}
+
+static void handle_meas_report(struct ms_anr_fsm_ctx *ctx, uint8_t *meas, const Packet_Measurement_Report_t *pmr)
+{
+	//TODO: transmit meas back to BSC
+	const NC_Measurement_Report_t *ncr;
+	int i, j;
+	memset(meas, 0xff, ctx->num_cells);
+
+	switch (pmr->UnionType) {
+	case 0: break;
+	case 1: /* EXT Reporting, should not happen */
+	default:
+		LOGPFSML(ctx->fi, LOGL_NOTICE, "EXT Reporting not supported!\n");
+		osmo_fsm_inst_term(ctx->fi, OSMO_FSM_TERM_ERROR, NULL);
+		return;
+	}
+
+	ncr = &pmr->u.NC_Measurement_Report;
+	LOGPFSML(ctx->fi, LOGL_NOTICE, "Rx MEAS REPORT %u neighbours\n", ncr->NUMBER_OF_NC_MEASUREMENTS);
+
+	for (i = 0; i < ncr->NUMBER_OF_NC_MEASUREMENTS; i++) {
+		const NC_Measurements_t *nc = &ncr->NC_Measurements[i];
+		/* infer ARFCN from FREQUENCY_N using previously calculated data: */
+		OSMO_ASSERT(nc->FREQUENCY_N < ARRAY_SIZE(ctx->nc_measurement_list));
+		uint16_t arfcn = ctx->nc_measurement_list[nc->FREQUENCY_N];
+		LOGPFSML(ctx->fi, LOGL_DEBUG, "Neigh arfcn_index=%u arfcn=%u bsic=%d %d dBm\n",
+			 nc->FREQUENCY_N, arfcn, nc->Exist_BSIC_N ? nc->BSIC_N : -1, nc->RXLEV_N - 110);
+		if (!nc->Exist_BSIC_N)
+			continue; /* Skip measurement without BSIC, since there could be several cells with same ARFCN */
+		for (j = 0; j < ctx->num_cells; j++) {
+			if (ctx->cell_list[j].arfcn != arfcn || ctx->cell_list[j].bsic != nc->BSIC_N)
+				continue;
+			meas[j] = nc->RXLEV_N;
+			break;
+		}
+		if (j == ctx->num_cells) {
+			LOGPFSML(ctx->fi, LOGL_NOTICE,
+				 "Neigh arfcn_index=%u arfcn=%u bsic=%u %d dBm not found in target cell list!\n",
+				 nc->FREQUENCY_N, arfcn, nc->BSIC_N, nc->RXLEV_N - 110);
+		}
+	}
+}
+
+////////////////
+// FSM states //
+////////////////
+
+static void st_initial(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	//struct gprs_rlcmac_bts *bts = ctx->ms->bts;
+	const struct ms_anr_ev_start *start_data;
+
+	switch (event) {
+	case MS_ANR_EV_START:
+		start_data = (const struct ms_anr_ev_start *)data;
+		/* Copy over cell list on which to ask for measurements */
+		OSMO_ASSERT(start_data->tbf);
+		ctx->tbf = start_data->tbf;
+		OSMO_ASSERT(start_data->num_cells <= ARRAY_SIZE(ctx->cell_list));
+		ctx->num_cells = start_data->num_cells;
+		if (start_data->num_cells)
+			memcpy(ctx->cell_list, start_data->cell_list, start_data->num_cells * sizeof(start_data->cell_list[0]));
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_TX_PKT_MEAS_RESET1);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_tx_pkt_meas_reset1(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	struct ms_anr_ev_create_rlcmac_msg_ctx *data_ctx;
+
+	switch (event) {
+	case MS_ANR_EV_CREATE_RLCMAC_MSG:
+		/* Set NC to RESET and drop NC_Freq_list for MS to go back to
+		   network defaults. */
+		data_ctx = (struct ms_anr_ev_create_rlcmac_msg_ctx *)data;
+		data_ctx->msg = create_packet_meas_order_reset(ctx, data_ctx, &ctx->poll_fn);
+		if (!data_ctx->msg) {
+			osmo_fsm_inst_term(fi, OSMO_FSM_TERM_ERROR, NULL);
+			return;
+		}
+		ctx->poll_ts = data_ctx->ts;
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_WAIT_CTRL_ACK1);
+		break;
+	case MS_ANR_EV_RX_PKT_MEAS_REPORT:
+		/* Ignore Meas Report from previously (potentially unfinished) prcoedures */
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_wait_ctrl_ack1(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	//struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+
+	switch (event) {
+	case MS_ANR_EV_RX_PKT_CTRL_ACK_MSG:
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_TX_PKT_MEAS_ORDER);
+		break;
+	case MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT:
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_TX_PKT_MEAS_RESET1);
+		break;
+	case MS_ANR_EV_RX_PKT_MEAS_REPORT:
+		/* Ignore Meas Report from previously (potentially unfinished) prcoedures */
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_tx_pkt_meas_order_on_enter(struct osmo_fsm_inst *fi, uint32_t prev_state)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	build_multipart_packet_meas_order(ctx);
+}
+
+static void st_tx_pkt_meas_order(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	struct ms_anr_ev_create_rlcmac_msg_ctx *data_ctx;
+
+	switch (event) {
+	case MS_ANR_EV_CREATE_RLCMAC_MSG:
+		data_ctx = (struct ms_anr_ev_create_rlcmac_msg_ctx *)data;
+		/* Set NC to 1 to force MS to send us Meas Rep */
+		data_ctx->msg = llist_first_entry(&ctx->meas_order_queue, struct msgb, list);
+		if (!data_ctx->msg) {
+			osmo_fsm_inst_term(fi, OSMO_FSM_TERM_ERROR, NULL);
+			return;
+		}
+		llist_del(&data_ctx->msg->list);
+		if (llist_empty(&ctx->meas_order_queue)) /* DONE */
+			ms_anr_fsm_state_chg(fi, MS_ANR_ST_WAIT_PKT_MEAS_REPORT);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_wait_rx_pkt_meas_report_on_enter(struct osmo_fsm_inst *fi, uint32_t prev_state)
+{
+	/* DO NOTHING */
+}
+
+
+static void st_wait_rx_pkt_meas_report(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	uint8_t *meas = alloca(ctx->num_cells);
+	struct ms_anr_ev_meas_compl ev_compl = {
+		.cell_list = ctx->cell_list,
+		.meas_list = meas,
+		.num_cells = ctx->num_cells,
+	};
+
+	switch (event) {
+	case MS_ANR_EV_RX_PKT_MEAS_REPORT:
+		handle_meas_report(ctx, meas, (const Packet_Measurement_Report_t *)data);
+		osmo_fsm_inst_dispatch(ctx->ms->bts->anr->fi, BTS_ANR_EV_MS_MEAS_COMPL, &ev_compl);
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_TX_PKT_MEAS_RESET2);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_tx_pkt_meas_reset2(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	struct ms_anr_ev_create_rlcmac_msg_ctx *data_ctx;
+	uint8_t *meas = alloca(ctx->num_cells);
+	struct ms_anr_ev_meas_compl ev_compl = {
+		.cell_list = ctx->cell_list,
+		.meas_list = meas,
+		.num_cells = ctx->num_cells,
+	};
+
+	switch (event) {
+	case MS_ANR_EV_CREATE_RLCMAC_MSG:
+		/* Set NC to RESET and drop NC_Freq_list for MS to go back to
+		   network defaults. */
+		data_ctx = (struct ms_anr_ev_create_rlcmac_msg_ctx *)data;
+		data_ctx->msg = create_packet_meas_order_reset(ctx, data_ctx, &ctx->poll_fn);
+		if (!data_ctx->msg) {
+			osmo_fsm_inst_term(fi, OSMO_FSM_TERM_ERROR, NULL);
+			return;
+		}
+		ctx->poll_ts = data_ctx->ts;
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_WAIT_CTRL_ACK2);
+		break;
+	case MS_ANR_EV_RX_PKT_MEAS_REPORT:
+		handle_meas_report(ctx, meas, (const Packet_Measurement_Report_t *)data);
+		osmo_fsm_inst_dispatch(ctx->ms->bts->anr->fi, BTS_ANR_EV_MS_MEAS_COMPL, &ev_compl);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_wait_ctrl_ack2(struct osmo_fsm_inst *fi, uint32_t event, void *data)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+	uint8_t *meas = alloca(ctx->num_cells);
+	struct ms_anr_ev_meas_compl ev_compl = {
+		.cell_list = ctx->cell_list,
+		.meas_list = meas,
+		.num_cells = ctx->num_cells,
+	};
+
+	switch (event) {
+	case MS_ANR_EV_RX_PKT_CTRL_ACK_MSG:
+		ms_anr_fsm_state_chg(fi, MS_ANR_ST_DONE);
+		break;
+	case MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT:
+		ms_anr_fsm_state_chg(fi, fi->state == MS_ANR_ST_WAIT_CTRL_ACK1 ?
+						MS_ANR_ST_TX_PKT_MEAS_RESET1 :
+						MS_ANR_ST_TX_PKT_MEAS_RESET2);
+		break;
+	case MS_ANR_EV_RX_PKT_MEAS_REPORT:
+		/* We may keep receiving meas report from MS while waiting to
+		 * receive the CTRL ACK: */
+		handle_meas_report(ctx, meas, (const Packet_Measurement_Report_t *)data);
+		osmo_fsm_inst_dispatch(ctx->ms->bts->anr->fi, BTS_ANR_EV_MS_MEAS_COMPL, &ev_compl);
+		break;
+	default:
+		OSMO_ASSERT(0);
+	}
+}
+
+static void st_done_on_enter(struct osmo_fsm_inst *fi, uint32_t prev_state)
+{
+	osmo_fsm_inst_term(fi, OSMO_FSM_TERM_REGULAR, NULL);
+}
+
+static void ms_anr_fsm_cleanup(struct osmo_fsm_inst *fi, enum osmo_fsm_term_cause cause)
+{
+	struct ms_anr_fsm_ctx *ctx = (struct ms_anr_fsm_ctx *)fi->priv;
+
+	/* after cleanup() finishes, FSM termination calls osmo_fsm_inst_free,
+	   so we need to avoid double-freeing it during ctx talloc free
+	   destructor */
+	talloc_reparent(ctx, ctx->ms, ctx->fi);
+	ctx->fi = NULL;
+
+	/* remove references from owning MS and free entire ctx */
+	ctx->ms->anr = NULL;
+
+	if (cause != OSMO_FSM_TERM_REGULAR && cause != OSMO_FSM_TERM_REQUEST) {
+		/* Signal to bts_anr_fsm that orchestrates us that we failed, so
+		 * that it can schedule the procedure again */
+		struct ms_anr_ev_abort ev_data = {
+			.cell_list = &ctx->cell_list[0],
+			.num_cells = ctx->num_cells,
+		};
+		osmo_fsm_inst_dispatch(ctx->ms->bts->anr->fi, BTS_ANR_EV_MS_MEAS_ABORTED, &ev_data);
+	}
+
+	talloc_free(ctx);
+}
+
+static int ms_anr_fsm_timer_cb(struct osmo_fsm_inst *fi)
+{
+	switch (fi->T) {
+		case PCU_TDEF_ANR_MS_TIMEOUT:
+			LOGPFSML(fi, LOGL_NOTICE, "ms_anr_fsm got stuck, freeing it. This probably indicates a bug somehwere (if not in state WAIT_PKT_MEAS_REPORT)\n");
+			osmo_fsm_inst_term(fi, OSMO_FSM_TERM_ERROR, NULL);
+			break;
+		default:
+			OSMO_ASSERT(0);
+	}
+	return 0;
+}
+
+static struct osmo_fsm_state ms_anr_fsm_states[] = {
+	[MS_ANR_ST_INITIAL] = {
+		.in_event_mask =
+			X(MS_ANR_EV_START),
+		.out_state_mask =
+			X(MS_ANR_ST_TX_PKT_MEAS_RESET1),
+		.name = "INITIAL",
+		.action = st_initial,
+	},
+	[MS_ANR_ST_TX_PKT_MEAS_RESET1] = {
+		.in_event_mask =
+			X(MS_ANR_EV_CREATE_RLCMAC_MSG) |
+			X(MS_ANR_EV_RX_PKT_MEAS_REPORT),
+		.out_state_mask =
+			X(MS_ANR_ST_WAIT_CTRL_ACK1),
+		.name = "TX_PKT_MEAS_RESET1",
+		.action = st_tx_pkt_meas_reset1,
+	},
+	[MS_ANR_ST_WAIT_CTRL_ACK1] = {
+		.in_event_mask =
+			X(MS_ANR_EV_RX_PKT_CTRL_ACK_MSG) |
+			X(MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT) |
+			X(MS_ANR_EV_RX_PKT_MEAS_REPORT),
+		.out_state_mask =
+			X(MS_ANR_ST_TX_PKT_MEAS_RESET1) |
+			X(MS_ANR_ST_TX_PKT_MEAS_ORDER),
+		.name = "WAIT_CTRL_ACK1",
+		.action = st_wait_ctrl_ack1,
+	},
+	[MS_ANR_ST_TX_PKT_MEAS_ORDER] = {
+		.in_event_mask =
+			X(MS_ANR_EV_CREATE_RLCMAC_MSG),
+		.out_state_mask =
+			X(MS_ANR_ST_WAIT_PKT_MEAS_REPORT),
+		.name = "TX_PKT_MEAS_ORDER",
+		.onenter = st_tx_pkt_meas_order_on_enter,
+		.action = st_tx_pkt_meas_order,
+	},
+	[MS_ANR_ST_WAIT_PKT_MEAS_REPORT] = {
+		.in_event_mask =
+			X(MS_ANR_EV_RX_PKT_MEAS_REPORT),
+		.out_state_mask =
+			X(MS_ANR_ST_TX_PKT_MEAS_RESET2),
+		.name = "WAIT_PKT_MEAS_REPORT",
+		.onenter = st_wait_rx_pkt_meas_report_on_enter,
+		.action = st_wait_rx_pkt_meas_report,
+	},
+	[MS_ANR_ST_TX_PKT_MEAS_RESET2] = {
+		.in_event_mask =
+			X(MS_ANR_EV_CREATE_RLCMAC_MSG) |
+			X(MS_ANR_EV_RX_PKT_MEAS_REPORT),
+		.out_state_mask =
+			X(MS_ANR_ST_WAIT_CTRL_ACK2),
+		.name = "TX_PKT_MEAS_RESET2",
+		.action = st_tx_pkt_meas_reset2,
+	},
+	[MS_ANR_ST_WAIT_CTRL_ACK2] = {
+		.in_event_mask =
+			X(MS_ANR_EV_RX_PKT_CTRL_ACK_MSG) |
+			X(MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT) |
+			X(MS_ANR_EV_RX_PKT_MEAS_REPORT),
+		.out_state_mask =
+			X(MS_ANR_ST_TX_PKT_MEAS_RESET2) |
+			X(MS_ANR_ST_DONE),
+		.name = "WAIT_CTRL_ACK2",
+		.action = st_wait_ctrl_ack2,
+	},
+	[MS_ANR_ST_DONE] = {
+		.in_event_mask = 0,
+		.out_state_mask = 0,
+		.name = "DONE",
+		.onenter = st_done_on_enter,
+	},
+};
+
+static struct osmo_fsm ms_anr_fsm = {
+	.name = "MS_ANR",
+	.states = ms_anr_fsm_states,
+	.num_states = ARRAY_SIZE(ms_anr_fsm_states),
+	.timer_cb = ms_anr_fsm_timer_cb,
+	.cleanup = ms_anr_fsm_cleanup,
+	.log_subsys = DANR,
+	.event_names = ms_anr_fsm_event_names,
+};
+
+static __attribute__((constructor)) void ms_anr_fsm_init(void)
+{
+	OSMO_ASSERT(osmo_fsm_register(&ms_anr_fsm) == 0);
+}
+
+static int ms_anr_fsm_ctx_talloc_destructor(struct ms_anr_fsm_ctx *ctx)
+{
+	/* if ctx->fi != NULL it means we come directly from talloc_free(ctx)
+	 * without having passed through ms_anr_fsm_cleanup() as part of
+	 * osmo_fsm_inst_term(). In this case, clean up manually similarly to
+	 * ms_anr_fsm_cleanup() and free the ctx->fi. */
+	if (ctx->fi) {
+		/* Signal to bts_anr_fsm that orchestrates us that we failed, so
+		 * that it can schedule the procedure again */
+		struct ms_anr_ev_abort ev_data = {
+			.cell_list = &ctx->cell_list[0],
+			.num_cells = ctx->num_cells,
+		};
+		osmo_fsm_inst_dispatch(ctx->ms->bts->anr->fi, BTS_ANR_EV_MS_MEAS_ABORTED, &ev_data);
+		osmo_fsm_inst_free(ctx->fi);
+		ctx->fi = NULL;
+	}
+
+	return 0;
+}
+
+struct ms_anr_fsm_ctx *ms_anr_fsm_alloc(struct GprsMs* ms)
+{
+	struct ms_anr_fsm_ctx *ctx = talloc_zero(ms, struct ms_anr_fsm_ctx);
+	char buf[64];
+
+	talloc_set_destructor(ctx, ms_anr_fsm_ctx_talloc_destructor);
+
+	ctx->ms = ms;
+	INIT_LLIST_HEAD(&ctx->meas_order_queue);
+
+	snprintf(buf, sizeof(buf), "TLLI-0x%08x", ms_tlli(ms));
+	ctx->fi = osmo_fsm_inst_alloc(&ms_anr_fsm, ctx, ctx, LOGL_INFO, buf);
+	if (!ctx->fi)
+		goto free_ret;
+
+	return ctx;
+free_ret:
+	talloc_free(ctx);
+	return NULL;
+}
+
+/* Used by bts_anr_fsm to abort ongoing procedure without need of being informed
+ * back by BTS_ANR_EV_MS_MEAS_ABORTED */
+void ms_anr_fsm_abort(struct ms_anr_fsm_ctx *ctx)
+{
+	osmo_fsm_inst_term(ctx->fi, OSMO_FSM_TERM_REQUEST, NULL);
+}
diff --git a/src/ms_anr_fsm.h b/src/ms_anr_fsm.h
new file mode 100644
index 0000000..84bb768
--- /dev/null
+++ b/src/ms_anr_fsm.h
@@ -0,0 +1,90 @@
+/* ms_anr_fsm.h
+ *
+ * Copyright (C) 2021 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
+ * Author: Pau Espin Pedrol <pespin@sysmocom.de>
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+#pragma once
+
+#include <osmocom/core/fsm.h>
+#include <osmocom/gsm/gsm23003.h>
+
+#include "pcu_utils.h"
+
+struct GprsMs;
+struct gprs_rlcmac_tbf;
+
+#define MAX_NEIGH_LIST_LEN 96
+#define MAX_NEIGH_MEAS_LIST_LEN 32
+
+enum ms_anr_fsm_event {
+	MS_ANR_EV_START, /* data: struct ms_anr_ev_start */
+	MS_ANR_EV_CREATE_RLCMAC_MSG, /* data: struct anr_ev_create_rlcmac_msg_ctx* */
+	MS_ANR_EV_RX_PKT_MEAS_REPORT, /* data: Packet_Measurement_Report_t */
+	MS_ANR_EV_RX_PKT_CTRL_ACK_MSG,
+	MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT,
+};
+
+enum ms_anr_fsm_states {
+	MS_ANR_ST_INITIAL,
+	MS_ANR_ST_TX_PKT_MEAS_RESET1,
+	MS_ANR_ST_WAIT_CTRL_ACK1,
+	MS_ANR_ST_TX_PKT_MEAS_ORDER,
+	MS_ANR_ST_WAIT_PKT_MEAS_REPORT,
+	MS_ANR_ST_TX_PKT_MEAS_RESET2,
+	MS_ANR_ST_WAIT_CTRL_ACK2,
+	MS_ANR_ST_DONE,
+};
+
+struct ms_anr_fsm_ctx {
+	struct osmo_fsm_inst *fi;
+	struct GprsMs* ms; /* back pointer */
+	struct gprs_rlcmac_tbf *tbf; /* target tbf to create messages for, selected upon first MS_ANR_EV_CREATE_RLCMAC_MSG */
+	struct arfcn_bsic cell_list[MAX_NEIGH_MEAS_LIST_LEN]; /* ordered by ascending ARFCN */
+	unsigned int num_cells;
+	struct llist_head meas_order_queue; /* list of msgb PMO_IDX=0..PMO_COUNT */
+	uint16_t nc_measurement_list[MAX_NEIGH_LIST_LEN]; /* Used to infer ARFCN from Frequency index received at Measurement Report */
+	unsigned int nc_measurement_list_len;
+	uint32_t poll_fn; /* Scheduled poll FN to CTRL ACK the Pkt Meas Order (reset) */
+	uint8_t poll_ts; /* Scheduled poll TS to CTRL ACK the Pkt Meas Order (reset */
+};
+
+/* passed as data in MS_ANR_EV_START */
+struct ms_anr_ev_start {
+	struct gprs_rlcmac_tbf *tbf; /* target DL TBF to create messages for */
+	const struct arfcn_bsic* cell_list;
+	unsigned int num_cells;
+};
+
+/* passed as data in MS_ANR_EV_CREATE_RLCMAC_MSG */
+struct ms_anr_ev_create_rlcmac_msg_ctx {
+	//struct gprs_rlcmac_tbf *tbf; /* target DL TBF to create messages for */
+	uint32_t fn; /* FN where the created DL ctrl block is to be sent */
+	uint8_t ts; /* TS where the created DL ctrl block is to be sent */
+	struct msgb *msg; /* to be filled by FSM during event processing */
+};
+
+struct ms_anr_fsm_ctx *ms_anr_fsm_alloc(struct GprsMs* ms);
+void ms_anr_fsm_abort(struct ms_anr_fsm_ctx *ctx);
+
+/* 3GPP TS44.060 Table 11.2.4.2: PACKET CELL CHANGE ORDER
+ * 3GPP TS 45.008 10.1.4 Network controlled Cell re-selection*/
+enum network_control_order {
+	NC_0 = 0x00,
+	NC_1 = 0x01,
+	NC_2 = 0x02,
+	NC_RESET = 0x03
+};
diff --git a/src/pcu_l1_if.cpp b/src/pcu_l1_if.cpp
index 5aa8849..dd51ef7 100644
--- a/src/pcu_l1_if.cpp
+++ b/src/pcu_l1_if.cpp
@@ -95,6 +95,7 @@
  * PCU messages
  */
 
+/* Can be used to allocate message with non-variable size */
 struct msgb *pcu_msgb_alloc(uint8_t msg_type, uint8_t bts_nr)
 {
 	struct msgb *msg;
@@ -111,6 +112,21 @@
 	return msg;
 }
 
+/* Allocate message with extra size, only reserve pcuif msg hdr */
+static struct msgb *pcu_msgb_alloc_ext_size(uint8_t msg_type, uint8_t bts_nr, size_t extra_size)
+{
+	struct msgb *msg;
+	struct gsm_pcu_if *pcu_prim;
+	msg = msgb_alloc(sizeof(struct gsm_pcu_if) + extra_size, "pcu_sock_tx");
+	/* Only header is filled, caller is responible for reserving + filling
+	 * message type specific contents: */
+	msgb_put(msg, PCUIF_HDR_SIZE);
+	pcu_prim = (struct gsm_pcu_if *) msgb_data(msg);
+	pcu_prim->msg_type = msg_type;
+	pcu_prim->bts_nr = bts_nr;
+	return msg;
+}
+
 const struct value_string gsm_pcu_if_text_type_names[] = {
 	OSMO_VALUE_STRING(PCU_VERSION),
 	OSMO_VALUE_STRING(PCU_OML_ALERT),
@@ -271,6 +287,49 @@
 	pcu_tx_data_req(bts, 0, 0, PCU_IF_SAPI_PCH, 0, 0, 0, data, PAGING_GROUP_LEN + GSM_MACBLOCK_LEN);
 }
 
+
+static void _arfcn_bsic2cell_desc(struct gsm48_cell_desc *cd, uint16_t arfcn, uint8_t bsic)
+{
+	cd->ncc = (bsic >> 3 & 0x7);
+	cd->bcc = (bsic & 0x7);
+	cd->arfcn_hi = arfcn >> 8;
+	cd->arfcn_lo = arfcn & 0xff;
+}
+
+int pcu_tx_anr_cnf(struct gprs_rlcmac_bts *bts, const struct arfcn_bsic *cell_list,
+			  const uint8_t *meas_list, unsigned int num_cells)
+{
+	struct msgb *msg;
+	struct gsm_pcu_if *pcu_prim;
+	struct gsm_pcu_if_anr_cnf *anr_cnf;
+
+	LOGP(DL1IF, LOGL_DEBUG, "(bts=%u) Sending ANR Confirmation: num_cells=%u\n",
+	     bts->nr, num_cells);
+
+	msg = pcu_msgb_alloc_ext_size(PCU_IF_MSG_CONTAINER, bts->nr, sizeof(struct gsm_pcu_if_anr_cnf));
+	if (!msg)
+		return -ENOMEM;
+	pcu_prim = (struct gsm_pcu_if *) msgb_data(msg);
+	anr_cnf = (struct gsm_pcu_if_anr_cnf *)&pcu_prim->u.container.data[0];
+
+	msgb_put(msg, sizeof(pcu_prim->u.container) + sizeof(struct gsm_pcu_if_anr_cnf));
+	pcu_prim->u.container.msg_type = PCU_IF_MSG_ANR_CNF;
+	osmo_store16be(sizeof(struct gsm_pcu_if_anr_cnf), &pcu_prim->u.container.length);
+
+	OSMO_ASSERT(num_cells <= ARRAY_SIZE(anr_cnf->cell_list));
+	OSMO_ASSERT(num_cells <= ARRAY_SIZE(anr_cnf->rxlev_list));
+
+	anr_cnf->num_cells = num_cells;
+	if (num_cells) {
+		unsigned int i;
+		for (i = 0; i < num_cells; i++)
+			_arfcn_bsic2cell_desc((struct gsm48_cell_desc*)&anr_cnf->cell_list[i], cell_list[i].arfcn, cell_list[i].bsic);
+		memcpy(anr_cnf->rxlev_list, meas_list, num_cells);
+	}
+
+	return pcu_sock_send(msg);
+}
+
 void pcu_rx_block_time(struct gprs_rlcmac_bts *bts, uint16_t arfcn, uint32_t fn, uint8_t ts_no)
 {
 	bts_set_current_block_frame_number(bts, fn);
@@ -950,11 +1009,28 @@
 	return 0;
 }
 
+static int pcu_rx_anr_req(struct gprs_rlcmac_bts *bts, struct gsm_pcu_if_anr_req *anr_req)
+{
+
+	LOGP(DL1IF, LOGL_INFO, "Automatic Neighbor Registration Request received: num_cells=%u cell_list=%s\n",
+	     anr_req->num_cells,
+	     osmo_hexdump((const uint8_t*)anr_req->cell_list, anr_req->num_cells * sizeof(*anr_req->cell_list)));
+	return osmo_fsm_inst_dispatch(bts->anr->fi, BTS_ANR_EV_RX_ANR_REQ, anr_req);
+}
+
 static int pcu_rx_container(struct gprs_rlcmac_bts *bts, struct gsm_pcu_if_container *container)
 {
 	int rc;
+	uint16_t data_length = osmo_load16be(&container->length);
 
 	switch (container->msg_type) {
+	case PCU_IF_MSG_ANR_REQ:
+		if (data_length < sizeof(struct gsm_pcu_if_anr_req)) {
+			LOGP(DL1IF, LOGL_ERROR, "Rx container(ANR_REQ) message too short\n");
+			return -EINVAL;
+		}
+		rc = pcu_rx_anr_req(bts, (struct gsm_pcu_if_anr_req*)&container->data);
+		break;
 	default:
 		LOGP(DL1IF, LOGL_NOTICE, "(bts=%d) Rx unexpected msg type (%u) inside container!\n",
 		     bts->nr, container->msg_type);
diff --git a/src/pcu_l1_if.h b/src/pcu_l1_if.h
index 2a4f0ea..3b14588 100644
--- a/src/pcu_l1_if.h
+++ b/src/pcu_l1_if.h
@@ -35,6 +35,7 @@
 #endif
 
 #include "pdch.h"
+#include "pcu_utils.h"
 
 static inline uint8_t qta2ta(int16_t qta)
 {
@@ -160,6 +161,9 @@
 #endif
 struct gprs_rlcmac_bts;
 
+int pcu_tx_anr_cnf(struct gprs_rlcmac_bts *bts, const struct arfcn_bsic *cell_list,
+			  const uint8_t *meas_list, unsigned int num_cells);
+
 int pcu_rx(struct gsm_pcu_if *pcu_prim, size_t pcu_prim_length);
 int pcu_l1if_open(void);
 void pcu_l1if_close(void);
diff --git a/src/pcu_utils.h b/src/pcu_utils.h
index e1a8572..c19449b 100644
--- a/src/pcu_utils.h
+++ b/src/pcu_utils.h
@@ -93,3 +93,8 @@
 	struct llist_head list; /* item used by llist */
 	void *entry;
 };
+
+struct arfcn_bsic {
+	uint16_t arfcn;
+	uint8_t bsic;
+};
diff --git a/src/pdch.cpp b/src/pdch.cpp
index 2ec40ce..5f35c28 100644
--- a/src/pdch.cpp
+++ b/src/pdch.cpp
@@ -48,6 +48,7 @@
 #include "coding_scheme.h"
 #include "gsm_rlcmac.h"
 #include "nacc_fsm.h"
+#include "ms_anr_fsm.h"
 }
 
 #include <errno.h>
@@ -425,6 +426,11 @@
 		 * switch to a new cell."
 		 */
 		return;
+	} else if (reason == PDCH_ULC_POLL_MEAS_ORDER && ms->anr &&
+		   (ms->anr->fi->state == MS_ANR_ST_WAIT_CTRL_ACK1 ||  ms->anr->fi->state == MS_ANR_ST_WAIT_CTRL_ACK2)
+		   && ms->anr->poll_fn == fn && ms->anr->poll_ts == ts_no) {
+		osmo_fsm_inst_dispatch(ms->anr->fi, MS_ANR_EV_RX_PKT_CTRL_ACK_MSG, NULL);
+		return;
 	}
 	LOGPDCH(this, DRLCMAC, LOGL_ERROR, "FN=%" PRIu32 " "
 		"Error: received PACKET CONTROL ACK at no request (reason=%s)\n", fn,
diff --git a/src/pdch_ul_controller.c b/src/pdch_ul_controller.c
index e7a721c..9730fa1 100644
--- a/src/pdch_ul_controller.c
+++ b/src/pdch_ul_controller.c
@@ -44,6 +44,7 @@
 	{ PDCH_ULC_POLL_UL_ACK, "UL_ACK" },
 	{ PDCH_ULC_POLL_DL_ACK, "DL_ACK" },
 	{ PDCH_ULC_POLL_CELL_CHG_CONTINUE, "CELL_CHG_CONTINUE" },
+	{ PDCH_ULC_POLL_MEAS_ORDER, "MEAS_ORDER" },
 	{ 0, NULL }
 };
 
diff --git a/src/pdch_ul_controller.h b/src/pdch_ul_controller.h
index c56945f..3b34fd5 100644
--- a/src/pdch_ul_controller.h
+++ b/src/pdch_ul_controller.h
@@ -58,6 +58,7 @@
 	PDCH_ULC_POLL_UL_ACK, /* Expect CTRL ACK (or PKT RES REQ on final UL ACK/NACK) for UL ACK/NACK we transmit */
 	PDCH_ULC_POLL_DL_ACK, /* Expect DL ACK/NACK requested by RRBP */
 	PDCH_ULC_POLL_CELL_CHG_CONTINUE, /* Expect CTRL ACK for Pkt cell Change Continue we transmit */
+	PDCH_ULC_POLL_MEAS_ORDER, /* Expect CTRL ACK for Pkt Measurement Order we transmit */
 };
 extern const struct value_string pdch_ulc_tbf_poll_reason_names[];
 
diff --git a/src/tbf.cpp b/src/tbf.cpp
index e83f472..2ae1921 100644
--- a/src/tbf.cpp
+++ b/src/tbf.cpp
@@ -50,6 +50,7 @@
 #include "gsm_rlcmac.h"
 #include "coding_scheme.h"
 #include "nacc_fsm.h"
+#include "ms_anr_fsm.h"
 }
 
 #include <errno.h>
@@ -617,6 +618,10 @@
 		LOGPTBFDL(this, LOGL_DEBUG, "Scheduled 'Packet Cell Change Continue' polling on %s (FN=%d, TS=%d)\n",
 			  chan, new_poll_fn, ts);
 		break;
+	case PDCH_ULC_POLL_MEAS_ORDER:
+		LOGPTBFDL(this, LOGL_DEBUG, "Scheduled 'Packet Measurement Order' polling on %s (FN=%d, TS=%d)\n",
+			  chan, new_poll_fn, ts);
+		break;
 	}
 }
 
@@ -725,6 +730,13 @@
 			bts_snd_dl_ass(dl_tbf->bts, dl_tbf, pgroup);
 			dl_tbf->m_wait_confirm = 1;
 		}
+
+		if (m_ms->anr &&
+		    (m_ms->anr->fi->state == MS_ANR_ST_WAIT_CTRL_ACK1 || m_ms->anr->fi->state == MS_ANR_ST_WAIT_CTRL_ACK2) &&
+		    m_ms->anr->poll_fn == poll_fn && m_ms->anr->poll_ts == pdch->ts_no) {
+			/* Timeout waiting for CTRL ACK acking Pkt Meas Order */
+			osmo_fsm_inst_dispatch(m_ms->anr->fi, MS_ANR_EV_RX_PKT_CTRL_ACK_TIMEOUT, NULL);
+		}
 	} else
 		LOGPTBF(this, LOGL_ERROR, "Poll Timeout, but no event!\n");
 }
diff --git a/src/tbf_dl.cpp b/src/tbf_dl.cpp
index eb215fe..df3da77 100644
--- a/src/tbf_dl.cpp
+++ b/src/tbf_dl.cpp
@@ -49,6 +49,7 @@
 	#include <osmocom/gsm/gsm_utils.h>
 	#include <osmocom/gsm/protocol/gsm_04_08.h>
 	#include "coding_scheme.h"
+	#include "ms_anr_fsm.h"
 }
 
 #include <errno.h>
@@ -229,13 +230,14 @@
 	return 0;
 }
 
-static int tbf_new_dl_assignment(struct gprs_rlcmac_bts *bts, GprsMs *ms,
+int tbf_new_dl_assignment(struct gprs_rlcmac_bts *bts, struct GprsMs *ms,
 				 struct gprs_rlcmac_dl_tbf **tbf)
 {
 	bool ss;
 	int8_t use_trx;
 	struct gprs_rlcmac_ul_tbf *ul_tbf = NULL, *old_ul_tbf;
 	struct gprs_rlcmac_dl_tbf *dl_tbf = NULL;
+	*tbf = NULL;
 
 	ul_tbf = ms_ul_tbf(ms);
 
@@ -252,6 +254,8 @@
 		use_trx = -1;
 		ss = true; /* PCH assignment only allows one timeslot */
 		old_ul_tbf = NULL;
+		if (!ms_imsi_valid(ms)) /* We'll need imsi to potentially page it on CCCH */
+			return -1;
 	}
 
 	// Create new TBF (any TRX)
@@ -1365,6 +1369,10 @@
 	int since_last_drain;
 	bool keep;
 
+	/* ongoing ANR procedure, don't close the TBF */
+	if (ms_anr_tbf_keep_open(ms(), (const struct gprs_rlcmac_tbf *)this))
+		return true;
+
 	dl_tbf_idle_msec = osmo_tdef_get(the_pcu->T_defs, -2031, OSMO_TDEF_MS, -1);
 	if (dl_tbf_idle_msec == 0)
 		return false;
@@ -1572,3 +1580,9 @@
 	else
 		return NULL;
 }
+
+int dl_tbf_append_data(struct gprs_rlcmac_dl_tbf *dl_tbf, uint16_t pdu_delay_csec,
+		const uint8_t *data, uint16_t len)
+{
+	return dl_tbf->append_data(pdu_delay_csec, data, len);
+}
diff --git a/src/tbf_dl.h b/src/tbf_dl.h
index 58d863b..e317f51 100644
--- a/src/tbf_dl.h
+++ b/src/tbf_dl.h
@@ -156,6 +156,12 @@
 		  const char *imsi, const uint8_t ms_class,
 		  const uint8_t egprs_ms_class, const uint16_t delay_csec,
 		  const uint8_t *data, const uint16_t len);
+/* Schedule new Dl TBF Assignment */
+int tbf_new_dl_assignment(struct gprs_rlcmac_bts *bts, struct GprsMs *ms,
+				 struct gprs_rlcmac_dl_tbf **tbf);
+
+int dl_tbf_append_data(struct gprs_rlcmac_dl_tbf *dl_tbf, uint16_t pdu_delay_csec,
+		const uint8_t *data, uint16_t len);
 
 #ifdef __cplusplus
 }