]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_ratelimit.c
Improve the handling of receiving unordered and unreliable user
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_ratelimit.c
1 /*-
2  *
3  * SPDX-License-Identifier: BSD-3-Clause
4  *
5  * Copyright (c) 2018-2020
6  *      Netflix Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  */
30 /**
31  * Author: Randall Stewart <rrs@netflix.com>
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include <sys/param.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/socket.h>
46 #include <sys/socketvar.h>
47 #include <sys/sysctl.h>
48 #include <sys/eventhandler.h>
49 #include <sys/mutex.h>
50 #include <sys/ck.h>
51 #include <net/if.h>
52 #include <net/if_var.h>
53 #include <netinet/in.h>
54 #include <netinet/in_pcb.h>
55 #define TCPSTATES               /* for logging */
56 #include <netinet/tcp_var.h>
57 #ifdef INET6
58 #include <netinet6/tcp6_var.h>
59 #endif
60 #include <netinet/tcp_ratelimit.h>
61 #ifndef USECS_IN_SECOND
62 #define USECS_IN_SECOND 1000000
63 #endif
64 /*
65  * For the purposes of each send, what is the size
66  * of an ethernet frame.
67  */
68 MALLOC_DEFINE(M_TCPPACE, "tcp_hwpace", "TCP Hardware pacing memory");
69 #ifdef RATELIMIT
70
71 /*
72  * The following preferred table will seem weird to
73  * the casual viewer. Why do we not have any rates below
74  * 1Mbps? Why do we have a rate at 1.44Mbps called common?
75  * Why do the rates cluster in the 1-100Mbps range more
76  * than others? Why does the table jump around at the beginnign
77  * and then be more consistently raising?
78  *
79  * Let me try to answer those questions. A lot of
80  * this is dependant on the hardware. We have three basic
81  * supporters of rate limiting
82  *
83  * Chelsio - Supporting 16 configurable rates.
84  * Mlx  - c4 supporting 13 fixed rates.
85  * Mlx  - c5 & c6 supporting 127 configurable rates.
86  *
87  * The c4 is why we have a common rate that is available
88  * in all rate tables. This is a selected rate from the
89  * c4 table and we assure its available in all ratelimit
90  * tables. This way the tcp_ratelimit code has an assured
91  * rate it should always be able to get. This answers a
92  * couple of the questions above.
93  *
94  * So what about the rest, well the table is built to
95  * try to get the most out of a joint hardware/software
96  * pacing system.  The software pacer will always pick
97  * a rate higher than the b/w that it is estimating
98  *
99  * on the path. This is done for two reasons.
100  * a) So we can discover more b/w
101  * and
102  * b) So we can send a block of MSS's down and then
103  *    have the software timer go off after the previous
104  *    send is completely out of the hardware.
105  *
106  * But when we do <b> we don't want to have the delay
107  * between the last packet sent by the hardware be
108  * excessively long (to reach our desired rate).
109  *
110  * So let me give an example for clarity.
111  *
112  * Lets assume that the tcp stack sees that 29,110,000 bps is
113  * what the bw of the path is. The stack would select the
114  * rate 31Mbps. 31Mbps means that each send that is done
115  * by the hardware will cause a 390 micro-second gap between
116  * the packets sent at that rate. For 29,110,000 bps we
117  * would need 416 micro-seconds gap between each send.
118  *
119  * Note that are calculating a complete time for pacing
120  * which includes the ethernet, IP and TCP overhead. So
121  * a full 1514 bytes is used for the above calculations.
122  * My testing has shown that both cards are also using this
123  * as their basis i.e. full payload size of the ethernet frame.
124  * The TCP stack caller needs to be aware of this and make the
125  * appropriate overhead calculations be included in its choices.
126  *
127  * Now, continuing our example, we pick a MSS size based on the
128  * delta between the two rates (416 - 390) divided into the rate
129  * we really wish to send at rounded up.  That results in a MSS
130  * send of 17 mss's at once. The hardware then will
131  * run out of data in a single 17MSS send in 6,630 micro-seconds.
132  *
133  * On the other hand the software pacer will send more data
134  * in 7,072 micro-seconds. This means that we will refill
135  * the hardware 52 microseconds after it would have sent
136  * next if it had not ran out of data. This is a win since we are
137  * only sending every 7ms or so and yet all the packets are spaced on
138  * the wire with 94% of what they should be and only
139  * the last packet is delayed extra to make up for the
140  * difference.
141  *
142  * Note that the above formula has two important caveat.
143  * If we are above (b/w wise) over 100Mbps we double the result
144  * of the MSS calculation. The second caveat is if we are 500Mbps
145  * or more we just send the maximum MSS at once i.e. 45MSS. At
146  * the higher b/w's even the cards have limits to what times (timer granularity)
147  * they can insert between packets and start to send more than one
148  * packet at a time on the wire.
149  *
150  */
151 #define COMMON_RATE 180500
152 const uint64_t desired_rates[] = {
153         122500,                 /* 1Mbps  - rate 1 */
154         180500,                 /* 1.44Mpbs - rate 2  common rate */
155         375000,                 /* 3Mbps    - rate 3 */
156         625000,                 /* 5Mbps    - rate 4 */
157         875000,                 /* 7Mbps    - rate 5 */
158         1125000,                /* 9Mbps    - rate 6 */
159         1375000,                /* 11Mbps   - rate 7 */
160         1625000,                /* 13Mbps   - rate 8 */
161         2625000,                /* 21Mbps   - rate 9 */
162         3875000,                /* 31Mbps   - rate 10 */
163         5125000,                /* 41Meg    - rate 11 */
164         12500000,               /* 100Mbps  - rate 12 */
165         25000000,               /* 200Mbps  - rate 13 */
166         50000000,               /* 400Mbps  - rate 14 */
167         63750000,               /* 51Mbps   - rate 15 */
168         100000000,              /* 800Mbps  - rate 16 */
169         1875000,                /* 15Mbps   - rate 17 */
170         2125000,                /* 17Mbps   - rate 18 */
171         2375000,                /* 19Mbps   - rate 19 */
172         2875000,                /* 23Mbps   - rate 20 */
173         3125000,                /* 25Mbps   - rate 21 */
174         3375000,                /* 27Mbps   - rate 22 */
175         3625000,                /* 29Mbps   - rate 23 */
176         4125000,                /* 33Mbps   - rate 24 */
177         4375000,                /* 35Mbps   - rate 25 */
178         4625000,                /* 37Mbps   - rate 26 */
179         4875000,                /* 39Mbps   - rate 27 */
180         5375000,                /* 43Mbps   - rate 28 */
181         5625000,                /* 45Mbps   - rate 29 */
182         5875000,                /* 47Mbps   - rate 30 */
183         6125000,                /* 49Mbps   - rate 31 */
184         6625000,                /* 53Mbps   - rate 32 */
185         6875000,                /* 55Mbps   - rate 33 */
186         7125000,                /* 57Mbps   - rate 34 */
187         7375000,                /* 59Mbps   - rate 35 */
188         7625000,                /* 61Mbps   - rate 36 */
189         7875000,                /* 63Mbps   - rate 37 */
190         8125000,                /* 65Mbps   - rate 38 */
191         8375000,                /* 67Mbps   - rate 39 */
192         8625000,                /* 69Mbps   - rate 40 */
193         8875000,                /* 71Mbps   - rate 41 */
194         9125000,                /* 73Mbps   - rate 42 */
195         9375000,                /* 75Mbps   - rate 43 */
196         9625000,                /* 77Mbps   - rate 44 */
197         9875000,                /* 79Mbps   - rate 45 */
198         10125000,               /* 81Mbps   - rate 46 */
199         10375000,               /* 83Mbps   - rate 47 */
200         10625000,               /* 85Mbps   - rate 48 */
201         10875000,               /* 87Mbps   - rate 49 */
202         11125000,               /* 89Mbps   - rate 50 */
203         11375000,               /* 91Mbps   - rate 51 */
204         11625000,               /* 93Mbps   - rate 52 */
205         11875000,               /* 95Mbps   - rate 53 */
206         13125000,               /* 105Mbps  - rate 54 */
207         13750000,               /* 110Mbps  - rate 55 */
208         14375000,               /* 115Mbps  - rate 56 */
209         15000000,               /* 120Mbps  - rate 57 */
210         15625000,               /* 125Mbps  - rate 58 */
211         16250000,               /* 130Mbps  - rate 59 */
212         16875000,               /* 135Mbps  - rate 60 */
213         17500000,               /* 140Mbps  - rate 61 */
214         18125000,               /* 145Mbps  - rate 62 */
215         18750000,               /* 150Mbps  - rate 64 */
216         20000000,               /* 160Mbps  - rate 65 */
217         21250000,               /* 170Mbps  - rate 66 */
218         22500000,               /* 180Mbps  - rate 67 */
219         23750000,               /* 190Mbps  - rate 68 */
220         26250000,               /* 210Mbps  - rate 69 */
221         27500000,               /* 220Mbps  - rate 70 */
222         28750000,               /* 230Mbps  - rate 71 */
223         30000000,               /* 240Mbps  - rate 72 */
224         31250000,               /* 250Mbps  - rate 73 */
225         34375000,               /* 275Mbps  - rate 74 */
226         37500000,               /* 300Mbps  - rate 75 */
227         40625000,               /* 325Mbps  - rate 76 */
228         43750000,               /* 350Mbps  - rate 77 */
229         46875000,               /* 375Mbps  - rate 78 */
230         53125000,               /* 425Mbps  - rate 79 */
231         56250000,               /* 450Mbps  - rate 80 */
232         59375000,               /* 475Mbps  - rate 81 */
233         62500000,               /* 500Mbps  - rate 82 */
234         68750000,               /* 550Mbps  - rate 83 */
235         75000000,               /* 600Mbps  - rate 84 */
236         81250000,               /* 650Mbps  - rate 85 */
237         87500000,               /* 700Mbps  - rate 86 */
238         93750000,               /* 750Mbps  - rate 87 */
239         106250000,              /* 850Mbps  - rate 88 */
240         112500000,              /* 900Mbps  - rate 89 */
241         125000000,              /* 1Gbps    - rate 90 */
242         156250000,              /* 1.25Gps  - rate 91 */
243         187500000,              /* 1.5Gps   - rate 92 */
244         218750000,              /* 1.75Gps  - rate 93 */
245         250000000,              /* 2Gbps    - rate 94 */
246         281250000,              /* 2.25Gps  - rate 95 */
247         312500000,              /* 2.5Gbps  - rate 96 */
248         343750000,              /* 2.75Gbps - rate 97 */
249         375000000,              /* 3Gbps    - rate 98 */
250         500000000,              /* 4Gbps    - rate 99 */
251         625000000,              /* 5Gbps    - rate 100 */
252         750000000,              /* 6Gbps    - rate 101 */
253         875000000,              /* 7Gbps    - rate 102 */
254         1000000000,             /* 8Gbps    - rate 103 */
255         1125000000,             /* 9Gbps    - rate 104 */
256         1250000000,             /* 10Gbps   - rate 105 */
257         1875000000,             /* 15Gbps   - rate 106 */
258         2500000000              /* 20Gbps   - rate 107 */
259 };
260
261 #define MAX_HDWR_RATES (sizeof(desired_rates)/sizeof(uint64_t))
262 #define RS_ORDERED_COUNT 16     /*
263                                  * Number that are in order
264                                  * at the beginning of the table,
265                                  * over this a sort is required.
266                                  */
267 #define RS_NEXT_ORDER_GROUP 16  /*
268                                  * The point in our table where
269                                  * we come fill in a second ordered
270                                  * group (index wise means -1).
271                                  */
272 #define ALL_HARDWARE_RATES 1004 /*
273                                  * 1Meg - 1Gig in 1 Meg steps
274                                  * plus 100, 200k  and 500k and
275                                  * 10Gig
276                                  */
277
278 #define RS_ONE_MEGABIT_PERSEC 1000000
279 #define RS_ONE_GIGABIT_PERSEC 1000000000
280 #define RS_TEN_GIGABIT_PERSEC 10000000000
281
282 static struct head_tcp_rate_set int_rs;
283 static struct mtx rs_mtx;
284 uint32_t rs_number_alive;
285 uint32_t rs_number_dead;
286
287 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, rl, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
288     "TCP Ratelimit stats");
289 SYSCTL_UINT(_net_inet_tcp_rl, OID_AUTO, alive, CTLFLAG_RW,
290     &rs_number_alive, 0,
291     "Number of interfaces initialized for ratelimiting");
292 SYSCTL_UINT(_net_inet_tcp_rl, OID_AUTO, dead, CTLFLAG_RW,
293     &rs_number_dead, 0,
294     "Number of interfaces departing from ratelimiting");
295
296 static void
297 rl_add_syctl_entries(struct sysctl_oid *rl_sysctl_root, struct tcp_rate_set *rs)
298 {
299         /*
300          * Add sysctl entries for thus interface.
301          */
302         if (rs->rs_flags & RS_INTF_NO_SUP) {
303                 SYSCTL_ADD_S32(&rs->sysctl_ctx,
304                    SYSCTL_CHILDREN(rl_sysctl_root),
305                    OID_AUTO, "disable", CTLFLAG_RD,
306                    &rs->rs_disable, 0,
307                    "Disable this interface from new hdwr limiting?");
308         } else {
309                 SYSCTL_ADD_S32(&rs->sysctl_ctx,
310                    SYSCTL_CHILDREN(rl_sysctl_root),
311                    OID_AUTO, "disable", CTLFLAG_RW,
312                    &rs->rs_disable, 0,
313                    "Disable this interface from new hdwr limiting?");
314         }
315         SYSCTL_ADD_S32(&rs->sysctl_ctx,
316             SYSCTL_CHILDREN(rl_sysctl_root),
317             OID_AUTO, "minseg", CTLFLAG_RW,
318             &rs->rs_min_seg, 0,
319             "What is the minimum we need to send on this interface?");
320         SYSCTL_ADD_U64(&rs->sysctl_ctx,
321             SYSCTL_CHILDREN(rl_sysctl_root),
322             OID_AUTO, "flow_limit", CTLFLAG_RW,
323             &rs->rs_flow_limit, 0,
324             "What is the limit for number of flows (0=unlimited)?");
325         SYSCTL_ADD_S32(&rs->sysctl_ctx,
326             SYSCTL_CHILDREN(rl_sysctl_root),
327             OID_AUTO, "highest", CTLFLAG_RD,
328             &rs->rs_highest_valid, 0,
329             "Highest valid rate");
330         SYSCTL_ADD_S32(&rs->sysctl_ctx,
331             SYSCTL_CHILDREN(rl_sysctl_root),
332             OID_AUTO, "lowest", CTLFLAG_RD,
333             &rs->rs_lowest_valid, 0,
334             "Lowest valid rate");
335         SYSCTL_ADD_S32(&rs->sysctl_ctx,
336             SYSCTL_CHILDREN(rl_sysctl_root),
337             OID_AUTO, "flags", CTLFLAG_RD,
338             &rs->rs_flags, 0,
339             "What lags are on the entry?");
340         SYSCTL_ADD_S32(&rs->sysctl_ctx,
341             SYSCTL_CHILDREN(rl_sysctl_root),
342             OID_AUTO, "numrates", CTLFLAG_RD,
343             &rs->rs_rate_cnt, 0,
344             "How many rates re there?");
345         SYSCTL_ADD_U64(&rs->sysctl_ctx,
346             SYSCTL_CHILDREN(rl_sysctl_root),
347             OID_AUTO, "flows_using", CTLFLAG_RD,
348             &rs->rs_flows_using, 0,
349             "How many flows are using this interface now?");
350 #ifdef DETAILED_RATELIMIT_SYSCTL
351         if (rs->rs_rlt && rs->rs_rate_cnt > 0) {
352                 /*  Lets display the rates */
353                 int i;
354                 struct sysctl_oid *rl_rates;
355                 struct sysctl_oid *rl_rate_num;
356                 char rate_num[16];
357                 rl_rates = SYSCTL_ADD_NODE(&rs->sysctl_ctx,
358                                             SYSCTL_CHILDREN(rl_sysctl_root),
359                                             OID_AUTO,
360                                             "rate",
361                                             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
362                                             "Ratelist");
363                 for( i = 0; i < rs->rs_rate_cnt; i++) {
364                         sprintf(rate_num, "%d", i);
365                         rl_rate_num = SYSCTL_ADD_NODE(&rs->sysctl_ctx,
366                                             SYSCTL_CHILDREN(rl_rates),
367                                             OID_AUTO,
368                                             rate_num,
369                                             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
370                                             "Individual Rate");
371                         SYSCTL_ADD_U32(&rs->sysctl_ctx,
372                                        SYSCTL_CHILDREN(rl_rate_num),
373                                        OID_AUTO, "flags", CTLFLAG_RD,
374                                        &rs->rs_rlt[i].flags, 0,
375                                        "Flags on this rate");
376                         SYSCTL_ADD_U32(&rs->sysctl_ctx,
377                                        SYSCTL_CHILDREN(rl_rate_num),
378                                        OID_AUTO, "pacetime", CTLFLAG_RD,
379                                        &rs->rs_rlt[i].time_between, 0,
380                                        "Time hardware inserts between 1500 byte sends");
381                         SYSCTL_ADD_U64(&rs->sysctl_ctx,
382                                        SYSCTL_CHILDREN(rl_rate_num),
383                                        OID_AUTO, "rate", CTLFLAG_RD,
384                                        &rs->rs_rlt[i].rate, 0,
385                                        "Rate in bytes per second");
386                 }
387         }
388 #endif
389 }
390
391 static void
392 rs_destroy(epoch_context_t ctx)
393 {
394         struct tcp_rate_set *rs;
395         bool do_free_rs;
396
397         rs = __containerof(ctx, struct tcp_rate_set, rs_epoch_ctx);
398
399         mtx_lock(&rs_mtx);
400         rs->rs_flags &= ~RS_FUNERAL_SCHD;
401         /*
402          * In theory its possible (but unlikely)
403          * that while the delete was occuring
404          * and we were applying the DEAD flag
405          * someone slipped in and found the
406          * interface in a lookup. While we
407          * decided rs_flows_using were 0 and
408          * scheduling the epoch_call, the other
409          * thread incremented rs_flow_using. This
410          * is because users have a pointer and
411          * we only use the rs_flows_using in an
412          * atomic fashion, i.e. the other entities
413          * are not protected. To assure this did
414          * not occur, we check rs_flows_using here
415          * before deleting.
416          */
417         do_free_rs = (rs->rs_flows_using == 0);
418         rs_number_dead--;
419         mtx_unlock(&rs_mtx);
420
421         if (do_free_rs) {
422                 sysctl_ctx_free(&rs->sysctl_ctx);
423                 free(rs->rs_rlt, M_TCPPACE);
424                 free(rs, M_TCPPACE);
425         }
426 }
427
428 static void
429 rs_defer_destroy(struct tcp_rate_set *rs)
430 {
431
432         mtx_assert(&rs_mtx, MA_OWNED);
433
434         /* Check if already pending. */
435         if (rs->rs_flags & RS_FUNERAL_SCHD)
436                 return;
437
438         rs_number_dead++;
439
440         /* Set flag to only defer once. */
441         rs->rs_flags |= RS_FUNERAL_SCHD;
442         NET_EPOCH_CALL(rs_destroy, &rs->rs_epoch_ctx);
443 }
444
445 #ifdef INET
446 extern counter_u64_t rate_limit_set_ok;
447 extern counter_u64_t rate_limit_active;
448 extern counter_u64_t rate_limit_alloc_fail;
449 #endif
450
451 static int
452 rl_attach_txrtlmt(struct ifnet *ifp,
453     uint32_t flowtype,
454     int flowid,
455     uint64_t cfg_rate,
456     struct m_snd_tag **tag)
457 {
458         int error;
459         union if_snd_tag_alloc_params params = {
460                 .rate_limit.hdr.type = IF_SND_TAG_TYPE_RATE_LIMIT,
461                 .rate_limit.hdr.flowid = flowid,
462                 .rate_limit.hdr.flowtype = flowtype,
463                 .rate_limit.max_rate = cfg_rate,
464                 .rate_limit.flags = M_NOWAIT,
465         };
466
467         if (ifp->if_snd_tag_alloc == NULL) {
468                 error = EOPNOTSUPP;
469         } else {
470                 error = ifp->if_snd_tag_alloc(ifp, &params, tag);
471 #ifdef INET
472                 if (error == 0) {
473                         if_ref((*tag)->ifp);
474                         counter_u64_add(rate_limit_set_ok, 1);
475                         counter_u64_add(rate_limit_active, 1);
476                 } else
477                         counter_u64_add(rate_limit_alloc_fail, 1);
478 #endif
479         }
480         return (error);
481 }
482
483 static void
484 populate_canned_table(struct tcp_rate_set *rs, const uint64_t *rate_table_act)
485 {
486         /*
487          * The internal table is "special", it
488          * is two seperate ordered tables that
489          * must be merged. We get here when the
490          * adapter specifies a number of rates that
491          * covers both ranges in the table in some
492          * form.
493          */
494         int i, at_low, at_high;
495         uint8_t low_disabled = 0, high_disabled = 0;
496
497         for(i = 0, at_low = 0, at_high = RS_NEXT_ORDER_GROUP; i < rs->rs_rate_cnt; i++) {
498                 rs->rs_rlt[i].flags = 0;
499                 rs->rs_rlt[i].time_between = 0;
500                 if ((low_disabled == 0) &&
501                     (high_disabled ||
502                      (rate_table_act[at_low] < rate_table_act[at_high]))) {
503                         rs->rs_rlt[i].rate = rate_table_act[at_low];
504                         at_low++;
505                         if (at_low == RS_NEXT_ORDER_GROUP)
506                                 low_disabled = 1;
507                 } else if (high_disabled == 0) {
508                         rs->rs_rlt[i].rate = rate_table_act[at_high];
509                         at_high++;
510                         if (at_high == MAX_HDWR_RATES)
511                                 high_disabled = 1;
512                 }
513         }
514 }
515
516 static struct tcp_rate_set *
517 rt_setup_new_rs(struct ifnet *ifp, int *error)
518 {
519         struct tcp_rate_set *rs;
520         const uint64_t *rate_table_act;
521         uint64_t lentim, res;
522         size_t sz;
523         uint32_t hash_type;
524         int i;
525         struct if_ratelimit_query_results rl;
526         struct sysctl_oid *rl_sysctl_root;
527         /*
528          * We expect to enter with the
529          * mutex locked.
530          */
531
532         if (ifp->if_ratelimit_query == NULL) {
533                 /*
534                  * We can do nothing if we cannot
535                  * get a query back from the driver.
536                  */
537                 printf("Warning:No query functions for %s:%d-- failed\n",
538                        ifp->if_dname, ifp->if_dunit);
539                 return (NULL);
540         }
541         rs = malloc(sizeof(struct tcp_rate_set), M_TCPPACE, M_NOWAIT | M_ZERO);
542         if (rs == NULL) {
543                 if (error)
544                         *error = ENOMEM;
545                 printf("Warning:No memory for malloc of tcp_rate_set\n");
546                 return (NULL);
547         }
548         memset(&rl, 0, sizeof(rl));
549         rl.flags = RT_NOSUPPORT;
550         ifp->if_ratelimit_query(ifp, &rl);
551         if (rl.flags & RT_IS_UNUSABLE) {
552                 /*
553                  * The interface does not really support
554                  * the rate-limiting.
555                  */
556                 memset(rs, 0, sizeof(struct tcp_rate_set));
557                 rs->rs_ifp = ifp;
558                 rs->rs_if_dunit = ifp->if_dunit;
559                 rs->rs_flags = RS_INTF_NO_SUP;
560                 rs->rs_disable = 1;
561                 rs_number_alive++;
562                 sysctl_ctx_init(&rs->sysctl_ctx);
563                 rl_sysctl_root = SYSCTL_ADD_NODE(&rs->sysctl_ctx,
564                     SYSCTL_STATIC_CHILDREN(_net_inet_tcp_rl),
565                     OID_AUTO,
566                     rs->rs_ifp->if_xname,
567                     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
568                     "");
569                 rl_add_syctl_entries(rl_sysctl_root, rs);
570                 mtx_lock(&rs_mtx);
571                 CK_LIST_INSERT_HEAD(&int_rs, rs, next);
572                 mtx_unlock(&rs_mtx);
573                 return (rs);
574         } else if ((rl.flags & RT_IS_INDIRECT) == RT_IS_INDIRECT) {
575                 memset(rs, 0, sizeof(struct tcp_rate_set));
576                 rs->rs_ifp = ifp;
577                 rs->rs_if_dunit = ifp->if_dunit;
578                 rs->rs_flags = RS_IS_DEFF;
579                 rs_number_alive++;
580                 sysctl_ctx_init(&rs->sysctl_ctx);
581                 rl_sysctl_root = SYSCTL_ADD_NODE(&rs->sysctl_ctx,
582                     SYSCTL_STATIC_CHILDREN(_net_inet_tcp_rl),
583                     OID_AUTO,
584                     rs->rs_ifp->if_xname,
585                     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
586                     "");
587                 rl_add_syctl_entries(rl_sysctl_root, rs);
588                 mtx_lock(&rs_mtx);
589                 CK_LIST_INSERT_HEAD(&int_rs, rs, next);
590                 mtx_unlock(&rs_mtx);
591                 return (rs);
592         } else if ((rl.flags & RT_IS_FIXED_TABLE) == RT_IS_FIXED_TABLE) {
593                 /* Mellanox C4 likely */
594                 rs->rs_ifp = ifp;
595                 rs->rs_if_dunit = ifp->if_dunit;
596                 rs->rs_rate_cnt = rl.number_of_rates;
597                 rs->rs_min_seg = rl.min_segment_burst;
598                 rs->rs_highest_valid = 0;
599                 rs->rs_flow_limit = rl.max_flows;
600                 rs->rs_flags = RS_IS_INTF | RS_NO_PRE;
601                 rs->rs_disable = 0;
602                 rate_table_act = rl.rate_table;
603         } else if ((rl.flags & RT_IS_SELECTABLE) == RT_IS_SELECTABLE) {
604                 /* Chelsio, C5 and C6 of Mellanox? */
605                 rs->rs_ifp = ifp;
606                 rs->rs_if_dunit = ifp->if_dunit;
607                 rs->rs_rate_cnt = rl.number_of_rates;
608                 rs->rs_min_seg = rl.min_segment_burst;
609                 rs->rs_disable = 0;
610                 rs->rs_flow_limit = rl.max_flows;
611                 rate_table_act = desired_rates;
612                 if ((rs->rs_rate_cnt > MAX_HDWR_RATES) &&
613                     (rs->rs_rate_cnt < ALL_HARDWARE_RATES)) {
614                         /*
615                          * Our desired table is not big
616                          * enough, do what we can.
617                          */
618                         rs->rs_rate_cnt = MAX_HDWR_RATES;
619                  }
620                 if (rs->rs_rate_cnt <= RS_ORDERED_COUNT)
621                         rs->rs_flags = RS_IS_INTF;
622                 else
623                         rs->rs_flags = RS_IS_INTF | RS_INT_TBL;
624                 if (rs->rs_rate_cnt >= ALL_HARDWARE_RATES)
625                         rs->rs_rate_cnt = ALL_HARDWARE_RATES;
626         } else {
627                 free(rs, M_TCPPACE);
628                 return (NULL);
629         }
630         sz = sizeof(struct tcp_hwrate_limit_table) * rs->rs_rate_cnt;
631         rs->rs_rlt = malloc(sz, M_TCPPACE, M_NOWAIT);
632         if (rs->rs_rlt == NULL) {
633                 if (error)
634                         *error = ENOMEM;
635 bail:
636                 free(rs, M_TCPPACE);
637                 return (NULL);
638         }
639         if (rs->rs_rate_cnt >= ALL_HARDWARE_RATES) {
640                 /*
641                  * The interface supports all
642                  * the rates we could possibly want.
643                  */
644                 uint64_t rat;
645
646                 rs->rs_rlt[0].rate = 12500;     /* 100k */
647                 rs->rs_rlt[1].rate = 25000;     /* 200k */
648                 rs->rs_rlt[2].rate = 62500;     /* 500k */
649                 /* Note 125000 == 1Megabit
650                  * populate 1Meg - 1000meg.
651                  */
652                 for(i = 3, rat = 125000; i< (ALL_HARDWARE_RATES-1); i++) {
653                         rs->rs_rlt[i].rate = rat;
654                         rat += 125000;
655                 }
656                 rs->rs_rlt[(ALL_HARDWARE_RATES-1)].rate = 1250000000;
657         } else if (rs->rs_flags & RS_INT_TBL) {
658                 /* We populate this in a special way */
659                 populate_canned_table(rs, rate_table_act);
660         } else {
661                 /*
662                  * Just copy in the rates from
663                  * the table, it is in order.
664                  */
665                 for (i=0; i<rs->rs_rate_cnt; i++) {
666                         rs->rs_rlt[i].rate = rate_table_act[i];
667                         rs->rs_rlt[i].time_between = 0;
668                         rs->rs_rlt[i].flags = 0;
669                 }
670         }
671         for (i = (rs->rs_rate_cnt - 1); i >= 0; i--) {
672                 /*
673                  * We go backwards through the list so that if we can't get
674                  * a rate and fail to init one, we have at least a chance of
675                  * getting the highest one.
676                  */
677                 rs->rs_rlt[i].ptbl = rs;
678                 rs->rs_rlt[i].tag = NULL;
679                 /*
680                  * Calculate the time between.
681                  */
682                 lentim = ETHERNET_SEGMENT_SIZE * USECS_IN_SECOND;
683                 res = lentim / rs->rs_rlt[i].rate;
684                 if (res > 0)
685                         rs->rs_rlt[i].time_between = res;
686                 else
687                         rs->rs_rlt[i].time_between = 1;
688                 if (rs->rs_flags & RS_NO_PRE) {
689                         rs->rs_rlt[i].flags = HDWRPACE_INITED;
690                         rs->rs_lowest_valid = i;
691                 } else {
692                         int err;
693
694                         if ((rl.flags & RT_IS_SETUP_REQ)  &&
695                             (ifp->if_ratelimit_query)) {
696                                 err = ifp->if_ratelimit_setup(ifp,
697                                          rs->rs_rlt[i].rate, i);
698                                 if (err)
699                                         goto handle_err;
700                         }
701 #ifdef RSS
702                         hash_type = M_HASHTYPE_RSS_TCP_IPV4;
703 #else
704                         hash_type = M_HASHTYPE_OPAQUE_HASH;
705 #endif
706                         err = rl_attach_txrtlmt(ifp,
707                             hash_type,
708                             (i + 1),
709                             rs->rs_rlt[i].rate,
710                             &rs->rs_rlt[i].tag);
711                         if (err) {
712 handle_err:
713                                 if (i == (rs->rs_rate_cnt - 1)) {
714                                         /*
715                                          * Huh - first rate and we can't get
716                                          * it?
717                                          */
718                                         free(rs->rs_rlt, M_TCPPACE);
719                                         if (error)
720                                                 *error = err;
721                                         goto bail;
722                                 } else {
723                                         if (error)
724                                                 *error = err;
725                                 }
726                                 break;
727                         } else {
728                                 rs->rs_rlt[i].flags = HDWRPACE_INITED | HDWRPACE_TAGPRESENT;
729                                 rs->rs_lowest_valid = i;
730                         }
731                 }
732         }
733         /* Did we get at least 1 rate? */
734         if (rs->rs_rlt[(rs->rs_rate_cnt - 1)].flags & HDWRPACE_INITED)
735                 rs->rs_highest_valid = rs->rs_rate_cnt - 1;
736         else {
737                 free(rs->rs_rlt, M_TCPPACE);
738                 goto bail;
739         }
740         rs_number_alive++;
741         sysctl_ctx_init(&rs->sysctl_ctx);
742         rl_sysctl_root = SYSCTL_ADD_NODE(&rs->sysctl_ctx,
743             SYSCTL_STATIC_CHILDREN(_net_inet_tcp_rl),
744             OID_AUTO,
745             rs->rs_ifp->if_xname,
746             CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
747             "");
748         rl_add_syctl_entries(rl_sysctl_root, rs);
749         mtx_lock(&rs_mtx);
750         CK_LIST_INSERT_HEAD(&int_rs, rs, next);
751         mtx_unlock(&rs_mtx);
752         return (rs);
753 }
754
755 static const struct tcp_hwrate_limit_table *
756 tcp_int_find_suitable_rate(const struct tcp_rate_set *rs,
757     uint64_t bytes_per_sec, uint32_t flags)
758 {
759         struct tcp_hwrate_limit_table *arte = NULL, *rte = NULL;
760         uint64_t mbits_per_sec, ind_calc;
761         int i;
762
763         mbits_per_sec = (bytes_per_sec * 8);
764         if (flags & RS_PACING_LT) {
765                 if ((mbits_per_sec < RS_ONE_MEGABIT_PERSEC) &&
766                     (rs->rs_lowest_valid <= 2)){
767                         /*
768                          * Smaller than 1Meg, only
769                          * 3 entries can match it.
770                          */
771                         for(i = rs->rs_lowest_valid; i < 3; i++) {
772                                 if (bytes_per_sec <= rs->rs_rlt[i].rate) {
773                                         rte = &rs->rs_rlt[i];
774                                         break;
775                                 } else if (rs->rs_rlt[i].flags & HDWRPACE_INITED) {
776                                         arte = &rs->rs_rlt[i];
777                                 }
778                         }
779                         goto done;
780                 } else if ((mbits_per_sec > RS_ONE_GIGABIT_PERSEC) &&
781                            (rs->rs_rlt[(ALL_HARDWARE_RATES-1)].flags & HDWRPACE_INITED)){
782                         /*
783                          * Larger than 1G (the majority of
784                          * our table.
785                          */
786                         if (mbits_per_sec < RS_TEN_GIGABIT_PERSEC)
787                                 rte = &rs->rs_rlt[(ALL_HARDWARE_RATES-1)];
788                         else
789                                 arte = &rs->rs_rlt[(ALL_HARDWARE_RATES-1)];
790                         goto done;
791                 }
792                 /*
793                  * If we reach here its in our table (between 1Meg - 1000Meg),
794                  * just take the rounded down mbits per second, and add
795                  * 1Megabit to it, from this we can calculate
796                  * the index in the table.
797                  */
798                 ind_calc = mbits_per_sec/RS_ONE_MEGABIT_PERSEC;
799                 if ((ind_calc * RS_ONE_MEGABIT_PERSEC) != mbits_per_sec)
800                         ind_calc++;
801                 /* our table is offset by 3, we add 2 */
802                 ind_calc += 2;
803                 if (ind_calc > (ALL_HARDWARE_RATES-1)) {
804                         /* This should not happen */
805                         ind_calc = ALL_HARDWARE_RATES-1;
806                 }
807                 if ((ind_calc >= rs->rs_lowest_valid) &&
808                     (ind_calc <= rs->rs_highest_valid))
809                 rte = &rs->rs_rlt[ind_calc];
810         } else if (flags & RS_PACING_EXACT_MATCH) {
811                 if ((mbits_per_sec < RS_ONE_MEGABIT_PERSEC) &&
812                     (rs->rs_lowest_valid <= 2)){
813                         for(i = rs->rs_lowest_valid; i < 3; i++) {
814                                 if (bytes_per_sec == rs->rs_rlt[i].rate) {
815                                         rte = &rs->rs_rlt[i];
816                                         break;
817                                 }
818                         }
819                 } else if ((mbits_per_sec > RS_ONE_GIGABIT_PERSEC) &&
820                            (rs->rs_rlt[(ALL_HARDWARE_RATES-1)].flags & HDWRPACE_INITED)) {
821                         /* > 1Gbps only one rate */
822                         if (bytes_per_sec == rs->rs_rlt[(ALL_HARDWARE_RATES-1)].rate) {
823                                 /* Its 10G wow */
824                                 rte = &rs->rs_rlt[(ALL_HARDWARE_RATES-1)];
825                         }
826                 } else {
827                         /* Ok it must be a exact meg (its between 1G and 1Meg) */
828                         ind_calc = mbits_per_sec/RS_ONE_MEGABIT_PERSEC;
829                         if ((ind_calc * RS_ONE_MEGABIT_PERSEC) == mbits_per_sec) {
830                                 /* its an exact Mbps */
831                                 ind_calc += 2;
832                                 if (ind_calc > (ALL_HARDWARE_RATES-1)) {
833                                         /* This should not happen */
834                                         ind_calc = ALL_HARDWARE_RATES-1;
835                                 }
836                                 if (rs->rs_rlt[ind_calc].flags & HDWRPACE_INITED)
837                                         rte = &rs->rs_rlt[ind_calc];
838                         }
839                 }
840         } else {
841                 /* we want greater than the requested rate */
842                 if ((mbits_per_sec < RS_ONE_MEGABIT_PERSEC) &&
843                     (rs->rs_lowest_valid <= 2)){
844                         arte = &rs->rs_rlt[3]; /* set alternate to 1Meg */
845                         for (i=2; i>=rs->rs_lowest_valid; i--) {
846                                 if (bytes_per_sec < rs->rs_rlt[i].rate) {
847                                         rte = &rs->rs_rlt[i];
848                                         break;
849                                 } else if ((flags & RS_PACING_GEQ) &&
850                                            (bytes_per_sec == rs->rs_rlt[i].rate)) {
851                                         rte = &rs->rs_rlt[i];
852                                         break;
853                                 } else {
854                                         arte = &rs->rs_rlt[i]; /* new alternate */
855                                 }
856                         }
857                 } else if (mbits_per_sec > RS_ONE_GIGABIT_PERSEC) {
858                         if ((bytes_per_sec < rs->rs_rlt[(ALL_HARDWARE_RATES-1)].rate) &&
859                             (rs->rs_rlt[(ALL_HARDWARE_RATES-1)].flags & HDWRPACE_INITED)){
860                                 /* Our top rate is larger than the request */
861                                 rte = &rs->rs_rlt[(ALL_HARDWARE_RATES-1)];
862                         } else if ((flags & RS_PACING_GEQ) &&
863                                    (bytes_per_sec == rs->rs_rlt[(ALL_HARDWARE_RATES-1)].rate) &&
864                                    (rs->rs_rlt[(ALL_HARDWARE_RATES-1)].flags & HDWRPACE_INITED)) {
865                                 /* It matches our top rate */
866                                 rte = &rs->rs_rlt[(ALL_HARDWARE_RATES-1)];
867                         } else if (rs->rs_rlt[(ALL_HARDWARE_RATES-1)].flags & HDWRPACE_INITED) {
868                                 /* The top rate is an alternative */
869                                 arte = &rs->rs_rlt[(ALL_HARDWARE_RATES-1)];
870                         }
871                 } else {
872                         /* Its in our range 1Meg - 1Gig */
873                         if (flags & RS_PACING_GEQ) {
874                                 ind_calc = mbits_per_sec/RS_ONE_MEGABIT_PERSEC;
875                                 if ((ind_calc * RS_ONE_MEGABIT_PERSEC) == mbits_per_sec) {
876                                         if (ind_calc > (ALL_HARDWARE_RATES-1)) {
877                                                 /* This should not happen */
878                                                 ind_calc = (ALL_HARDWARE_RATES-1);
879                                         }
880                                         rte = &rs->rs_rlt[ind_calc];
881                                 }
882                                 goto done;
883                         }
884                         ind_calc = (mbits_per_sec + (RS_ONE_MEGABIT_PERSEC-1))/RS_ONE_MEGABIT_PERSEC;
885                         ind_calc += 2;
886                         if (ind_calc > (ALL_HARDWARE_RATES-1)) {
887                                 /* This should not happen */
888                                 ind_calc = ALL_HARDWARE_RATES-1;
889                         }
890                         if (rs->rs_rlt[ind_calc].flags & HDWRPACE_INITED)
891                                 rte = &rs->rs_rlt[ind_calc];
892                 }
893         }
894 done:
895         if ((rte == NULL) &&
896             (arte != NULL) &&
897             (flags & RS_PACING_SUB_OK)) {
898                 /* We can use the substitute */
899                 rte = arte;
900         }
901         return (rte);
902 }
903
904 static const struct tcp_hwrate_limit_table *
905 tcp_find_suitable_rate(const struct tcp_rate_set *rs, uint64_t bytes_per_sec, uint32_t flags)
906 {
907         /**
908          * Hunt the rate table with the restrictions in flags and find a
909          * suitable rate if possible.
910          * RS_PACING_EXACT_MATCH - look for an exact match to rate.
911          * RS_PACING_GT     - must be greater than.
912          * RS_PACING_GEQ    - must be greater than or equal.
913          * RS_PACING_LT     - must be less than.
914          * RS_PACING_SUB_OK - If we don't meet criteria a
915          *                    substitute is ok.
916          */
917         int i, matched;
918         struct tcp_hwrate_limit_table *rte = NULL;
919
920         if ((rs->rs_flags & RS_INT_TBL) &&
921             (rs->rs_rate_cnt >= ALL_HARDWARE_RATES)) {
922                 /*
923                  * Here we don't want to paw thru
924                  * a big table, we have everything
925                  * from 1Meg - 1000Meg in 1Meg increments.
926                  * Use an alternate method to "lookup".
927                  */
928                 return (tcp_int_find_suitable_rate(rs, bytes_per_sec, flags));
929         }
930         if ((flags & RS_PACING_LT) ||
931             (flags & RS_PACING_EXACT_MATCH)) {
932                 /*
933                  * For exact and less than we go forward through the table.
934                  * This way when we find one larger we stop (exact was a
935                  * toss up).
936                  */
937                 for (i = rs->rs_lowest_valid, matched = 0; i <= rs->rs_highest_valid; i++) {
938                         if ((flags & RS_PACING_EXACT_MATCH) &&
939                             (bytes_per_sec == rs->rs_rlt[i].rate)) {
940                                 rte = &rs->rs_rlt[i];
941                                 matched = 1;
942                                 break;
943                         } else if ((flags & RS_PACING_LT) &&
944                             (bytes_per_sec <= rs->rs_rlt[i].rate)) {
945                                 rte = &rs->rs_rlt[i];
946                                 matched = 1;
947                                 break;
948                         }
949                         if (bytes_per_sec > rs->rs_rlt[i].rate)
950                                 break;
951                 }
952                 if ((matched == 0) &&
953                     (flags & RS_PACING_LT) &&
954                     (flags & RS_PACING_SUB_OK)) {
955                         /* Kick in a substitute (the lowest) */
956                         rte = &rs->rs_rlt[rs->rs_lowest_valid];
957                 }
958         } else {
959                 /*
960                  * Here we go backward through the table so that we can find
961                  * the one greater in theory faster (but its probably a
962                  * wash).
963                  */
964                 for (i = rs->rs_highest_valid, matched = 0; i >= rs->rs_lowest_valid; i--) {
965                         if (rs->rs_rlt[i].rate > bytes_per_sec) {
966                                 /* A possible candidate */
967                                 rte = &rs->rs_rlt[i];
968                         }
969                         if ((flags & RS_PACING_GEQ) &&
970                             (bytes_per_sec == rs->rs_rlt[i].rate)) {
971                                 /* An exact match and we want equal */
972                                 matched = 1;
973                                 rte = &rs->rs_rlt[i];
974                                 break;
975                         } else if (rte) {
976                                 /*
977                                  * Found one that is larger than but don't
978                                  * stop, there may be a more closer match.
979                                  */
980                                 matched = 1;
981                         }
982                         if (rs->rs_rlt[i].rate < bytes_per_sec) {
983                                 /*
984                                  * We found a table entry that is smaller,
985                                  * stop there will be none greater or equal.
986                                  */
987                                 break;
988                         }
989                 }
990                 if ((matched == 0) &&
991                     (flags & RS_PACING_SUB_OK)) {
992                         /* Kick in a substitute (the highest) */
993                         rte = &rs->rs_rlt[rs->rs_highest_valid];
994                 }
995         }
996         return (rte);
997 }
998
999 static struct ifnet *
1000 rt_find_real_interface(struct ifnet *ifp, struct inpcb *inp, int *error)
1001 {
1002         struct ifnet *tifp;
1003         struct m_snd_tag *tag;
1004         union if_snd_tag_alloc_params params = {
1005                 .rate_limit.hdr.type = IF_SND_TAG_TYPE_RATE_LIMIT,
1006                 .rate_limit.hdr.flowid = 1,
1007                 .rate_limit.hdr.numa_domain = inp->inp_numa_domain,
1008                 .rate_limit.max_rate = COMMON_RATE,
1009                 .rate_limit.flags = M_NOWAIT,
1010         };
1011         int err;
1012 #ifdef RSS
1013         params.rate_limit.hdr.flowtype = ((inp->inp_vflag & INP_IPV6) ?
1014             M_HASHTYPE_RSS_TCP_IPV6 : M_HASHTYPE_RSS_TCP_IPV4);
1015 #else
1016         params.rate_limit.hdr.flowtype = M_HASHTYPE_OPAQUE_HASH;
1017 #endif
1018         tag = NULL;
1019         if (ifp->if_snd_tag_alloc) {
1020                 if (error)
1021                         *error = ENODEV;
1022                 return (NULL);
1023         }
1024         err = ifp->if_snd_tag_alloc(ifp, &params, &tag);
1025         if (err) {
1026                 /* Failed to setup a tag? */
1027                 if (error)
1028                         *error = err;
1029                 return (NULL);
1030         }
1031         tifp = tag->ifp;
1032         tifp->if_snd_tag_free(tag);
1033         return (tifp);
1034 }
1035
1036 static const struct tcp_hwrate_limit_table *
1037 rt_setup_rate(struct inpcb *inp, struct ifnet *ifp, uint64_t bytes_per_sec,
1038     uint32_t flags, int *error)
1039 {
1040         /* First lets find the interface if it exists */
1041         const struct tcp_hwrate_limit_table *rte;
1042         struct tcp_rate_set *rs;
1043         struct epoch_tracker et;
1044         int err;
1045
1046         NET_EPOCH_ENTER(et);
1047 use_real_interface:
1048         CK_LIST_FOREACH(rs, &int_rs, next) {
1049                 /*
1050                  * Note we don't look with the lock since we either see a
1051                  * new entry or will get one when we try to add it.
1052                  */
1053                 if (rs->rs_flags & RS_IS_DEAD) {
1054                         /* The dead are not looked at */
1055                         continue;
1056                 }
1057                 if ((rs->rs_ifp == ifp) &&
1058                     (rs->rs_if_dunit == ifp->if_dunit)) {
1059                         /* Ok we found it */
1060                         break;
1061                 }
1062         }
1063         if ((rs == NULL) ||
1064             (rs->rs_flags & RS_INTF_NO_SUP) ||
1065             (rs->rs_flags & RS_IS_DEAD)) {
1066                 /*
1067                  * This means we got a packet *before*
1068                  * the IF-UP was processed below, <or>
1069                  * while or after we already received an interface
1070                  * departed event. In either case we really don't
1071                  * want to do anything with pacing, in
1072                  * the departing case the packet is not
1073                  * going to go very far. The new case
1074                  * might be arguable, but its impossible
1075                  * to tell from the departing case.
1076                  */
1077                 if (rs->rs_disable && error)
1078                         *error = ENODEV;
1079                 NET_EPOCH_EXIT(et);
1080                 return (NULL);
1081         }
1082
1083         if ((rs == NULL) || (rs->rs_disable != 0)) {
1084                 if (rs->rs_disable && error)
1085                         *error = ENOSPC;
1086                 NET_EPOCH_EXIT(et);
1087                 return (NULL);
1088         }
1089         if (rs->rs_flags & RS_IS_DEFF) {
1090                 /* We need to find the real interface */
1091                 struct ifnet *tifp;
1092
1093                 tifp = rt_find_real_interface(ifp, inp, error);
1094                 if (tifp == NULL) {
1095                         if (rs->rs_disable && error)
1096                                 *error = ENOTSUP;
1097                         NET_EPOCH_EXIT(et);
1098                         return (NULL);
1099                 }
1100                 goto use_real_interface;
1101         }
1102         if (rs->rs_flow_limit &&
1103             ((rs->rs_flows_using + 1) > rs->rs_flow_limit)) {
1104                 if (error)
1105                         *error = ENOSPC;
1106                 NET_EPOCH_EXIT(et);
1107                 return (NULL);
1108         }
1109         rte = tcp_find_suitable_rate(rs, bytes_per_sec, flags);
1110         if (rte) {
1111                 err = in_pcbattach_txrtlmt(inp, rs->rs_ifp,
1112                     inp->inp_flowtype,
1113                     inp->inp_flowid,
1114                     rte->rate,
1115                     &inp->inp_snd_tag);
1116                 if (err) {
1117                         /* Failed to attach */
1118                         if (error)
1119                                 *error = err;
1120                         rte = NULL;
1121                 }
1122         }
1123         if (rte) {
1124                 /*
1125                  * We use an atomic here for accounting so we don't have to
1126                  * use locks when freeing.
1127                  */
1128                 atomic_add_64(&rs->rs_flows_using, 1);
1129         }
1130         NET_EPOCH_EXIT(et);
1131         return (rte);
1132 }
1133
1134 static void
1135 tcp_rl_ifnet_link(void *arg __unused, struct ifnet *ifp, int link_state)
1136 {
1137         int error;
1138         struct tcp_rate_set *rs;
1139
1140         if (((ifp->if_capabilities & IFCAP_TXRTLMT) == 0) ||
1141             (link_state != LINK_STATE_UP)) {
1142                 /*
1143                  * We only care on an interface going up that is rate-limit
1144                  * capable.
1145                  */
1146                 return;
1147         }
1148         mtx_lock(&rs_mtx);
1149         CK_LIST_FOREACH(rs, &int_rs, next) {
1150                 if ((rs->rs_ifp == ifp) &&
1151                     (rs->rs_if_dunit == ifp->if_dunit)) {
1152                         /* We already have initialized this guy */
1153                         mtx_unlock(&rs_mtx);
1154                         return;
1155                 }
1156         }
1157         mtx_unlock(&rs_mtx);
1158         rt_setup_new_rs(ifp, &error);
1159 }
1160
1161 static void
1162 tcp_rl_ifnet_departure(void *arg __unused, struct ifnet *ifp)
1163 {
1164         struct tcp_rate_set *rs, *nrs;
1165         struct ifnet *tifp;
1166         int i;
1167
1168         mtx_lock(&rs_mtx);
1169         CK_LIST_FOREACH_SAFE(rs, &int_rs, next, nrs) {
1170                 if ((rs->rs_ifp == ifp) &&
1171                     (rs->rs_if_dunit == ifp->if_dunit)) {
1172                         CK_LIST_REMOVE(rs, next);
1173                         rs_number_alive--;
1174                         rs->rs_flags |= RS_IS_DEAD;
1175                         for (i = 0; i < rs->rs_rate_cnt; i++) {
1176                                 if (rs->rs_rlt[i].flags & HDWRPACE_TAGPRESENT) {
1177                                         tifp = rs->rs_rlt[i].tag->ifp;
1178                                         in_pcbdetach_tag(tifp, rs->rs_rlt[i].tag);
1179                                         rs->rs_rlt[i].tag = NULL;
1180                                 }
1181                                 rs->rs_rlt[i].flags = HDWRPACE_IFPDEPARTED;
1182                         }
1183                         if (rs->rs_flows_using == 0)
1184                                 rs_defer_destroy(rs);
1185                         break;
1186                 }
1187         }
1188         mtx_unlock(&rs_mtx);
1189 }
1190
1191 static void
1192 tcp_rl_shutdown(void *arg __unused, int howto __unused)
1193 {
1194         struct tcp_rate_set *rs, *nrs;
1195         struct ifnet *tifp;
1196         int i;
1197
1198         mtx_lock(&rs_mtx);
1199         CK_LIST_FOREACH_SAFE(rs, &int_rs, next, nrs) {
1200                 CK_LIST_REMOVE(rs, next);
1201                 rs_number_alive--;
1202                 rs->rs_flags |= RS_IS_DEAD;
1203                 for (i = 0; i < rs->rs_rate_cnt; i++) {
1204                         if (rs->rs_rlt[i].flags & HDWRPACE_TAGPRESENT) {
1205                                 tifp = rs->rs_rlt[i].tag->ifp;
1206                                 in_pcbdetach_tag(tifp, rs->rs_rlt[i].tag);
1207                                 rs->rs_rlt[i].tag = NULL;
1208                         }
1209                         rs->rs_rlt[i].flags = HDWRPACE_IFPDEPARTED;
1210                 }
1211                 if (rs->rs_flows_using == 0)
1212                         rs_defer_destroy(rs);
1213         }
1214         mtx_unlock(&rs_mtx);
1215 }
1216
1217 const struct tcp_hwrate_limit_table *
1218 tcp_set_pacing_rate(struct tcpcb *tp, struct ifnet *ifp,
1219     uint64_t bytes_per_sec, int flags, int *error)
1220 {
1221         const struct tcp_hwrate_limit_table *rte;
1222
1223         if (tp->t_inpcb->inp_snd_tag == NULL) {
1224                 /*
1225                  * We are setting up a rate for the first time.
1226                  */
1227                 if ((ifp->if_capabilities & IFCAP_TXRTLMT) == 0) {
1228                         /* Not supported by the egress */
1229                         if (error)
1230                                 *error = ENODEV;
1231                         return (NULL);
1232                 }
1233 #ifdef KERN_TLS
1234                 if (tp->t_inpcb->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) {
1235                         /*
1236                          * We currently can't do both TLS and hardware
1237                          * pacing
1238                          */
1239                         if (error)
1240                                 *error = EINVAL;
1241                         return (NULL);
1242                 }
1243 #endif
1244                 rte = rt_setup_rate(tp->t_inpcb, ifp, bytes_per_sec, flags, error);
1245         } else {
1246                 /*
1247                  * We are modifying a rate, wrong interface?
1248                  */
1249                 if (error)
1250                         *error = EINVAL;
1251                 rte = NULL;
1252         }
1253         *error = 0;
1254         return (rte);
1255 }
1256
1257 const struct tcp_hwrate_limit_table *
1258 tcp_chg_pacing_rate(const struct tcp_hwrate_limit_table *crte,
1259     struct tcpcb *tp, struct ifnet *ifp,
1260     uint64_t bytes_per_sec, int flags, int *error)
1261 {
1262         const struct tcp_hwrate_limit_table *nrte;
1263         const struct tcp_rate_set *rs;
1264         int is_indirect = 0;
1265         int err;
1266
1267         if ((tp->t_inpcb->inp_snd_tag == NULL) ||
1268             (crte == NULL)) {
1269                 /* Wrong interface */
1270                 if (error)
1271                         *error = EINVAL;
1272                 return (NULL);
1273         }
1274         rs = crte->ptbl;
1275         if ((rs->rs_flags & RS_IS_DEAD) ||
1276             (crte->flags & HDWRPACE_IFPDEPARTED)) {
1277                 /* Release the rate, and try anew */
1278 re_rate:
1279                 tcp_rel_pacing_rate(crte, tp);
1280                 nrte = tcp_set_pacing_rate(tp, ifp,
1281                     bytes_per_sec, flags, error);
1282                 return (nrte);
1283         }
1284         if ((rs->rs_flags & RT_IS_INDIRECT ) == RT_IS_INDIRECT)
1285                 is_indirect = 1;
1286         else
1287                 is_indirect = 0;
1288         if ((is_indirect == 0) &&
1289             ((ifp != rs->rs_ifp) ||
1290             (ifp->if_dunit != rs->rs_if_dunit))) {
1291                 /*
1292                  * Something changed, the user is not pointing to the same
1293                  * ifp? Maybe a route updated on this guy?
1294                  */
1295                 goto re_rate;
1296         } else if (is_indirect) {
1297                 /*
1298                  * For indirect we have to dig in and find the real interface.
1299                  */
1300                 struct ifnet *rifp;
1301
1302                 rifp = rt_find_real_interface(ifp, tp->t_inpcb, error);
1303                 if (rifp == NULL) {
1304                         /* Can't find it? */
1305                         goto re_rate;
1306                 }
1307                 if ((rifp != rs->rs_ifp) ||
1308                     (ifp->if_dunit != rs->rs_if_dunit)) {
1309                         goto re_rate;
1310                 }
1311         }
1312         nrte = tcp_find_suitable_rate(rs, bytes_per_sec, flags);
1313         if (nrte == crte) {
1314                 /* No change */
1315                 if (error)
1316                         *error = 0;
1317                 return (crte);
1318         }
1319         if (nrte == NULL) {
1320                 /* Release the old rate */
1321                 tcp_rel_pacing_rate(crte, tp);
1322                 return (NULL);
1323         }
1324         /* Change rates to our new entry */
1325         err = in_pcbmodify_txrtlmt(tp->t_inpcb, nrte->rate);
1326         if (err) {
1327                 if (error)
1328                         *error = err;
1329                 return (NULL);
1330         }
1331         if (error)
1332                 *error = 0;
1333         return (nrte);
1334 }
1335
1336 void
1337 tcp_rel_pacing_rate(const struct tcp_hwrate_limit_table *crte, struct tcpcb *tp)
1338 {
1339         const struct tcp_rate_set *crs;
1340         struct tcp_rate_set *rs;
1341         uint64_t pre;
1342
1343         crs = crte->ptbl;
1344         /*
1345          * Now we must break the const
1346          * in order to release our refcount.
1347          */
1348         rs = __DECONST(struct tcp_rate_set *, crs);
1349         pre = atomic_fetchadd_64(&rs->rs_flows_using, -1);
1350         if (pre == 1) {
1351                 mtx_lock(&rs_mtx);
1352                 /*
1353                  * Is it dead?
1354                  */
1355                 if (rs->rs_flags & RS_IS_DEAD)
1356                         rs_defer_destroy(rs);
1357                 mtx_unlock(&rs_mtx);
1358         }
1359         in_pcbdetach_txrtlmt(tp->t_inpcb);
1360 }
1361
1362 #define ONE_POINT_TWO_MEG 150000 /* 1.2 megabits in bytes */
1363 #define ONE_HUNDRED_MBPS 12500000       /* 100Mbps in bytes per second */
1364 #define FIVE_HUNDRED_MBPS 62500000      /* 500Mbps in bytes per second */
1365 #define MAX_MSS_SENT 43 /* 43 mss = 43 x 1500 = 64,500 bytes */
1366
1367 uint32_t
1368 tcp_get_pacing_burst_size (uint64_t bw, uint32_t segsiz, int can_use_1mss,
1369    const struct tcp_hwrate_limit_table *te, int *err)
1370 {
1371         /*
1372          * We use the google formula to calculate the
1373          * TSO size. I.E.
1374          * bw < 24Meg
1375          *   tso = 2mss
1376          * else
1377          *   tso = min(bw/1000, 64k)
1378          *
1379          * Note for these calculations we ignore the
1380          * packet overhead (enet hdr, ip hdr and tcp hdr).
1381          */
1382         uint64_t lentim, res, bytes;
1383         uint32_t new_tso, min_tso_segs;
1384
1385         bytes = bw / 1000;
1386         if (bytes > (64 * 1000))
1387                 bytes = 64 * 1000;
1388         /* Round up */
1389         new_tso = (bytes + segsiz - 1) / segsiz;
1390         if (can_use_1mss && (bw < ONE_POINT_TWO_MEG))
1391                 min_tso_segs = 1;
1392         else
1393                 min_tso_segs = 2;
1394         if (new_tso < min_tso_segs)
1395                 new_tso = min_tso_segs;
1396         if (new_tso > MAX_MSS_SENT)
1397                 new_tso = MAX_MSS_SENT;
1398         new_tso *= segsiz;
1399         /*
1400          * If we are not doing hardware pacing
1401          * then we are done.
1402          */
1403         if (te == NULL) {
1404                 if (err)
1405                         *err = 0;
1406                 return(new_tso);
1407         }
1408         /*
1409          * For hardware pacing we look at the
1410          * rate you are sending at and compare
1411          * that to the rate you have in hardware.
1412          *
1413          * If the hardware rate is slower than your
1414          * software rate then you are in error and
1415          * we will build a queue in our hardware whic
1416          * is probably not desired, in such a case
1417          * just return the non-hardware TSO size.
1418          *
1419          * If the rate in hardware is faster (which
1420          * it should be) then look at how long it
1421          * takes to send one ethernet segment size at
1422          * your b/w and compare that to the time it
1423          * takes to send at the rate you had selected.
1424          *
1425          * If your time is greater (which we hope it is)
1426          * we get the delta between the two, and then
1427          * divide that into your pacing time. This tells
1428          * us how many MSS you can send down at once (rounded up).
1429          *
1430          * Note we also double this value if the b/w is over
1431          * 100Mbps. If its over 500meg we just set you to the
1432          * max (43 segments).
1433          */
1434         if (te->rate > FIVE_HUNDRED_MBPS)
1435                 return (segsiz * MAX_MSS_SENT);
1436         if (te->rate == bw) {
1437                 /* We are pacing at exactly the hdwr rate */
1438                 return (segsiz * MAX_MSS_SENT);
1439         }
1440         lentim = ETHERNET_SEGMENT_SIZE * USECS_IN_SECOND;
1441         res = lentim / bw;
1442         if (res > te->time_between) {
1443                 uint32_t delta, segs;
1444
1445                 delta = res - te->time_between;
1446                 segs = (res + delta - 1)/delta;
1447                 if (te->rate > ONE_HUNDRED_MBPS)
1448                         segs *= 2;
1449                 if (segs < min_tso_segs)
1450                         segs = min_tso_segs;
1451                 if (segs > MAX_MSS_SENT)
1452                         segs = MAX_MSS_SENT;
1453                 segs *= segsiz;
1454                 if (err)
1455                         *err = 0;
1456                 if (segs < new_tso) {
1457                         /* unexpected ? */
1458                         return(new_tso);
1459                 } else {
1460                         return (segs);
1461                 }
1462         } else {
1463                 /*
1464                  * Your time is smaller which means
1465                  * we will grow a queue on our
1466                  * hardware. Send back the non-hardware
1467                  * rate.
1468                  */
1469                 if (err)
1470                         *err = -1;
1471                 return (new_tso);
1472         }
1473 }
1474
1475 static eventhandler_tag rl_ifnet_departs;
1476 static eventhandler_tag rl_ifnet_arrives;
1477 static eventhandler_tag rl_shutdown_start;
1478
1479 static void
1480 tcp_rs_init(void *st __unused)
1481 {
1482         CK_LIST_INIT(&int_rs);
1483         rs_number_alive = 0;
1484         rs_number_dead = 0;
1485         mtx_init(&rs_mtx, "tcp_rs_mtx", "rsmtx", MTX_DEF);
1486         rl_ifnet_departs = EVENTHANDLER_REGISTER(ifnet_departure_event,
1487             tcp_rl_ifnet_departure,
1488             NULL, EVENTHANDLER_PRI_ANY);
1489         rl_ifnet_arrives = EVENTHANDLER_REGISTER(ifnet_link_event,
1490             tcp_rl_ifnet_link,
1491             NULL, EVENTHANDLER_PRI_ANY);
1492         rl_shutdown_start = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1493             tcp_rl_shutdown, NULL,
1494             SHUTDOWN_PRI_FIRST);
1495         printf("TCP_ratelimit: Is now initialized\n");
1496 }
1497
1498 SYSINIT(tcp_rl_init, SI_SUB_SMP + 1, SI_ORDER_ANY, tcp_rs_init, NULL);
1499 #endif