AP_DECLARE(apr_status_t) ap_filter_setaside_brigade(ap_filter_t *f,
        apr_bucket_brigade *bb)
{
    int loglevel = ap_get_conn_module_loglevel(f->c, APLOG_MODULE_INDEX);

    if (loglevel >= APLOG_TRACE6) {
        ap_log_cerror(
            APLOG_MARK, APLOG_TRACE6, 0, f->c,
            "setaside %s brigade to %s brigade in '%s' output filter",
            (APR_BRIGADE_EMPTY(bb) ? "empty" : "full"),
            (!f->bb || APR_BRIGADE_EMPTY(f->bb) ? "empty" : "full"), f->frec->name);
    }

    if (!APR_BRIGADE_EMPTY(bb)) {
        /*
         * Set aside the brigade bb within f->bb.
         */
        ap_filter_prepare_brigade(f, NULL);

        /* decide what pool we setaside to, request pool or deferred pool? */
        if (f->r) {
            apr_bucket *e;
            for (e = APR_BRIGADE_FIRST(bb); e != APR_BRIGADE_SENTINEL(bb); e =
                    APR_BUCKET_NEXT(e)) {
                if (APR_BUCKET_IS_TRANSIENT(e)) {
                    int rv = apr_bucket_setaside(e, f->r->pool);
                    if (rv != APR_SUCCESS) {
                        return rv;
                    }
                }
            }
            APR_BRIGADE_CONCAT(f->bb, bb);
        }
        else {
            if (!f->deferred_pool) {
                apr_pool_create(&f->deferred_pool, f->c->pool);
                apr_pool_tag(f->deferred_pool, "deferred_pool");
            }
            return ap_save_brigade(f, &f->bb, &bb, f->deferred_pool);
        }

    }
    else if (f->deferred_pool) {
        /*
         * There are no more requests in the pipeline. We can just clear the
         * pool.
         */
        apr_brigade_cleanup(f->bb);
        apr_pool_clear(f->deferred_pool);
    }
    return APR_SUCCESS;
}