inc_counter:
        bfqq->weight_counter->num_active++;
+       bfqq->ref++;
 }
 
 /*
 
 reset_entity_pointer:
        bfqq->weight_counter = NULL;
+       bfq_put_queue(bfqq);
 }
 
 /*
 {
        struct bfq_entity *entity = bfqq->entity.parent;
 
-       __bfq_weights_tree_remove(bfqd, bfqq,
-                                 &bfqd->queue_weights_tree);
-
        for_each_entity(entity) {
                struct bfq_sched_data *sd = entity->my_sched_data;
 
                        bfqd->num_groups_with_pending_reqs--;
                }
        }
+
+       /*
+        * Next function is invoked last, because it causes bfqq to be
+        * freed if the following holds: bfqq is not in service and
+        * has no dispatched request. DO NOT use bfqq after the next
+        * function invocation.
+        */
+       __bfq_weights_tree_remove(bfqd, bfqq,
+                                 &bfqd->queue_weights_tree);
 }
 
 /*
 
 static int bfqq_process_refs(struct bfq_queue *bfqq)
 {
-       return bfqq->ref - bfqq->allocated - bfqq->entity.on_st;
+       return bfqq->ref - bfqq->allocated - bfqq->entity.on_st -
+               (bfqq->weight_counter != NULL);
 }
 
 /* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */
 
 
        bfqd->busy_queues[bfqq->ioprio_class - 1]--;
 
-       if (!bfqq->dispatched)
-               bfq_weights_tree_remove(bfqd, bfqq);
-
        if (bfqq->wr_coeff > 1)
                bfqd->wr_busy_queues--;
 
        bfqg_stats_update_dequeue(bfqq_group(bfqq));
 
        bfq_deactivate_bfqq(bfqd, bfqq, true, expiration);
+
+       if (!bfqq->dispatched)
+               bfq_weights_tree_remove(bfqd, bfqq);
 }
 
 /*