VOL-2172: Deleting tech-profile at ONU
- Handle DELETE_GEM_PORT_REQUEST and DELETE_TCONT_REQ inter-adapter-message.
- Introduce a new OMCI task BrcmTpDeleteTask to delete GemPorts and TCONT
- When tech-profile download is already done, check if it is case
  where new gem-ports are being added dynamically. If new gem-ports
  are detected in TpInstance, add them.
- Rename BrcmTpServiceSpecificTask to BrcmTpSetupTask
- Move setting up of IEEE8021pMapper and ANI MacBridgePortConfigData
  to BrcmTpSetupTask (when TCONT is being setup). There should be
  unique IEEE8021pMapper and ANI MacBridgePortConfigData per TCONT.
- When TCONT is removed, remove IEEE8021pMapper and ANI MacBridgePortConfigData.
- Ensure IEEE8021pMapper and ANI MacBridgePortConfigData have element of
  TP-Table ID in its entity ID.
- GemPort Entity ID set to be same as GemPort ID and not dynamically generated.
- Fix code indentations
- Bump voltha proto version to 2.1.1
- Bump pyvoltha version to 2.3.2

Change-Id: Ie4a90d6cd6916e27a6e32b3727b161252cb80ca3
diff --git a/python/adapters/brcm_openomci_onu/omci/brcm_mib_download_task.py b/python/adapters/brcm_openomci_onu/omci/brcm_mib_download_task.py
index f09379b..e8b0841 100644
--- a/python/adapters/brcm_openomci_onu/omci/brcm_mib_download_task.py
+++ b/python/adapters/brcm_openomci_onu/omci/brcm_mib_download_task.py
@@ -279,51 +279,6 @@
             self.check_status_and_state(results, 'create-mac-bridge-service-profile')
 
             ################################################################################
-            # PON Specific                                                                 #
-            ################################################################################
-            # IEEE 802.1 Mapper Service config - Once per PON
-            #
-            #  EntityID will be referenced by:
-            #            - MAC Bridge Port Configuration Data for the PON port
-            #  References:
-            #            - Nothing at this point. When a GEM port is created, this entity will
-            #              be updated to reference the GEM Interworking TP
-
-            msg = Ieee8021pMapperServiceProfileFrame(self._ieee_mapper_service_profile_entity_id + uni_port.mac_bridge_port_num)
-            frame = msg.create()
-            self.log.debug('openomci-msg', omci_msg=msg)
-            results = yield omci_cc.send(frame)
-            self.check_status_and_state(results, 'create-8021p-mapper-service-profile')
-
-            ################################################################################
-            # Create MAC Bridge Port Configuration Data for the PON port via IEEE 802.1
-            # mapper service. Upon receipt by the ONU, the ONU will create an instance
-            # of the following before returning the response.
-            #
-            #     - MAC bridge port designation data
-            #     - MAC bridge port filter table data
-            #     - MAC bridge port bridge table data
-            #
-            #  EntityID will be referenced by:
-            #            - Implicitly by the VLAN tagging filter data
-            #  References:
-            #            - MAC Bridge Service Profile (the bridge)
-            #            - IEEE 802.1p mapper service profile for PON port
-
-            # TODO: magic. make a static variable for tp_type
-            msg = MacBridgePortConfigurationDataFrame(
-                self._mac_bridge_port_ani_entity_id + uni_port.mac_bridge_port_num,
-                bridge_id_pointer=self._mac_bridge_service_profile_entity_id + uni_port.mac_bridge_port_num,  # Bridge Entity ID
-                port_num= 0xff, # Port ID - unique number within the bridge
-                tp_type=3, # TP Type (IEEE 802.1p mapper service)
-                tp_pointer=self._ieee_mapper_service_profile_entity_id + uni_port.mac_bridge_port_num  # TP ID, 8021p mapper ID
-            )
-            frame = msg.create()
-            self.log.debug('openomci-msg', omci_msg=msg)
-            results = yield omci_cc.send(frame)
-            self.check_status_and_state(results, 'create-mac-bridge-port-configuration-data-8021p-mapper')
-
-            ################################################################################
             # UNI Specific                                                                 #
             ################################################################################
             # MAC Bridge Port config
diff --git a/python/adapters/brcm_openomci_onu/omci/brcm_tp_delete_task.py b/python/adapters/brcm_openomci_onu/omci/brcm_tp_delete_task.py
new file mode 100644
index 0000000..a5619c7
--- /dev/null
+++ b/python/adapters/brcm_openomci_onu/omci/brcm_tp_delete_task.py
@@ -0,0 +1,285 @@
+#
+# Copyright 2018 the original author or authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import
+import structlog
+from twisted.internet import reactor
+from twisted.internet.defer import inlineCallbacks, TimeoutError, failure
+from pyvoltha.adapters.extensions.omci.omci_me import Ont2G, OmciNullPointer, PriorityQueueFrame, \
+    Ieee8021pMapperServiceProfileFrame, MacBridgePortConfigurationDataFrame
+from pyvoltha.adapters.extensions.omci.tasks.task import Task
+from pyvoltha.adapters.extensions.omci.omci_defs import EntityOperations, ReasonCodes
+from pyvoltha.adapters.extensions.omci.omci_entities import OntG, Tcont, PriorityQueueG
+
+OP = EntityOperations
+RC = ReasonCodes
+
+# The DELETE_TP_TASK_PRIORITY should be higher than SETUP_TP_TASK_PRIORITY
+DELETE_TP_TASK_PRIORITY = 250
+
+
+class TechProfileDeleteFailure(Exception):
+    """
+    This error is raised by default when the delete fails
+    """
+
+
+class TechProfileResourcesFailure(Exception):
+    """
+    This error is raised by when one or more resources required is not available
+    """
+
+
+class BrcmTpDeleteTask(Task):
+    """
+    OpenOMCI Tech-Profile Delete Task
+
+    """
+
+    name = "Broadcom Tech-Profile Delete Task"
+
+    def __init__(self, omci_agent, handler, uni_id, tp_table_id,
+                 tcont=None, gem_port=None):
+        """
+        Class initialization
+
+        :param omci_agent: (OmciAdapterAgent) OMCI Adapter agent
+        :param handler: (BrcmOpenomciOnuHandler) ONU Device Handler Instance
+        :param uni_id: (int) numeric id of the uni port on the onu device, starts at 0
+        :param tp_table_id: (int) Technology Profile Table-ID
+        """
+        log = structlog.get_logger(device_id=handler.device_id, uni_id=uni_id)
+        log.debug('function-entry')
+
+        super(BrcmTpDeleteTask, self).__init__(BrcmTpDeleteTask.name,
+                                               omci_agent,
+                                               handler.device_id,
+                                               priority=DELETE_TP_TASK_PRIORITY,
+                                               exclusive=True)
+
+        self.log = log
+
+        self._onu_device = omci_agent.get_device(handler.device_id)
+        self._local_deferred = None
+
+        self._uni_port = handler.uni_ports[uni_id]
+        assert self._uni_port.uni_id == uni_id
+
+        # Tech Profile Table ID
+        self._tp_table_id = tp_table_id
+
+        self._tcont = tcont
+        self._gem_port = gem_port
+
+        self._alloc_id = self._tcont.alloc_id if self._tcont else None
+        self._gem_port_id = self._gem_port.gem_id if gem_port else None
+
+        # Entity IDs. IDs with values can probably be most anything for most ONUs,
+        #             IDs set to None are discovered/set
+        self._mac_bridge_service_profile_entity_id = \
+            handler.mac_bridge_service_profile_entity_id
+        self._ieee_mapper_service_profile_entity_id = \
+            handler.pon_port.ieee_mapper_service_profile_entity_id
+        self._mac_bridge_port_ani_entity_id = \
+            handler.pon_port.mac_bridge_port_ani_entity_id
+
+    def cancel_deferred(self):
+        self.log.debug('function-entry')
+        super(BrcmTpDeleteTask, self).cancel_deferred()
+
+        d, self._local_deferred = self._local_deferred, None
+        try:
+            if d is not None and not d.called:
+                d.cancel()
+        except:
+            pass
+
+    def start(self):
+        """
+        Start the Tech-Profile Delete
+        """
+        self.log.debug('function-entry')
+        super(BrcmTpDeleteTask, self).start()
+        if self._tcont is not None:
+            self._local_deferred = reactor.callLater(0, self.delete_tcont_and_associated_me)
+        elif self._gem_port is not None:
+            self._local_deferred = reactor.callLater(0, self.delete_gem_port_nw_ctp_and_associated_me)
+        else:
+            raise Exception("both-alloc-id-and-gem-port-id-are-none")
+
+    def stop(self):
+        """
+        Shutdown Tech-Profile delete tasks
+        """
+        self.log.debug('function-entry')
+        self.log.debug('stopping')
+
+        self.cancel_deferred()
+        super(BrcmTpDeleteTask, self).stop()
+
+    def check_status_and_state(self, results, operation=''):
+        """
+        Check the results of an OMCI response.  An exception is thrown
+        if the task was cancelled or an error was detected.
+
+        :param results: (OmciFrame) OMCI Response frame
+        :param operation: (str) what operation was being performed
+        :return: True if successful, False if the entity existed (already created)
+        """
+        self.log.debug('function-entry')
+
+        omci_msg = results.fields['omci_message'].fields
+        status = omci_msg['success_code']
+        error_mask = omci_msg.get('parameter_error_attributes_mask', 'n/a')
+        failed_mask = omci_msg.get('failed_attributes_mask', 'n/a')
+        unsupported_mask = omci_msg.get('unsupported_attributes_mask', 'n/a')
+
+        self.log.debug("OMCI Result", operation=operation, omci_msg=omci_msg, status=status, error_mask=error_mask,
+                       failed_mask=failed_mask, unsupported_mask=unsupported_mask)
+
+        if status == RC.Success:
+            self.strobe_watchdog()
+            return True
+
+        elif status == RC.InstanceExists:
+            return False
+
+        raise TechProfileDeleteFailure(
+            '{} failed with a status of {}, error_mask: {}, failed_mask: {}, '
+            'unsupported_mask: {}'.format(operation, status, error_mask, failed_mask, unsupported_mask))
+
+    @inlineCallbacks
+    def delete_tcont_and_associated_me(self):
+        self.log.debug('function-entry')
+
+        omci_cc = self._onu_device.omci_cc
+
+        try:
+            ################################################################################
+            # Reset TCONT ME
+            ################################################################################
+
+            tcont_idents = self._onu_device.query_mib(Tcont.class_id)
+            self.log.debug('tcont-idents', tcont_idents=tcont_idents)
+            tcont_entity_id = None
+            for k, v in tcont_idents.items():
+                if not isinstance(v, dict):
+                    continue
+                alloc_check = v.get('attributes', {}).get('alloc_id', 0)
+                # Some onu report both to indicate an available tcont
+                if alloc_check == self._alloc_id:
+                    tcont_entity_id = k
+                    break
+
+            if tcont_entity_id is None:
+                self.log.error("tcont-not-found-for-delete", alloc_id=self._alloc_id)
+                return
+
+            self.log.debug('found-tcont', tcont_entity_id=tcont_entity_id, alloc_id=self._alloc_id)
+
+            # Remove the TCONT (rather reset the TCONT to point alloc_id to 0xffff)
+            # The _tcont.remove_from_hardware is already doing check_status_and_state
+            yield self._tcont.remove_from_hardware(omci_cc)
+
+            # At this point, the gem-ports should have been removed already.
+            # Remove the 8021p Mapper and ANI MacBridgePortConfigData
+            yield self._delete__8021p_mapper__ani_mac_bridge_port()
+
+            # There are no other associated MEs now.
+            # There might be TrafficScheduler MEs that point to a TCONT.
+            # TrafficScheduler ME not used currently.
+
+            self.deferred.callback("tech-profile-remove-success--tcont")
+
+        except TimeoutError as e:
+            self.log.warn('rx-timeout-tech-profile', e=e)
+            self.deferred.errback(failure.Failure(e))
+
+        except Exception as e:
+            self.log.exception('omci-delete-tech-profile', e=e)
+            self.deferred.errback(failure.Failure(e))
+
+    @inlineCallbacks
+    def delete_gem_port_nw_ctp_and_associated_me(self):
+        omci_cc = self._onu_device.omci_cc
+        try:
+            ################################################################################
+            # Delete GemPortNetworkCTP and GemPortInterworkingPoint
+            ################################################################################
+            # The _gem_port.remove_from_hardware is already doing check_status_and_state
+            yield self._gem_port.remove_from_hardware(omci_cc)
+
+            self.deferred.callback("tech-profile-remove-success--gem-port")
+
+        except TimeoutError as e:
+            self.log.warn('rx-timeout-tech-profile', e=e)
+            self.deferred.errback(failure.Failure(e))
+
+        except Exception as e:
+            self.log.exception('omci-delete-tech-profile', e=e)
+            self.deferred.errback(failure.Failure(e))
+
+    @inlineCallbacks
+    def _delete__8021p_mapper__ani_mac_bridge_port(self):
+
+        omci_cc = self._onu_device.omci_cc
+
+        try:
+            ################################################################################
+            # Delete 8021p mapper
+            ################################################################################
+            msg = Ieee8021pMapperServiceProfileFrame(
+                self._ieee_mapper_service_profile_entity_id +
+                self._uni_port.mac_bridge_port_num +
+                self._tp_table_id
+            )
+            frame = msg.delete()
+            self.log.debug('openomci-msg', omci_msg=msg)
+            results = yield omci_cc.send(frame)
+            self.check_status_and_state(results, 'delete-8021p-mapper-service-profile')
+
+            ################################################################################
+            # Delete MacBridgePortConfigData
+            ################################################################################
+            # TODO: magic. make a static variable for tp_type
+            msg = MacBridgePortConfigurationDataFrame(
+                self._mac_bridge_port_ani_entity_id + self._uni_port.mac_bridge_port_num + self._tp_table_id,
+                bridge_id_pointer=(
+                        self._mac_bridge_service_profile_entity_id +
+                        self._uni_port.mac_bridge_port_num +
+                        self._tp_table_id
+                ),
+                # Bridge Entity ID
+                port_num=0xff,  # Port ID - unique number within the bridge
+                tp_type=3,  # TP Type (IEEE 802.1p mapper service)
+                tp_pointer=(
+                        self._ieee_mapper_service_profile_entity_id +
+                        self._uni_port.mac_bridge_port_num +
+                        self._tp_table_id
+                )
+                # TP ID, 8021p mapper ID
+            )
+            frame = msg.delete()
+            self.log.debug('openomci-msg', omci_msg=msg)
+            results = yield omci_cc.send(frame)
+            self.check_status_and_state(results, 'delete-mac-bridge-port-configuration-data-8021p-mapper')
+
+        except TimeoutError as e:
+            self.log.warn('rx-timeout-8021p-ani-port-delete', e=e)
+            raise
+
+        except Exception as e:
+            self.log.exception('omci-delete-8021p-ani-port-delete', e=e)
+            raise
diff --git a/python/adapters/brcm_openomci_onu/omci/brcm_tp_service_specific_task.py b/python/adapters/brcm_openomci_onu/omci/brcm_tp_setup_task.py
similarity index 67%
rename from python/adapters/brcm_openomci_onu/omci/brcm_tp_service_specific_task.py
rename to python/adapters/brcm_openomci_onu/omci/brcm_tp_setup_task.py
index 62a1e51..6a1bacb 100644
--- a/python/adapters/brcm_openomci_onu/omci/brcm_tp_service_specific_task.py
+++ b/python/adapters/brcm_openomci_onu/omci/brcm_tp_setup_task.py
@@ -18,16 +18,16 @@
 from twisted.internet import reactor
 from twisted.internet.defer import inlineCallbacks, TimeoutError, failure
 from pyvoltha.adapters.extensions.omci.omci_me import Ont2G, OmciNullPointer, PriorityQueueFrame, \
-    Ieee8021pMapperServiceProfileFrame
+    Ieee8021pMapperServiceProfileFrame, MacBridgePortConfigurationDataFrame
 from pyvoltha.adapters.extensions.omci.tasks.task import Task
 from pyvoltha.adapters.extensions.omci.omci_defs import EntityOperations, ReasonCodes
-from pyvoltha.adapters.extensions.omci.omci_entities import OntG, Tcont, PriorityQueueG
-from pon_port import TASK_PRIORITY
-
+from pyvoltha.adapters.extensions.omci.omci_entities import OntG, Tcont, PriorityQueueG, Ieee8021pMapperServiceProfile
 
 OP = EntityOperations
 RC = ReasonCodes
 
+SETUP_TP_TASK_PRIORITY = 240
+
 
 class TechProfileDownloadFailure(Exception):
     """
@@ -41,7 +41,7 @@
     """
 
 
-class BrcmTpServiceSpecificTask(Task):
+class BrcmTpSetupTask(Task):
     """
     OpenOMCI Tech-Profile Download Task
 
@@ -49,22 +49,23 @@
 
     name = "Broadcom Tech-Profile Download Task"
 
-    def __init__(self, omci_agent, handler, uni_id):
+    def __init__(self, omci_agent, handler, uni_id, tconts, gem_ports, tp_table_id):
         """
         Class initialization
 
         :param omci_agent: (OmciAdapterAgent) OMCI Adapter agent
         :param handler: (BrcmOpenomciOnuHandler) ONU Device Handler Instance
         :param uni_id: (int) numeric id of the uni port on the onu device, starts at 0
+        :param tp_table_id: (int) Technology Profile Table-ID
         """
         log = structlog.get_logger(device_id=handler.device_id, uni_id=uni_id)
         log.debug('function-entry')
 
-        super(BrcmTpServiceSpecificTask, self).__init__(BrcmTpServiceSpecificTask.name,
-                                                        omci_agent,
-                                                        handler.device_id,
-                                                        priority=TASK_PRIORITY,
-                                                        exclusive=True)
+        super(BrcmTpSetupTask, self).__init__(BrcmTpSetupTask.name,
+                                              omci_agent,
+                                              handler.device_id,
+                                              priority=SETUP_TP_TASK_PRIORITY,
+                                              exclusive=True)
 
         self.log = log
 
@@ -74,6 +75,9 @@
         self._uni_port = handler.uni_ports[uni_id]
         assert self._uni_port.uni_id == uni_id
 
+        # Tech Profile Table ID
+        self._tp_table_id = tp_table_id
+
         # Entity IDs. IDs with values can probably be most anything for most ONUs,
         #             IDs set to None are discovered/set
 
@@ -86,26 +90,20 @@
         self._gal_enet_profile_entity_id = \
             handler.gal_enet_profile_entity_id
 
-        # Extract the current set of TCONT and GEM Ports from the Handler's pon_port that are
-        # relevant to this task's UNI. It won't change. But, the underlying pon_port may change
-        # due to additional tasks on different UNIs. So, it we cannot use the pon_port affter
-        # this initializer
         self._tconts = []
-        for tcont in list(handler.pon_port.tconts.values()):
-            if tcont.uni_id is not None and tcont.uni_id != self._uni_port.uni_id: continue
-            self._tconts.append(tcont)
+        for t in tconts:
+            self._tconts.append(t)
 
         self._gem_ports = []
-        for gem_port in list(handler.pon_port.gem_ports.values()):
-            if gem_port.uni_id is not None and gem_port.uni_id != self._uni_port.uni_id: continue
-            self._gem_ports.append(gem_port)
+        for g in gem_ports:
+            self._gem_ports.append(g)
 
         self.tcont_me_to_queue_map = dict()
         self.uni_port_to_queue_map = dict()
 
     def cancel_deferred(self):
         self.log.debug('function-entry')
-        super(BrcmTpServiceSpecificTask, self).cancel_deferred()
+        super(BrcmTpSetupTask, self).cancel_deferred()
 
         d, self._local_deferred = self._local_deferred, None
         try:
@@ -119,7 +117,7 @@
         Start the Tech-Profile Download
         """
         self.log.debug('function-entry')
-        super(BrcmTpServiceSpecificTask, self).start()
+        super(BrcmTpSetupTask, self).start()
         self._local_deferred = reactor.callLater(0, self.perform_service_specific_steps)
 
     def stop(self):
@@ -130,7 +128,7 @@
         self.log.debug('stopping')
 
         self.cancel_deferred()
-        super(BrcmTpServiceSpecificTask, self).stop()
+        super(BrcmTpSetupTask, self).stop()
 
     def check_status_and_state(self, results, operation=''):
         """
@@ -160,8 +158,8 @@
             return False
 
         raise TechProfileDownloadFailure(
-            '{} failed with a status of {}, error_mask: {}, failed_mask: {}, unsupported_mask: {}'
-            .format(operation, status, error_mask, failed_mask, unsupported_mask))
+            '{} failed with a status of {}, error_mask: {}, failed_mask: {}, '
+            'unsupported_mask: {}'.format(operation, status, error_mask, failed_mask, unsupported_mask))
 
     @inlineCallbacks
     def perform_service_specific_steps(self):
@@ -181,6 +179,22 @@
             #  References:
             #            - ONU created TCONT (created on ONU startup)
 
+            # Setup 8021p mapper and ani mac bridge port, if it does not exist
+            # Querying just 8021p mapper ME should be enough since we create and
+            # delete 8021pMapper and ANI Mac Bridge Port together.
+            ieee_8021p_mapper_exists = False
+            ieee_8021p_mapper = self._onu_device.query_mib(Ieee8021pMapperServiceProfile.class_id)
+            for k, v in ieee_8021p_mapper.items():
+                if not isinstance(v, dict):
+                    continue
+                if k == (self._ieee_mapper_service_profile_entity_id +
+                         self._uni_port.mac_bridge_port_num + self._tp_table_id):
+                    ieee_8021p_mapper_exists = True
+
+            if ieee_8021p_mapper_exists is False:
+                self.log.info("setting-up-8021pmapper-ani-mac-bridge-port")
+                yield self._setup__8021p_mapper__ani_mac_bridge_port()
+
             tcont_idents = self._onu_device.query_mib(Tcont.class_id)
             self.log.debug('tcont-idents', tcont_idents=tcont_idents)
 
@@ -266,23 +280,22 @@
                         tcont_me = (related_port & 0xffff0000) >> 16
                         if tcont_me not in self.tcont_me_to_queue_map:
                             self.log.debug("prior-q-related-port-and-tcont-me",
-                                            related_port=related_port,
-                                            tcont_me=tcont_me)
+                                           related_port=related_port,
+                                           tcont_me=tcont_me)
                             self.tcont_me_to_queue_map[tcont_me] = list()
 
                         self.tcont_me_to_queue_map[tcont_me].append(k)
                     else:
                         uni_port = (related_port & 0xffff0000) >> 16
-                        if uni_port ==  self._uni_port.entity_id:
+                        if uni_port == self._uni_port.entity_id:
                             if uni_port not in self.uni_port_to_queue_map:
                                 self.log.debug("prior-q-related-port-and-uni-port-me",
-                                                related_port=related_port,
-                                                uni_port_me=uni_port)
+                                               related_port=related_port,
+                                               uni_port_me=uni_port)
                                 self.uni_port_to_queue_map[uni_port] = list()
 
                             self.uni_port_to_queue_map[uni_port].append(k)
 
-
             self.log.debug("ul-prior-q", ul_prior_q=self.tcont_me_to_queue_map)
             self.log.debug("dl-prior-q", dl_prior_q=self.uni_port_to_queue_map)
 
@@ -293,8 +306,6 @@
                     self.log.error('unknown-tcont-reference', gem_id=gem_port.gem_id)
                     continue
 
-                ul_prior_q_entity_id = None
-                dl_prior_q_entity_id = None
                 if gem_port.direction == "upstream" or \
                         gem_port.direction == "bi-directional":
 
@@ -324,11 +335,12 @@
 
                     # TODO: Need to restore on failure.  Need to check status/results
                     results = yield gem_port.add_to_hardware(omci_cc,
-                                             tcont.entity_id,
-                                             self._ieee_mapper_service_profile_entity_id +
-                                                      self._uni_port.mac_bridge_port_num,
-                                             self._gal_enet_profile_entity_id,
-                                             ul_prior_q_entity_id, dl_prior_q_entity_id)
+                                                             tcont.entity_id,
+                                                             self._ieee_mapper_service_profile_entity_id +
+                                                             self._uni_port.mac_bridge_port_num +
+                                                             self._tp_table_id,
+                                                             self._gal_enet_profile_entity_id,
+                                                             ul_prior_q_entity_id, dl_prior_q_entity_id)
                     self.check_status_and_state(results, 'assign-gem-port')
                 elif gem_port.direction == "downstream":
                     # Downstream is inverse of upstream
@@ -344,10 +356,10 @@
             #
 
             ont2g = self._onu_device.query_mib(Ont2G.class_id)
-            qos_config_flexibility_ie = ont2g.get(0, {}).get('attributes', {}).\
-                                        get('qos_configuration_flexibility', None)
+            qos_config_flexibility_ie = ont2g.get(0, {}).get('attributes', {}). \
+                get('qos_configuration_flexibility', None)
             self.log.debug("qos_config_flexibility",
-                            qos_config_flexibility=qos_config_flexibility_ie)
+                           qos_config_flexibility=qos_config_flexibility_ie)
 
             if qos_config_flexibility_ie & 0b100000:
                 is_related_ports_configurable = True
@@ -364,13 +376,12 @@
                     self.log.debug("updating-pq-priority")
                     related_port = pq_to_related_port[v["pq_entity_id"]]
                     related_port = related_port & 0xffff0000
-                    related_port = related_port | v['priority_q'] # Set priority
+                    related_port = related_port | v['priority_q']  # Set priority
                     msg = PriorityQueueFrame(v["pq_entity_id"], related_port=related_port)
                     frame = msg.set()
                     results = yield omci_cc.send(frame)
                     self.check_status_and_state(results, 'set-priority-queues-priority')
 
-
             ################################################################################
             # Update the IEEE 802.1p Mapper Service Profile config
             #
@@ -381,6 +392,23 @@
             #
 
             gem_entity_ids = [OmciNullPointer] * 8
+            # If IEEE8021pMapper ME existed already, then we need to re-build the
+            # inter-working-tp-pointers for different gem-entity-ids.
+            if ieee_8021p_mapper_exists:
+                self.log.debug("rebuilding-interworking-tp-pointers")
+                for k, v in ieee_8021p_mapper.items():
+                    if not isinstance(v, dict):
+                        continue
+                    # Check the entity-id of the instance matches what we expect
+                    # for this Uni/TechProfileId
+                    if k == (self._ieee_mapper_service_profile_entity_id +
+                             self._uni_port.mac_bridge_port_num + self._tp_table_id):
+                        for i in range(len(gem_entity_ids)):
+                            gem_entity_ids[i] = v.get('attributes', {}). \
+                                get('interwork_tp_pointer_for_p_bit_priority_' + str(i), OmciNullPointer)
+                        self.log.debug("interworking-tp-pointers-rebuilt-after-query-from-onu",
+                                       i_w_tp_ptr=gem_entity_ids)
+
             for gem_port in self._gem_ports:
                 self.log.debug("tp-gem-port", entity_id=gem_port.entity_id, uni_id=gem_port.uni_id)
 
@@ -395,7 +423,9 @@
                     pass
 
             msg = Ieee8021pMapperServiceProfileFrame(
-                self._ieee_mapper_service_profile_entity_id + self._uni_port.mac_bridge_port_num,  # 802.1p mapper Service Mapper Profile ID
+                (self._ieee_mapper_service_profile_entity_id +
+                 self._uni_port.mac_bridge_port_num + self._tp_table_id),
+                # 802.1p mapper Service Mapper Profile ID
                 interwork_tp_pointers=gem_entity_ids  # Interworking TP IDs
             )
             frame = msg.set()
@@ -412,3 +442,74 @@
         except Exception as e:
             self.log.exception('omci-setup-tech-profile', e=e)
             self.deferred.errback(failure.Failure(e))
+
+    @inlineCallbacks
+    def _setup__8021p_mapper__ani_mac_bridge_port(self):
+
+        omci_cc = self._onu_device.omci_cc
+
+        try:
+            ################################################################################
+            # PON Specific                                                                 #
+            ################################################################################
+            # IEEE 802.1 Mapper Service config - One per tech-profile per UNI
+            #
+            #  EntityID will be referenced by:
+            #            - MAC Bridge Port Configuration Data for the PON port and TP ID
+            #  References:
+            #            - Nothing at this point. When a GEM port is created, this entity will
+            #              be updated to reference the GEM Interworking TP
+
+            msg = Ieee8021pMapperServiceProfileFrame(
+                self._ieee_mapper_service_profile_entity_id +
+                self._uni_port.mac_bridge_port_num +
+                self._tp_table_id
+            )
+            frame = msg.create()
+            self.log.debug('openomci-msg', omci_msg=msg)
+            results = yield omci_cc.send(frame)
+            self.check_status_and_state(results, 'create-8021p-mapper-service-profile')
+
+            ################################################################################
+            # Create MAC Bridge Port Configuration Data for the PON port via IEEE 802.1
+            # mapper service and this per TechProfile. Upon receipt by the ONU, the ONU will create an instance
+            # of the following before returning the response.
+            #
+            #     - MAC bridge port designation data
+            #     - MAC bridge port filter table data
+            #     - MAC bridge port bridge table data
+            #
+            #  EntityID will be referenced by:
+            #            - Implicitly by the VLAN tagging filter data
+            #  References:
+            #            - MAC Bridge Service Profile (the bridge)
+            #            - IEEE 802.1p mapper service profile for PON port
+
+            # TODO: magic. make a static variable for tp_type
+            msg = MacBridgePortConfigurationDataFrame(
+                self._mac_bridge_port_ani_entity_id + self._uni_port.mac_bridge_port_num + self._tp_table_id,
+                bridge_id_pointer=(
+                        self._mac_bridge_service_profile_entity_id +
+                        self._uni_port.mac_bridge_port_num),
+                # Bridge Entity ID
+                port_num=0xff,  # Port ID - unique number within the bridge
+                tp_type=3,  # TP Type (IEEE 802.1p mapper service)
+                tp_pointer=(
+                        self._ieee_mapper_service_profile_entity_id +
+                        self._uni_port.mac_bridge_port_num +
+                        self._tp_table_id
+                )
+                # TP ID, 8021p mapper ID
+            )
+            frame = msg.create()
+            self.log.debug('openomci-msg', omci_msg=msg)
+            results = yield omci_cc.send(frame)
+            self.check_status_and_state(results, 'create-mac-bridge-port-configuration-data-8021p-mapper')
+
+        except TimeoutError as e:
+            self.log.warn('rx-timeout-8021p-ani-port-setup', e=e)
+            raise
+
+        except Exception as e:
+            self.log.exception('omci-setup-8021p-ani-port-setup', e=e)
+            raise
diff --git a/python/adapters/brcm_openomci_onu/omci/brcm_uni_lock_task.py b/python/adapters/brcm_openomci_onu/omci/brcm_uni_lock_task.py
index aecefc1..8e9a2e1 100644
--- a/python/adapters/brcm_openomci_onu/omci/brcm_uni_lock_task.py
+++ b/python/adapters/brcm_openomci_onu/omci/brcm_uni_lock_task.py
@@ -47,10 +47,10 @@
         :param priority: (int) OpenOMCI Task priority (0..255) 255 is the highest
         """
         super(BrcmUniLockTask, self).__init__(BrcmUniLockTask.name,
-                                                omci_agent,
-                                                device_id,
-                                                priority=priority,
-                                                exclusive=True)
+                                              omci_agent,
+                                              device_id,
+                                              priority=priority,
+                                              exclusive=True)
         self._device = omci_agent.get_device(device_id)
         self._lock = lock
         self._results = None
@@ -74,7 +74,6 @@
         super(BrcmUniLockTask, self).start()
         self._local_deferred = reactor.callLater(0, self.perform_lock)
 
-
     @inlineCallbacks
     def perform_lock(self):
         """
@@ -98,7 +97,7 @@
             for entity_id in veip_list:
                 veip_value = self._config.veip_entities[entity_id]
                 msg = VeipUniFrame(entity_id,
-                                           attributes=dict(administrative_state=state))
+                                   attributes=dict(administrative_state=state))
                 yield self._send_uni_lock_msg(entity_id, veip_value, msg)
 
             msg = OntGFrame(attributes={'administrative_state': state})
@@ -122,7 +121,6 @@
             self.log.exception('setting-uni-lock-state', e=e)
             self.deferred.errback(failure.Failure(e))
 
-
     @inlineCallbacks
     def _send_uni_lock_msg(self, entity_id, value, me_message):
         frame = me_message.set()