* simply assign the @new_node to that slot and be done.
         */
        if (!node) {
+               if (flags == BPF_EXIST) {
+                       ret = -ENOENT;
+                       goto out;
+               }
                rcu_assign_pointer(*slot, new_node);
                goto out;
        }
         * which already has the correct data array set.
         */
        if (node->prefixlen == matchlen) {
+               if (!(node->flags & LPM_TREE_NODE_FLAG_IM)) {
+                       if (flags == BPF_NOEXIST) {
+                               ret = -EEXIST;
+                               goto out;
+                       }
+                       trie->n_entries--;
+               } else if (flags == BPF_EXIST) {
+                       ret = -ENOENT;
+                       goto out;
+               }
+
                new_node->child[0] = node->child[0];
                new_node->child[1] = node->child[1];
 
-               if (!(node->flags & LPM_TREE_NODE_FLAG_IM))
-                       trie->n_entries--;
-
                rcu_assign_pointer(*slot, new_node);
                free_node = node;
 
                goto out;
        }
 
+       if (flags == BPF_EXIST) {
+               ret = -ENOENT;
+               goto out;
+       }
+
        /* If the new node matches the prefix completely, it must be inserted
         * as an ancestor. Simply insert it between @node and *@slot.
         */