+static inline void _talloc_free_children(struct talloc_chunk *tc)
+{
+ void *ptr = TC_PTR_FROM_CHUNK(tc);
+
+ tc->flags |= TALLOC_FLAG_LOOP;
+
+ while (tc->child) {
+ void *child = TC_PTR_FROM_CHUNK(tc->child);
+ if (unlikely(_talloc_free(child) == -1)) {
+ const void *new_parent = no_owner_context;
+ struct talloc_chunk *p = talloc_parent_chunk(ptr);
+
+ /*
+ * we need to work out who will own an abandoned child
+ * if it cannot be freed. In priority order, the first
+ * choice is our parent, and the final choice is the
+ * no owner context.
+ */
+ if (p) {
+ new_parent = TC_PTR_FROM_CHUNK(p);
+ }
+
+ /*
+ * if talloc_free fails because of refs and
+ * not due to the destructor, it will already
+ * have a new owner no_owner_context
+ */
+ if (!talloc_parent_is_no_owner(child)) {
+ talloc_steal(new_parent, child);
+ }
+ }
+ }
+
+ tc->flags &= ~TALLOC_FLAG_LOOP;
+}