# [Cake] Choosing a tin to work on

Kevin Darbyshire-Bryant kevin at darbyshire-bryant.me.uk
Wed Apr 12 05:15:29 EDT 2017

```
On 11/04/17 14:59, George Amanakis wrote:
> Hi Jonathan,
>
> I have some questions regarding the algorithm to choose a tin to dequeue
> from in sch_cake.c:
> -----------8<------------
>         int oi, best_tin=0;
>         s64 best_time = 0xFFFFFFFFFFFFUL;
>
>         for(oi=0; oi < q->tin_cnt; oi++) {
>             int tin = q->tin_order[oi];
>             b = q->tins + tin;
>             if((b->sparse_flow_count + b->bulk_flow_count) > 0) {
>                 s64 tdiff = b->tin_time_next_packet - now;
>                 if(tdiff <= 0 || tdiff <= best_time) {
>                     best_time = tdiff;
>                     best_tin = tin;
>                 }
>             }
>         }
> -----------8<------------
>
> 1) best_time is defined as a positive signed integer, this equals to 78
> hours if I did the calculations right. Why did you choose this? Did you
> mean to define it as "-1"?
> 2) If you meant to define it as "-1", the condition "tdiff <= best_time"
> would not matter. I can see no case where "tdiff > 0" and "tdiff <=
> best_time".
>
> Could you shed some light into this?
>
> Thank you,
> George

I'll try to answer this based on a vague bit of understanding...and then
Jonathan can shoot me down as well :-)

So the 'best_time' is signed because we can have a packet in a tin that
is not yet due to be sent (a positive result...ie. we have got here
early) and/or we can have a tin that is due now/overdue (a zero/negative
result, we've got here late)

The complication is that we can have multiple tins overdue, so we want
the highest priority *and* least overdue (least late) tin - this is the
reason for searching in tin_order[oi] and as a result tdiff can be <=0
and bigger than best_time.

best_time is initialised to the 'most early' time possible.

Kevin  (awaits to be shot at :-) )

```