+ p->V += (len<<MY_M) / p->sum ; /* update V */
+ q->S = q->F ; /* update start time */
+ if (q->len == 0) { /* Flow not backlogged any more */
+ fs->backlogged-- ;
+ heap_insert(&(p->idle_heap), q->F, q);
+ } else { /* still backlogged */
+ /*
+ * update F and position in backlogged queue, then
+ * put flow in not_eligible_heap (we will fix this later).
+ */
+ len = (q->head)->m_pkthdr.len;
+ q->F += (len<<MY_M)/(u_int64_t) fs->weight ;
+ if (DN_KEY_LEQ(q->S, p->V))
+ heap_insert(neh, q->S, q);
+ else
+ heap_insert(sch, q->F, q);
+ }
+ }
+ /*
+ * now compute V = max(V, min(S_i)). Remember that all elements in sch
+ * have by definition S_i <= V so if sch is not empty, V is surely
+ * the max and we must not update it. Conversely, if sch is empty
+ * we only need to look at neh.
+ */
+ if (sch->elements == 0 && neh->elements > 0)
+ p->V = MAX64 ( p->V, neh->p[0].key );
+ /* move from neh to sch any packets that have become eligible */
+ while (neh->elements > 0 && DN_KEY_LEQ(neh->p[0].key, p->V) ) {
+ struct dn_flow_queue *q = neh->p[0].object ;
+ heap_extract(neh, NULL);
+ heap_insert(sch, q->F, q);
+ }
+
+ if (p->if_name[0] != '\0') {/* tx clock is from a real thing */
+ p_numbytes = -1 ; /* mark not ready for I/O */
+ break ;
+ }
+ }
+ if (sch->elements == 0 && neh->elements == 0 && p_numbytes >= 0
+ && p->idle_heap.elements > 0) {
+ /*
+ * no traffic and no events scheduled. We can get rid of idle-heap.
+ */
+ int i ;
+
+ for (i = 0 ; i < p->idle_heap.elements ; i++) {
+ struct dn_flow_queue *q = p->idle_heap.p[i].object ;
+
+ q->F = 0 ;
+ q->S = q->F + 1 ;
+ }
+ p->sum = 0 ;
+ p->V = 0 ;
+ p->idle_heap.elements = 0 ;
+ }
+ /*
+ * If we are getting clocks from dummynet (not a real interface) and
+ * If we are under credit, schedule the next ready event.
+ * Also fix the delivery time of the last packet.
+ */
+ if (p->if_name[0]==0 && p_numbytes < 0) { /* this implies bandwidth >0 */
+ dn_key t=0 ; /* number of ticks i have to wait */
+
+ if (p->bandwidth > 0)
+ t = ( p->bandwidth -1 - p_numbytes) / p->bandwidth ;
+ dn_tag_get(p->tail)->output_time += t ;
+ p->sched_time = curr_time ;
+ heap_insert(&wfq_ready_heap, curr_time + t, (void *)p);
+ /* XXX should check errors on heap_insert, and drain the whole
+ * queue on error hoping next time we are luckier.
+ */
+ }
+
+ /* Fit (adjust if necessary) 64bit result into 32bit variable. */
+ if (p_numbytes > INT_MAX)
+ p->numbytes = INT_MAX;
+ else if (p_numbytes < INT_MIN)
+ p->numbytes = INT_MIN;
+ else
+ p->numbytes = p_numbytes;
+
+ /*
+ * If the delay line was empty call transmit_event(p) now.
+ * Otherwise, the scheduler will take care of it.
+ */
+ if (p_was_empty)
+ transmit_event(p, head, tail);
+
+}
+
+/*
+ * This is called every 1ms. It is used to
+ * increment the current tick counter and schedule expired events.
+ */
+static void
+dummynet(__unused void * unused)
+{
+ void *p ; /* generic parameter to handler */
+ struct dn_heap *h ;
+ struct dn_heap *heaps[3];
+ struct mbuf *head = NULL, *tail = NULL;
+ int i;
+ struct dn_pipe *pe ;
+ struct timespec ts;
+ struct timeval tv;
+
+ heaps[0] = &ready_heap ; /* fixed-rate queues */
+ heaps[1] = &wfq_ready_heap ; /* wfq queues */
+ heaps[2] = &extract_heap ; /* delay line */
+
+ lck_mtx_lock(dn_mutex);
+
+ /* make all time measurements in milliseconds (ms) -
+ * here we convert secs and usecs to msecs (just divide the
+ * usecs and take the closest whole number).
+ */
+ microuptime(&tv);
+ curr_time = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
+
+ for (i=0; i < 3 ; i++) {
+ h = heaps[i];
+ while (h->elements > 0 && DN_KEY_LEQ(h->p[0].key, curr_time) ) {
+ if (h->p[0].key > curr_time)
+ printf("dummynet: warning, heap %d is %d ticks late\n",
+ i, (int)(curr_time - h->p[0].key));
+ p = h->p[0].object ; /* store a copy before heap_extract */
+ heap_extract(h, NULL); /* need to extract before processing */
+ if (i == 0)
+ ready_event(p, &head, &tail) ;
+ else if (i == 1) {
+ struct dn_pipe *pipe = p;
+ if (pipe->if_name[0] != '\0')
+ printf("dummynet: bad ready_event_wfq for pipe %s\n",
+ pipe->if_name);
+ else
+ ready_event_wfq(p, &head, &tail) ;
+ } else {
+ transmit_event(p, &head, &tail);
+ }
+ }
+ }
+ /* sweep pipes trying to expire idle flow_queues */
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH(pe, &pipehash[i], next)
+ if (pe->idle_heap.elements > 0 &&
+ DN_KEY_LT(pe->idle_heap.p[0].key, pe->V) ) {
+ struct dn_flow_queue *q = pe->idle_heap.p[0].object ;
+
+ heap_extract(&(pe->idle_heap), NULL);
+ q->S = q->F + 1 ; /* mark timestamp as invalid */
+ pe->sum -= q->fs->weight ;
+ }
+
+ /* check the heaps to see if there's still stuff in there, and
+ * only set the timer if there are packets to process
+ */
+ timer_enabled = 0;
+ for (i=0; i < 3 ; i++) {
+ h = heaps[i];
+ if (h->elements > 0) { // set the timer
+ ts.tv_sec = 0;
+ ts.tv_nsec = 1 * 1000000; // 1ms
+ timer_enabled = 1;
+ bsd_timeout(dummynet, NULL, &ts);
+ break;
+ }
+ }
+
+ /*
+ * If a packet chain has been dequeued, set serialize=1 so that new
+ * packets don't get dispatched out of turn
+ */
+ if (head != NULL)
+ serialize = 1;
+
+ lck_mtx_unlock(dn_mutex);
+
+ /* Send out the de-queued list of ready-to-send packets */
+ if (head != NULL) {
+ dummynet_send(head);
+ lck_mtx_lock(dn_mutex);
+ serialize = 0;
+ lck_mtx_unlock(dn_mutex);
+ }
+}
+
+
+static void
+dummynet_send(struct mbuf *m)
+{
+ struct dn_pkt_tag *pkt;
+ struct mbuf *n;
+
+ for (; m != NULL; m = n) {
+ n = m->m_nextpkt;
+ m->m_nextpkt = NULL;
+ pkt = dn_tag_get(m);
+
+ switch (pkt->dn_dir) {
+ case DN_TO_IP_OUT: {
+ struct route tmp_rt = pkt->ro;
+ (void)ip_output(m, NULL, &tmp_rt, pkt->flags, NULL, NULL);
+ if (tmp_rt.ro_rt) {
+ rtfree(tmp_rt.ro_rt);
+ tmp_rt.ro_rt = NULL;
+ }
+ break ;
+ }
+ case DN_TO_IP_IN :
+ proto_inject(PF_INET, m);
+ break ;
+
+ default:
+ printf("dummynet: bad switch %d!\n", pkt->dn_dir);
+ m_freem(m);
+ break ;
+ }
+ }
+}
+
+
+
+/*
+ * called by an interface when tx_rdy occurs.
+ */
+int
+if_tx_rdy(struct ifnet *ifp)
+{
+ struct dn_pipe *p;
+ struct mbuf *head = NULL, *tail = NULL;
+ int i;
+
+ lck_mtx_lock(dn_mutex);
+
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH(p, &pipehash[i], next)
+ if (p->ifp == ifp)
+ break ;
+ if (p == NULL) {
+ char buf[32];
+ snprintf(buf, sizeof(buf), "%s%d",ifp->if_name, ifp->if_unit);
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH(p, &pipehash[i], next)
+ if (!strcmp(p->if_name, buf) ) {
+ p->ifp = ifp ;
+ DPRINTF(("dummynet: ++ tx rdy from %s (now found)\n", buf));
+ break ;
+ }
+ }
+ if (p != NULL) {
+ DPRINTF(("dummynet: ++ tx rdy from %s%d - qlen %d\n", ifp->if_name,
+ ifp->if_unit, ifp->if_snd.ifq_len));
+ p->numbytes = 0 ; /* mark ready for I/O */
+ ready_event_wfq(p, &head, &tail);
+ }
+ lck_mtx_unlock(dn_mutex);
+
+
+ /* Send out the de-queued list of ready-to-send packets */
+ if (head != NULL)
+ dummynet_send(head);
+
+ return 0;
+}
+
+/*
+ * Unconditionally expire empty queues in case of shortage.
+ * Returns the number of queues freed.
+ */
+static int
+expire_queues(struct dn_flow_set *fs)
+{
+ struct dn_flow_queue *q, *prev ;
+ int i, initial_elements = fs->rq_elements ;
+ struct timeval timenow;
+
+ getmicrotime(&timenow);
+
+ if (fs->last_expired == timenow.tv_sec)
+ return 0 ;
+ fs->last_expired = timenow.tv_sec ;
+ for (i = 0 ; i <= fs->rq_size ; i++) /* last one is overflow */
+ for (prev=NULL, q = fs->rq[i] ; q != NULL ; )
+ if (q->head != NULL || q->S != q->F+1) {
+ prev = q ;
+ q = q->next ;
+ } else { /* entry is idle, expire it */
+ struct dn_flow_queue *old_q = q ;
+
+ if (prev != NULL)
+ prev->next = q = q->next ;
+ else
+ fs->rq[i] = q = q->next ;
+ fs->rq_elements-- ;
+ FREE(old_q, M_DUMMYNET);
+ }
+ return initial_elements - fs->rq_elements ;
+}
+
+/*
+ * If room, create a new queue and put at head of slot i;
+ * otherwise, create or use the default queue.
+ */
+static struct dn_flow_queue *
+create_queue(struct dn_flow_set *fs, int i)
+{
+ struct dn_flow_queue *q ;
+
+ if (fs->rq_elements > fs->rq_size * dn_max_ratio &&
+ expire_queues(fs) == 0) {
+ /*
+ * No way to get room, use or create overflow queue.
+ */
+ i = fs->rq_size ;
+ if ( fs->rq[i] != NULL )
+ return fs->rq[i] ;
+ }
+ q = _MALLOC(sizeof(*q), M_DUMMYNET, M_DONTWAIT | M_ZERO);
+ if (q == NULL) {
+ printf("dummynet: sorry, cannot allocate queue for new flow\n");
+ return NULL ;
+ }
+ q->fs = fs ;
+ q->hash_slot = i ;
+ q->next = fs->rq[i] ;
+ q->S = q->F + 1; /* hack - mark timestamp as invalid */
+ fs->rq[i] = q ;
+ fs->rq_elements++ ;
+ return q ;
+}
+
+/*
+ * Given a flow_set and a pkt in last_pkt, find a matching queue
+ * after appropriate masking. The queue is moved to front
+ * so that further searches take less time.
+ */
+static struct dn_flow_queue *
+find_queue(struct dn_flow_set *fs, struct ipfw_flow_id *id)
+{
+ int i = 0 ; /* we need i and q for new allocations */
+ struct dn_flow_queue *q, *prev;
+
+ if ( !(fs->flags_fs & DN_HAVE_FLOW_MASK) )
+ q = fs->rq[0] ;
+ else {
+ /* first, do the masking */
+ id->dst_ip &= fs->flow_mask.dst_ip ;
+ id->src_ip &= fs->flow_mask.src_ip ;
+ id->dst_port &= fs->flow_mask.dst_port ;
+ id->src_port &= fs->flow_mask.src_port ;
+ id->proto &= fs->flow_mask.proto ;
+ id->flags = 0 ; /* we don't care about this one */
+ /* then, hash function */
+ i = ( (id->dst_ip) & 0xffff ) ^
+ ( (id->dst_ip >> 15) & 0xffff ) ^
+ ( (id->src_ip << 1) & 0xffff ) ^
+ ( (id->src_ip >> 16 ) & 0xffff ) ^
+ (id->dst_port << 1) ^ (id->src_port) ^
+ (id->proto );
+ i = i % fs->rq_size ;
+ /* finally, scan the current list for a match */
+ searches++ ;
+ for (prev=NULL, q = fs->rq[i] ; q ; ) {
+ search_steps++;
+ if (id->dst_ip == q->id.dst_ip &&
+ id->src_ip == q->id.src_ip &&
+ id->dst_port == q->id.dst_port &&
+ id->src_port == q->id.src_port &&
+ id->proto == q->id.proto &&
+ id->flags == q->id.flags)
+ break ; /* found */
+ else if (pipe_expire && q->head == NULL && q->S == q->F+1 ) {
+ /* entry is idle and not in any heap, expire it */
+ struct dn_flow_queue *old_q = q ;
+
+ if (prev != NULL)
+ prev->next = q = q->next ;
+ else
+ fs->rq[i] = q = q->next ;
+ fs->rq_elements-- ;
+ FREE(old_q, M_DUMMYNET);
+ continue ;
+ }
+ prev = q ;
+ q = q->next ;
+ }
+ if (q && prev != NULL) { /* found and not in front */
+ prev->next = q->next ;
+ q->next = fs->rq[i] ;
+ fs->rq[i] = q ;
+ }
+ }
+ if (q == NULL) { /* no match, need to allocate a new entry */
+ q = create_queue(fs, i);
+ if (q != NULL)
+ q->id = *id ;
+ }
+ return q ;
+}
+
+static int
+red_drops(struct dn_flow_set *fs, struct dn_flow_queue *q, int len)
+{
+ /*
+ * RED algorithm
+ *
+ * RED calculates the average queue size (avg) using a low-pass filter
+ * with an exponential weighted (w_q) moving average:
+ * avg <- (1-w_q) * avg + w_q * q_size
+ * where q_size is the queue length (measured in bytes or * packets).
+ *
+ * If q_size == 0, we compute the idle time for the link, and set
+ * avg = (1 - w_q)^(idle/s)
+ * where s is the time needed for transmitting a medium-sized packet.
+ *
+ * Now, if avg < min_th the packet is enqueued.
+ * If avg > max_th the packet is dropped. Otherwise, the packet is
+ * dropped with probability P function of avg.
+ *
+ */
+
+ int64_t p_b = 0;
+ /* queue in bytes or packets ? */
+ u_int q_size = (fs->flags_fs & DN_QSIZE_IS_BYTES) ? q->len_bytes : q->len;
+
+ DPRINTF(("\ndummynet: %d q: %2u ", (int) curr_time, q_size));
+
+ /* average queue size estimation */
+ if (q_size != 0) {
+ /*
+ * queue is not empty, avg <- avg + (q_size - avg) * w_q
+ */
+ int diff = SCALE(q_size) - q->avg;
+ int64_t v = SCALE_MUL((int64_t) diff, (int64_t) fs->w_q);
+
+ q->avg += (int) v;
+ } else {
+ /*
+ * queue is empty, find for how long the queue has been
+ * empty and use a lookup table for computing
+ * (1 - * w_q)^(idle_time/s) where s is the time to send a
+ * (small) packet.
+ * XXX check wraps...
+ */
+ if (q->avg) {
+ u_int t = (curr_time - q->q_time) / fs->lookup_step;
+
+ q->avg = (t < fs->lookup_depth) ?
+ SCALE_MUL(q->avg, fs->w_q_lookup[t]) : 0;
+ }
+ }
+ DPRINTF(("dummynet: avg: %u ", SCALE_VAL(q->avg)));
+
+ /* should i drop ? */
+
+ if (q->avg < fs->min_th) {
+ q->count = -1;
+ return 0; /* accept packet ; */
+ }
+ if (q->avg >= fs->max_th) { /* average queue >= max threshold */
+ if (fs->flags_fs & DN_IS_GENTLE_RED) {
+ /*
+ * According to Gentle-RED, if avg is greater than max_th the
+ * packet is dropped with a probability
+ * p_b = c_3 * avg - c_4
+ * where c_3 = (1 - max_p) / max_th, and c_4 = 1 - 2 * max_p
+ */
+ p_b = SCALE_MUL((int64_t) fs->c_3, (int64_t) q->avg) - fs->c_4;
+ } else {
+ q->count = -1;
+ DPRINTF(("dummynet: - drop"));
+ return 1 ;
+ }
+ } else if (q->avg > fs->min_th) {
+ /*
+ * we compute p_b using the linear dropping function p_b = c_1 *
+ * avg - c_2, where c_1 = max_p / (max_th - min_th), and c_2 =
+ * max_p * min_th / (max_th - min_th)
+ */
+ p_b = SCALE_MUL((int64_t) fs->c_1, (int64_t) q->avg) - fs->c_2;
+ }
+ if (fs->flags_fs & DN_QSIZE_IS_BYTES)
+ p_b = (p_b * len) / fs->max_pkt_size;
+ if (++q->count == 0)
+ q->random = MY_RANDOM & 0xffff;
+ else {
+ /*
+ * q->count counts packets arrived since last drop, so a greater
+ * value of q->count means a greater packet drop probability.
+ */
+ if (SCALE_MUL(p_b, SCALE((int64_t) q->count)) > q->random) {
+ q->count = 0;
+ DPRINTF(("dummynet: - red drop"));
+ /* after a drop we calculate a new random value */
+ q->random = MY_RANDOM & 0xffff;
+ return 1; /* drop */
+ }
+ }
+ /* end of RED algorithm */
+ return 0 ; /* accept */
+}
+
+static __inline
+struct dn_flow_set *
+locate_flowset(int fs_nr)
+{
+ struct dn_flow_set *fs;
+ SLIST_FOREACH(fs, &flowsethash[HASH(fs_nr)], next)
+ if (fs->fs_nr == fs_nr)
+ return fs ;
+
+ return (NULL);
+}
+
+static __inline struct dn_pipe *
+locate_pipe(int pipe_nr)
+{
+ struct dn_pipe *pipe;
+
+ SLIST_FOREACH(pipe, &pipehash[HASH(pipe_nr)], next)
+ if (pipe->pipe_nr == pipe_nr)
+ return (pipe);
+
+ return (NULL);
+}
+
+
+
+/*
+ * dummynet hook for packets. Below 'pipe' is a pipe or a queue
+ * depending on whether WF2Q or fixed bw is used.
+ *
+ * pipe_nr pipe or queue the packet is destined for.
+ * dir where shall we send the packet after dummynet.
+ * m the mbuf with the packet
+ * ifp the 'ifp' parameter from the caller.
+ * NULL in ip_input, destination interface in ip_output,
+ * real_dst in bdg_forward
+ * ro route parameter (only used in ip_output, NULL otherwise)
+ * dst destination address, only used by ip_output
+ * rule matching rule, in case of multiple passes
+ * flags flags from the caller, only used in ip_output
+ *
+ */
+static int
+dummynet_io(struct mbuf *m, int pipe_nr, int dir, struct ip_fw_args *fwa)
+{
+ struct mbuf *head = NULL, *tail = NULL;
+ struct dn_pkt_tag *pkt;
+ struct m_tag *mtag;
+ struct dn_flow_set *fs = NULL;
+ struct dn_pipe *pipe ;
+ u_int64_t len = m->m_pkthdr.len ;
+ struct dn_flow_queue *q = NULL ;
+ int is_pipe;
+ struct timespec ts;
+ struct timeval tv;
+
+#if IPFW2
+ ipfw_insn *cmd = fwa->rule->cmd + fwa->rule->act_ofs;
+
+ if (cmd->opcode == O_LOG)
+ cmd += F_LEN(cmd);
+ is_pipe = (cmd->opcode == O_PIPE);
+#else
+ is_pipe = (fwa->rule->fw_flg & IP_FW_F_COMMAND) == IP_FW_F_PIPE;
+#endif
+
+ pipe_nr &= 0xffff ;
+
+ lck_mtx_lock(dn_mutex);
+
+ /* make all time measurements in milliseconds (ms) -
+ * here we convert secs and usecs to msecs (just divide the
+ * usecs and take the closest whole number).
+ */
+ microuptime(&tv);
+ curr_time = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
+
+ /*
+ * This is a dummynet rule, so we expect an O_PIPE or O_QUEUE rule.
+ */
+ if (is_pipe) {
+ pipe = locate_pipe(pipe_nr);
+ if (pipe != NULL)
+ fs = &(pipe->fs);
+ } else
+ fs = locate_flowset(pipe_nr);
+
+
+ if (fs == NULL){
+ goto dropit ; /* this queue/pipe does not exist! */
+ }
+ pipe = fs->pipe ;
+ if (pipe == NULL) { /* must be a queue, try find a matching pipe */
+ pipe = locate_pipe(fs->parent_nr);
+
+ if (pipe != NULL)
+ fs->pipe = pipe ;
+ else {
+ printf("dummynet: no pipe %d for queue %d, drop pkt\n",
+ fs->parent_nr, fs->fs_nr);
+ goto dropit ;
+ }
+ }
+ q = find_queue(fs, &(fwa->f_id));
+ if ( q == NULL )
+ goto dropit ; /* cannot allocate queue */
+ /*
+ * update statistics, then check reasons to drop pkt
+ */
+ q->tot_bytes += len ;
+ q->tot_pkts++ ;
+ if ( fs->plr && (MY_RANDOM < fs->plr) )
+ goto dropit ; /* random pkt drop */
+ if ( fs->flags_fs & DN_QSIZE_IS_BYTES) {
+ if (q->len_bytes > fs->qsize)
+ goto dropit ; /* queue size overflow */
+ } else {
+ if (q->len >= fs->qsize)
+ goto dropit ; /* queue count overflow */
+ }
+ if ( fs->flags_fs & DN_IS_RED && red_drops(fs, q, len) )
+ goto dropit ;
+
+ /* XXX expensive to zero, see if we can remove it*/
+ mtag = m_tag_alloc(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET,
+ sizeof(struct dn_pkt_tag), M_NOWAIT);
+ if ( mtag == NULL )
+ goto dropit ; /* cannot allocate packet header */
+ m_tag_prepend(m, mtag); /* attach to mbuf chain */
+
+ pkt = (struct dn_pkt_tag *)(mtag+1);
+ bzero(pkt, sizeof(struct dn_pkt_tag));
+ /* ok, i can handle the pkt now... */
+ /* build and enqueue packet + parameters */
+ pkt->rule = fwa->rule ;
+ pkt->dn_dir = dir ;
+
+ pkt->ifp = fwa->oif;
+ if (dir == DN_TO_IP_OUT) {
+ /*
+ * We need to copy *ro because for ICMP pkts (and maybe others)
+ * the caller passed a pointer into the stack; dst might also be
+ * a pointer into *ro so it needs to be updated.
+ */
+ pkt->ro = *(fwa->ro);
+ if (fwa->ro->ro_rt)
+ RT_ADDREF(fwa->ro->ro_rt);
+
+ if (fwa->dst == (struct sockaddr_in *)&fwa->ro->ro_dst) /* dst points into ro */
+ fwa->dst = (struct sockaddr_in *)&(pkt->ro.ro_dst) ;
+
+ pkt->dn_dst = fwa->dst;
+ pkt->flags = fwa->flags;
+ if (fwa->ipoa != NULL)
+ pkt->ipoa = *(fwa->ipoa);
+ }
+ if (q->head == NULL)
+ q->head = m;
+ else
+ q->tail->m_nextpkt = m;
+ q->tail = m;
+ q->len++;
+ q->len_bytes += len ;
+
+ if ( q->head != m ) /* flow was not idle, we are done */
+ goto done;
+ /*
+ * If we reach this point the flow was previously idle, so we need
+ * to schedule it. This involves different actions for fixed-rate or
+ * WF2Q queues.
+ */
+ if (is_pipe) {
+ /*
+ * Fixed-rate queue: just insert into the ready_heap.
+ */
+ dn_key t = 0 ;
+ if (pipe->bandwidth)
+ t = SET_TICKS(m, q, pipe);
+ q->sched_time = curr_time ;
+ if (t == 0) /* must process it now */
+ ready_event( q , &head, &tail );
+ else
+ heap_insert(&ready_heap, curr_time + t , q );
+ } else {
+ /*
+ * WF2Q. First, compute start time S: if the flow was idle (S=F+1)
+ * set S to the virtual time V for the controlling pipe, and update
+ * the sum of weights for the pipe; otherwise, remove flow from
+ * idle_heap and set S to max(F,V).
+ * Second, compute finish time F = S + len/weight.
+ * Third, if pipe was idle, update V=max(S, V).
+ * Fourth, count one more backlogged flow.
+ */
+ if (DN_KEY_GT(q->S, q->F)) { /* means timestamps are invalid */
+ q->S = pipe->V ;
+ pipe->sum += fs->weight ; /* add weight of new queue */
+ } else {
+ heap_extract(&(pipe->idle_heap), q);
+ q->S = MAX64(q->F, pipe->V ) ;
+ }
+ q->F = q->S + ( len<<MY_M )/(u_int64_t) fs->weight;
+
+ if (pipe->not_eligible_heap.elements == 0 &&
+ pipe->scheduler_heap.elements == 0)
+ pipe->V = MAX64 ( q->S, pipe->V );
+ fs->backlogged++ ;
+ /*
+ * Look at eligibility. A flow is not eligibile if S>V (when
+ * this happens, it means that there is some other flow already
+ * scheduled for the same pipe, so the scheduler_heap cannot be
+ * empty). If the flow is not eligible we just store it in the
+ * not_eligible_heap. Otherwise, we store in the scheduler_heap
+ * and possibly invoke ready_event_wfq() right now if there is
+ * leftover credit.
+ * Note that for all flows in scheduler_heap (SCH), S_i <= V,
+ * and for all flows in not_eligible_heap (NEH), S_i > V .
+ * So when we need to compute max( V, min(S_i) ) forall i in SCH+NEH,
+ * we only need to look into NEH.
+ */
+ if (DN_KEY_GT(q->S, pipe->V) ) { /* not eligible */
+ if (pipe->scheduler_heap.elements == 0)
+ printf("dummynet: ++ ouch! not eligible but empty scheduler!\n");
+ heap_insert(&(pipe->not_eligible_heap), q->S, q);
+ } else {
+ heap_insert(&(pipe->scheduler_heap), q->F, q);
+ if (pipe->numbytes >= 0) { /* pipe is idle */
+ if (pipe->scheduler_heap.elements != 1)
+ printf("dummynet: OUCH! pipe should have been idle!\n");
+ DPRINTF(("dummynet: waking up pipe %d at %d\n",
+ pipe->pipe_nr, (int)(q->F >> MY_M)));
+ pipe->sched_time = curr_time ;
+ ready_event_wfq(pipe, &head, &tail);
+ }
+ }
+ }
+done:
+ /* start the timer and set global if not already set */
+ if (!timer_enabled) {
+ ts.tv_sec = 0;
+ ts.tv_nsec = 1 * 1000000; // 1ms
+ timer_enabled = 1;
+ bsd_timeout(dummynet, NULL, &ts);
+ }
+
+ lck_mtx_unlock(dn_mutex);
+ if (head != NULL)
+ dummynet_send(head);
+
+ return 0;
+
+dropit:
+ if (q)
+ q->drops++ ;
+ lck_mtx_unlock(dn_mutex);
+ m_freem(m);
+ return ( (fs && (fs->flags_fs & DN_NOERROR)) ? 0 : ENOBUFS);
+}
+
+/*
+ * Below, the rtfree is only needed when (pkt->dn_dir == DN_TO_IP_OUT)
+ * Doing this would probably save us the initial bzero of dn_pkt
+ */
+#define DN_FREE_PKT(_m) do { \
+ struct m_tag *tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_DUMMYNET, NULL); \
+ if (tag) { \
+ struct dn_pkt_tag *n = (struct dn_pkt_tag *)(tag+1); \
+ if (n->ro.ro_rt != NULL) { \
+ rtfree(n->ro.ro_rt); \
+ n->ro.ro_rt = NULL; \
+ } \
+ } \
+ m_tag_delete(_m, tag); \
+ m_freem(_m); \
+} while (0)
+
+/*
+ * Dispose all packets and flow_queues on a flow_set.
+ * If all=1, also remove red lookup table and other storage,
+ * including the descriptor itself.
+ * For the one in dn_pipe MUST also cleanup ready_heap...
+ */
+static void
+purge_flow_set(struct dn_flow_set *fs, int all)
+{
+ struct dn_flow_queue *q, *qn ;
+ int i ;
+
+ lck_mtx_assert(dn_mutex, LCK_MTX_ASSERT_OWNED);
+
+ for (i = 0 ; i <= fs->rq_size ; i++ ) {
+ for (q = fs->rq[i] ; q ; q = qn ) {
+ struct mbuf *m, *mnext;
+
+ mnext = q->head;
+ while ((m = mnext) != NULL) {
+ mnext = m->m_nextpkt;
+ DN_FREE_PKT(m);
+ }
+ qn = q->next ;
+ FREE(q, M_DUMMYNET);
+ }
+ fs->rq[i] = NULL ;
+ }
+ fs->rq_elements = 0 ;
+ if (all) {
+ /* RED - free lookup table */
+ if (fs->w_q_lookup)
+ FREE(fs->w_q_lookup, M_DUMMYNET);
+ if (fs->rq)
+ FREE(fs->rq, M_DUMMYNET);
+ /* if this fs is not part of a pipe, free it */
+ if (fs->pipe && fs != &(fs->pipe->fs) )
+ FREE(fs, M_DUMMYNET);
+ }
+}
+
+/*
+ * Dispose all packets queued on a pipe (not a flow_set).
+ * Also free all resources associated to a pipe, which is about
+ * to be deleted.
+ */
+static void
+purge_pipe(struct dn_pipe *pipe)
+{
+ struct mbuf *m, *mnext;
+
+ purge_flow_set( &(pipe->fs), 1 );
+
+ mnext = pipe->head;
+ while ((m = mnext) != NULL) {
+ mnext = m->m_nextpkt;
+ DN_FREE_PKT(m);
+ }
+
+ heap_free( &(pipe->scheduler_heap) );
+ heap_free( &(pipe->not_eligible_heap) );
+ heap_free( &(pipe->idle_heap) );
+}
+
+/*
+ * Delete all pipes and heaps returning memory. Must also
+ * remove references from all ipfw rules to all pipes.
+ */
+static void
+dummynet_flush(void)
+{
+ struct dn_pipe *pipe, *pipe1;
+ struct dn_flow_set *fs, *fs1;
+ int i;
+
+ lck_mtx_lock(dn_mutex);
+
+ /* remove all references to pipes ...*/
+ flush_pipe_ptrs(NULL);
+
+ /* Free heaps so we don't have unwanted events. */
+ heap_free(&ready_heap);
+ heap_free(&wfq_ready_heap);
+ heap_free(&extract_heap);
+
+ /*
+ * Now purge all queued pkts and delete all pipes.
+ *
+ * XXXGL: can we merge the for(;;) cycles into one or not?
+ */
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH_SAFE(fs, &flowsethash[i], next, fs1) {
+ SLIST_REMOVE(&flowsethash[i], fs, dn_flow_set, next);
+ purge_flow_set(fs, 1);
+ }
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH_SAFE(pipe, &pipehash[i], next, pipe1) {
+ SLIST_REMOVE(&pipehash[i], pipe, dn_pipe, next);
+ purge_pipe(pipe);
+ FREE(pipe, M_DUMMYNET);
+ }
+ lck_mtx_unlock(dn_mutex);
+}
+
+
+extern struct ip_fw *ip_fw_default_rule ;
+static void
+dn_rule_delete_fs(struct dn_flow_set *fs, void *r)
+{
+ int i ;
+ struct dn_flow_queue *q ;
+ struct mbuf *m ;
+
+ for (i = 0 ; i <= fs->rq_size ; i++) /* last one is ovflow */
+ for (q = fs->rq[i] ; q ; q = q->next )
+ for (m = q->head ; m ; m = m->m_nextpkt ) {
+ struct dn_pkt_tag *pkt = dn_tag_get(m) ;
+ if (pkt->rule == r)
+ pkt->rule = ip_fw_default_rule ;
+ }
+}
+/*
+ * when a firewall rule is deleted, scan all queues and remove the flow-id
+ * from packets matching this rule.
+ */
+void
+dn_rule_delete(void *r)
+{
+ struct dn_pipe *p ;
+ struct dn_flow_set *fs ;
+ struct dn_pkt_tag *pkt ;
+ struct mbuf *m ;
+ int i;
+
+ lck_mtx_lock(dn_mutex);
+
+ /*
+ * If the rule references a queue (dn_flow_set), then scan
+ * the flow set, otherwise scan pipes. Should do either, but doing
+ * both does not harm.
+ */
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH(fs, &flowsethash[i], next)
+ dn_rule_delete_fs(fs, r);
+
+ for (i = 0; i < HASHSIZE; i++)
+ SLIST_FOREACH(p, &pipehash[i], next) {
+ fs = &(p->fs);
+ dn_rule_delete_fs(fs, r);
+ for (m = p->head ; m ; m = m->m_nextpkt ) {
+ pkt = dn_tag_get(m);
+ if (pkt->rule == r)
+ pkt->rule = ip_fw_default_rule;
+ }
+ }
+ lck_mtx_unlock(dn_mutex);
+}
+
+/*
+ * setup RED parameters
+ */
+static int
+config_red(struct dn_flow_set *p, struct dn_flow_set * x)
+{
+ int i;
+
+ x->w_q = p->w_q;
+ x->min_th = SCALE(p->min_th);
+ x->max_th = SCALE(p->max_th);
+ x->max_p = p->max_p;
+
+ x->c_1 = p->max_p / (p->max_th - p->min_th);
+ x->c_2 = SCALE_MUL(x->c_1, SCALE(p->min_th));
+ if (x->flags_fs & DN_IS_GENTLE_RED) {
+ x->c_3 = (SCALE(1) - p->max_p) / p->max_th;
+ x->c_4 = (SCALE(1) - 2 * p->max_p);
+ }
+
+ /* if the lookup table already exist, free and create it again */
+ if (x->w_q_lookup) {
+ FREE(x->w_q_lookup, M_DUMMYNET);
+ x->w_q_lookup = NULL ;
+ }
+ if (red_lookup_depth == 0) {
+ printf("\ndummynet: net.inet.ip.dummynet.red_lookup_depth must be > 0\n");
+ FREE(x, M_DUMMYNET);
+ return EINVAL;
+ }
+ x->lookup_depth = red_lookup_depth;
+ x->w_q_lookup = (u_int *) _MALLOC(x->lookup_depth * sizeof(int),
+ M_DUMMYNET, M_DONTWAIT);
+ if (x->w_q_lookup == NULL) {
+ printf("dummynet: sorry, cannot allocate red lookup table\n");
+ FREE(x, M_DUMMYNET);
+ return ENOSPC;
+ }
+
+ /* fill the lookup table with (1 - w_q)^x */
+ x->lookup_step = p->lookup_step ;
+ x->lookup_weight = p->lookup_weight ;
+ x->w_q_lookup[0] = SCALE(1) - x->w_q;
+ for (i = 1; i < x->lookup_depth; i++)
+ x->w_q_lookup[i] = SCALE_MUL(x->w_q_lookup[i - 1], x->lookup_weight);
+ if (red_avg_pkt_size < 1)
+ red_avg_pkt_size = 512 ;
+ x->avg_pkt_size = red_avg_pkt_size ;
+ if (red_max_pkt_size < 1)
+ red_max_pkt_size = 1500 ;
+ x->max_pkt_size = red_max_pkt_size ;
+ return 0 ;
+}
+
+static int
+alloc_hash(struct dn_flow_set *x, struct dn_flow_set *pfs)
+{
+ if (x->flags_fs & DN_HAVE_FLOW_MASK) { /* allocate some slots */
+ int l = pfs->rq_size;
+
+ if (l == 0)
+ l = dn_hash_size;
+ if (l < 4)
+ l = 4;
+ else if (l > DN_MAX_HASH_SIZE)
+ l = DN_MAX_HASH_SIZE;
+ x->rq_size = l;
+ } else /* one is enough for null mask */
+ x->rq_size = 1;
+ x->rq = _MALLOC((1 + x->rq_size) * sizeof(struct dn_flow_queue *),
+ M_DUMMYNET, M_DONTWAIT | M_ZERO);
+ if (x->rq == NULL) {
+ printf("dummynet: sorry, cannot allocate queue\n");
+ return ENOSPC;
+ }
+ x->rq_elements = 0;
+ return 0 ;
+}
+
+static void
+set_fs_parms(struct dn_flow_set *x, struct dn_flow_set *src)