+static struct bridge_vlan_port *
+bridge_find_vlan_member_port(struct bridge_member *bm, struct bridge_vlan *vlan)
+{
+ const char *ifname = bm->dev.dev->ifname;
+ int i;
+
+ for (i = 0; i < vlan->n_ports; i++) {
+ if (strcmp(vlan->ports[i].ifname, ifname) != 0)
+ continue;
+
+ return &vlan->ports[i];
+ }
+
+ return NULL;
+}
+
+static bool
+bridge_member_vlan_is_pvid(struct bridge_member *bm, struct bridge_vlan_port *port)
+{
+ return (!bm->pvid && (port->flags & BRVLAN_F_UNTAGGED)) ||
+ (port->flags & BRVLAN_F_PVID);
+}
+
+static void
+__bridge_set_member_vlan(struct bridge_member *bm, struct bridge_vlan *vlan,
+ struct bridge_vlan_port *port, bool add)
+{
+ uint16_t flags;
+
+ flags = port->flags;
+ if (bm->pvid == vlan->vid)
+ flags |= BRVLAN_F_PVID;
+
+ system_bridge_vlan(port->ifname, vlan->vid, add, flags);
+}
+
+static void
+bridge_set_member_vlan(struct bridge_member *bm, struct bridge_vlan *vlan, bool add)
+{
+ struct bridge_vlan_port *port;
+
+ if (!bm->present)
+ return;
+
+ port = bridge_find_vlan_member_port(bm, vlan);
+ if (!port)
+ return;
+
+ if (bridge_member_vlan_is_pvid(bm, port))
+ bm->pvid = vlan->vid;
+
+ __bridge_set_member_vlan(bm, vlan, port, add);
+}
+
+static void
+brigde_set_local_vlan(struct bridge_state *bst, struct bridge_vlan *vlan, bool add)
+{
+ if (!vlan->local && add)
+ return;
+
+ system_bridge_vlan(bst->dev.ifname, vlan->vid, add, BRVLAN_F_SELF);
+}
+
+static void
+bridge_set_local_vlans(struct bridge_state *bst, bool add)
+{
+ struct bridge_vlan *vlan;
+
+ vlist_for_each_element(&bst->dev.vlans, vlan, node)
+ brigde_set_local_vlan(bst, vlan, add);
+}
+
+static struct bridge_vlan *
+bridge_recalc_member_pvid(struct bridge_member *bm)
+{
+ struct bridge_state *bst = bm->bst;
+ struct bridge_vlan_port *port;
+ struct bridge_vlan *vlan, *ret = NULL;
+
+ vlist_for_each_element(&bst->dev.vlans, vlan, node) {
+ port = bridge_find_vlan_member_port(bm, vlan);
+ if (!port)
+ continue;
+
+ if (!bridge_member_vlan_is_pvid(bm, port))
+ continue;
+
+ ret = vlan;
+ if (port->flags & BRVLAN_F_PVID)
+ break;
+ }
+
+ return ret;
+}
+
+static void
+bridge_set_vlan_state(struct bridge_state *bst, struct bridge_vlan *vlan, bool add)
+{
+ struct bridge_member *bm;
+ struct bridge_vlan *vlan2;
+
+ brigde_set_local_vlan(bst, vlan, add);
+
+ vlist_for_each_element(&bst->members, bm, node) {
+ struct bridge_vlan_port *port;
+ int new_pvid = -1;
+
+ port = bridge_find_vlan_member_port(bm, vlan);
+ if (!port)
+ continue;
+
+ if (add) {
+ if (bridge_member_vlan_is_pvid(bm, port))
+ bm->pvid = vlan->vid;
+ } else if (bm->pvid == vlan->vid) {
+ vlan2 = bridge_recalc_member_pvid(bm);
+ if (vlan2 && vlan2->vid != vlan->vid) {
+ bridge_set_member_vlan(bm, vlan2, false);
+ bridge_set_member_vlan(bm, vlan2, true);
+ }
+ new_pvid = vlan2 ? vlan2->vid : 0;
+ }
+
+ if (!bm->present)
+ continue;
+
+ __bridge_set_member_vlan(bm, vlan, port, add);
+ if (new_pvid >= 0)
+ bm->pvid = new_pvid;
+ }
+}
+