IPVS: Allow boot time change of hash size
[safe/jmp/linux-2.6] / net / netfilter / ipvs / ip_vs_conn.c
1 /*
2  * IPVS         An implementation of the IP virtual server support for the
3  *              LINUX operating system.  IPVS is now implemented as a module
4  *              over the Netfilter framework. IPVS can be used to build a
5  *              high-performance and highly available server based on a
6  *              cluster of servers.
7  *
8  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
9  *              Peter Kese <peter.kese@ijs.si>
10  *              Julian Anastasov <ja@ssi.bg>
11  *
12  *              This program is free software; you can redistribute it and/or
13  *              modify it under the terms of the GNU General Public License
14  *              as published by the Free Software Foundation; either version
15  *              2 of the License, or (at your option) any later version.
16  *
17  * The IPVS code for kernel 2.2 was done by Wensong Zhang and Peter Kese,
18  * with changes/fixes from Julian Anastasov, Lars Marowsky-Bree, Horms
19  * and others. Many code here is taken from IP MASQ code of kernel 2.2.
20  *
21  * Changes:
22  *
23  */
24
25 #define KMSG_COMPONENT "IPVS"
26 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
27
28 #include <linux/interrupt.h>
29 #include <linux/in.h>
30 #include <linux/net.h>
31 #include <linux/kernel.h>
32 #include <linux/module.h>
33 #include <linux/vmalloc.h>
34 #include <linux/proc_fs.h>              /* for proc_net_* */
35 #include <linux/seq_file.h>
36 #include <linux/jhash.h>
37 #include <linux/random.h>
38
39 #include <net/net_namespace.h>
40 #include <net/ip_vs.h>
41
42
43 #ifndef CONFIG_IP_VS_TAB_BITS
44 #define CONFIG_IP_VS_TAB_BITS   12
45 #endif
46
47 /*
48  * Connection hash size. Default is what was selected at compile time.
49 */
50 int ip_vs_conn_tab_bits = CONFIG_IP_VS_TAB_BITS;
51 module_param_named(conn_tab_bits, ip_vs_conn_tab_bits, int, 0444);
52 MODULE_PARM_DESC(conn_tab_bits, "Set connections' hash size");
53
54 /* size and mask values */
55 int ip_vs_conn_tab_size;
56 int ip_vs_conn_tab_mask;
57
58 /*
59  *  Connection hash table: for input and output packets lookups of IPVS
60  */
61 static struct list_head *ip_vs_conn_tab;
62
63 /*  SLAB cache for IPVS connections */
64 static struct kmem_cache *ip_vs_conn_cachep __read_mostly;
65
66 /*  counter for current IPVS connections */
67 static atomic_t ip_vs_conn_count = ATOMIC_INIT(0);
68
69 /*  counter for no client port connections */
70 static atomic_t ip_vs_conn_no_cport_cnt = ATOMIC_INIT(0);
71
72 /* random value for IPVS connection hash */
73 static unsigned int ip_vs_conn_rnd;
74
75 /*
76  *  Fine locking granularity for big connection hash table
77  */
78 #define CT_LOCKARRAY_BITS  4
79 #define CT_LOCKARRAY_SIZE  (1<<CT_LOCKARRAY_BITS)
80 #define CT_LOCKARRAY_MASK  (CT_LOCKARRAY_SIZE-1)
81
82 struct ip_vs_aligned_lock
83 {
84         rwlock_t        l;
85 } __attribute__((__aligned__(SMP_CACHE_BYTES)));
86
87 /* lock array for conn table */
88 static struct ip_vs_aligned_lock
89 __ip_vs_conntbl_lock_array[CT_LOCKARRAY_SIZE] __cacheline_aligned;
90
91 static inline void ct_read_lock(unsigned key)
92 {
93         read_lock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
94 }
95
96 static inline void ct_read_unlock(unsigned key)
97 {
98         read_unlock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
99 }
100
101 static inline void ct_write_lock(unsigned key)
102 {
103         write_lock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
104 }
105
106 static inline void ct_write_unlock(unsigned key)
107 {
108         write_unlock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
109 }
110
111 static inline void ct_read_lock_bh(unsigned key)
112 {
113         read_lock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
114 }
115
116 static inline void ct_read_unlock_bh(unsigned key)
117 {
118         read_unlock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
119 }
120
121 static inline void ct_write_lock_bh(unsigned key)
122 {
123         write_lock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
124 }
125
126 static inline void ct_write_unlock_bh(unsigned key)
127 {
128         write_unlock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
129 }
130
131
132 /*
133  *      Returns hash value for IPVS connection entry
134  */
135 static unsigned int ip_vs_conn_hashkey(int af, unsigned proto,
136                                        const union nf_inet_addr *addr,
137                                        __be16 port)
138 {
139 #ifdef CONFIG_IP_VS_IPV6
140         if (af == AF_INET6)
141                 return jhash_3words(jhash(addr, 16, ip_vs_conn_rnd),
142                                     (__force u32)port, proto, ip_vs_conn_rnd)
143                         & ip_vs_conn_tab_mask;
144 #endif
145         return jhash_3words((__force u32)addr->ip, (__force u32)port, proto,
146                             ip_vs_conn_rnd)
147                 & ip_vs_conn_tab_mask;
148 }
149
150
151 /*
152  *      Hashes ip_vs_conn in ip_vs_conn_tab by proto,addr,port.
153  *      returns bool success.
154  */
155 static inline int ip_vs_conn_hash(struct ip_vs_conn *cp)
156 {
157         unsigned hash;
158         int ret;
159
160         /* Hash by protocol, client address and port */
161         hash = ip_vs_conn_hashkey(cp->af, cp->protocol, &cp->caddr, cp->cport);
162
163         ct_write_lock(hash);
164
165         if (!(cp->flags & IP_VS_CONN_F_HASHED)) {
166                 list_add(&cp->c_list, &ip_vs_conn_tab[hash]);
167                 cp->flags |= IP_VS_CONN_F_HASHED;
168                 atomic_inc(&cp->refcnt);
169                 ret = 1;
170         } else {
171                 pr_err("%s(): request for already hashed, called from %pF\n",
172                        __func__, __builtin_return_address(0));
173                 ret = 0;
174         }
175
176         ct_write_unlock(hash);
177
178         return ret;
179 }
180
181
182 /*
183  *      UNhashes ip_vs_conn from ip_vs_conn_tab.
184  *      returns bool success.
185  */
186 static inline int ip_vs_conn_unhash(struct ip_vs_conn *cp)
187 {
188         unsigned hash;
189         int ret;
190
191         /* unhash it and decrease its reference counter */
192         hash = ip_vs_conn_hashkey(cp->af, cp->protocol, &cp->caddr, cp->cport);
193
194         ct_write_lock(hash);
195
196         if (cp->flags & IP_VS_CONN_F_HASHED) {
197                 list_del(&cp->c_list);
198                 cp->flags &= ~IP_VS_CONN_F_HASHED;
199                 atomic_dec(&cp->refcnt);
200                 ret = 1;
201         } else
202                 ret = 0;
203
204         ct_write_unlock(hash);
205
206         return ret;
207 }
208
209
210 /*
211  *  Gets ip_vs_conn associated with supplied parameters in the ip_vs_conn_tab.
212  *  Called for pkts coming from OUTside-to-INside.
213  *      s_addr, s_port: pkt source address (foreign host)
214  *      d_addr, d_port: pkt dest address (load balancer)
215  */
216 static inline struct ip_vs_conn *__ip_vs_conn_in_get
217 (int af, int protocol, const union nf_inet_addr *s_addr, __be16 s_port,
218  const union nf_inet_addr *d_addr, __be16 d_port)
219 {
220         unsigned hash;
221         struct ip_vs_conn *cp;
222
223         hash = ip_vs_conn_hashkey(af, protocol, s_addr, s_port);
224
225         ct_read_lock(hash);
226
227         list_for_each_entry(cp, &ip_vs_conn_tab[hash], c_list) {
228                 if (cp->af == af &&
229                     ip_vs_addr_equal(af, s_addr, &cp->caddr) &&
230                     ip_vs_addr_equal(af, d_addr, &cp->vaddr) &&
231                     s_port == cp->cport && d_port == cp->vport &&
232                     ((!s_port) ^ (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) &&
233                     protocol == cp->protocol) {
234                         /* HIT */
235                         atomic_inc(&cp->refcnt);
236                         ct_read_unlock(hash);
237                         return cp;
238                 }
239         }
240
241         ct_read_unlock(hash);
242
243         return NULL;
244 }
245
246 struct ip_vs_conn *ip_vs_conn_in_get
247 (int af, int protocol, const union nf_inet_addr *s_addr, __be16 s_port,
248  const union nf_inet_addr *d_addr, __be16 d_port)
249 {
250         struct ip_vs_conn *cp;
251
252         cp = __ip_vs_conn_in_get(af, protocol, s_addr, s_port, d_addr, d_port);
253         if (!cp && atomic_read(&ip_vs_conn_no_cport_cnt))
254                 cp = __ip_vs_conn_in_get(af, protocol, s_addr, 0, d_addr,
255                                          d_port);
256
257         IP_VS_DBG_BUF(9, "lookup/in %s %s:%d->%s:%d %s\n",
258                       ip_vs_proto_name(protocol),
259                       IP_VS_DBG_ADDR(af, s_addr), ntohs(s_port),
260                       IP_VS_DBG_ADDR(af, d_addr), ntohs(d_port),
261                       cp ? "hit" : "not hit");
262
263         return cp;
264 }
265
266 /* Get reference to connection template */
267 struct ip_vs_conn *ip_vs_ct_in_get
268 (int af, int protocol, const union nf_inet_addr *s_addr, __be16 s_port,
269  const union nf_inet_addr *d_addr, __be16 d_port)
270 {
271         unsigned hash;
272         struct ip_vs_conn *cp;
273
274         hash = ip_vs_conn_hashkey(af, protocol, s_addr, s_port);
275
276         ct_read_lock(hash);
277
278         list_for_each_entry(cp, &ip_vs_conn_tab[hash], c_list) {
279                 if (cp->af == af &&
280                     ip_vs_addr_equal(af, s_addr, &cp->caddr) &&
281                     /* protocol should only be IPPROTO_IP if
282                      * d_addr is a fwmark */
283                     ip_vs_addr_equal(protocol == IPPROTO_IP ? AF_UNSPEC : af,
284                                      d_addr, &cp->vaddr) &&
285                     s_port == cp->cport && d_port == cp->vport &&
286                     cp->flags & IP_VS_CONN_F_TEMPLATE &&
287                     protocol == cp->protocol) {
288                         /* HIT */
289                         atomic_inc(&cp->refcnt);
290                         goto out;
291                 }
292         }
293         cp = NULL;
294
295   out:
296         ct_read_unlock(hash);
297
298         IP_VS_DBG_BUF(9, "template lookup/in %s %s:%d->%s:%d %s\n",
299                       ip_vs_proto_name(protocol),
300                       IP_VS_DBG_ADDR(af, s_addr), ntohs(s_port),
301                       IP_VS_DBG_ADDR(af, d_addr), ntohs(d_port),
302                       cp ? "hit" : "not hit");
303
304         return cp;
305 }
306
307 /*
308  *  Gets ip_vs_conn associated with supplied parameters in the ip_vs_conn_tab.
309  *  Called for pkts coming from inside-to-OUTside.
310  *      s_addr, s_port: pkt source address (inside host)
311  *      d_addr, d_port: pkt dest address (foreign host)
312  */
313 struct ip_vs_conn *ip_vs_conn_out_get
314 (int af, int protocol, const union nf_inet_addr *s_addr, __be16 s_port,
315  const union nf_inet_addr *d_addr, __be16 d_port)
316 {
317         unsigned hash;
318         struct ip_vs_conn *cp, *ret=NULL;
319
320         /*
321          *      Check for "full" addressed entries
322          */
323         hash = ip_vs_conn_hashkey(af, protocol, d_addr, d_port);
324
325         ct_read_lock(hash);
326
327         list_for_each_entry(cp, &ip_vs_conn_tab[hash], c_list) {
328                 if (cp->af == af &&
329                     ip_vs_addr_equal(af, d_addr, &cp->caddr) &&
330                     ip_vs_addr_equal(af, s_addr, &cp->daddr) &&
331                     d_port == cp->cport && s_port == cp->dport &&
332                     protocol == cp->protocol) {
333                         /* HIT */
334                         atomic_inc(&cp->refcnt);
335                         ret = cp;
336                         break;
337                 }
338         }
339
340         ct_read_unlock(hash);
341
342         IP_VS_DBG_BUF(9, "lookup/out %s %s:%d->%s:%d %s\n",
343                       ip_vs_proto_name(protocol),
344                       IP_VS_DBG_ADDR(af, s_addr), ntohs(s_port),
345                       IP_VS_DBG_ADDR(af, d_addr), ntohs(d_port),
346                       ret ? "hit" : "not hit");
347
348         return ret;
349 }
350
351
352 /*
353  *      Put back the conn and restart its timer with its timeout
354  */
355 void ip_vs_conn_put(struct ip_vs_conn *cp)
356 {
357         /* reset it expire in its timeout */
358         mod_timer(&cp->timer, jiffies+cp->timeout);
359
360         __ip_vs_conn_put(cp);
361 }
362
363
364 /*
365  *      Fill a no_client_port connection with a client port number
366  */
367 void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport)
368 {
369         if (ip_vs_conn_unhash(cp)) {
370                 spin_lock(&cp->lock);
371                 if (cp->flags & IP_VS_CONN_F_NO_CPORT) {
372                         atomic_dec(&ip_vs_conn_no_cport_cnt);
373                         cp->flags &= ~IP_VS_CONN_F_NO_CPORT;
374                         cp->cport = cport;
375                 }
376                 spin_unlock(&cp->lock);
377
378                 /* hash on new dport */
379                 ip_vs_conn_hash(cp);
380         }
381 }
382
383
384 /*
385  *      Bind a connection entry with the corresponding packet_xmit.
386  *      Called by ip_vs_conn_new.
387  */
388 static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp)
389 {
390         switch (IP_VS_FWD_METHOD(cp)) {
391         case IP_VS_CONN_F_MASQ:
392                 cp->packet_xmit = ip_vs_nat_xmit;
393                 break;
394
395         case IP_VS_CONN_F_TUNNEL:
396                 cp->packet_xmit = ip_vs_tunnel_xmit;
397                 break;
398
399         case IP_VS_CONN_F_DROUTE:
400                 cp->packet_xmit = ip_vs_dr_xmit;
401                 break;
402
403         case IP_VS_CONN_F_LOCALNODE:
404                 cp->packet_xmit = ip_vs_null_xmit;
405                 break;
406
407         case IP_VS_CONN_F_BYPASS:
408                 cp->packet_xmit = ip_vs_bypass_xmit;
409                 break;
410         }
411 }
412
413 #ifdef CONFIG_IP_VS_IPV6
414 static inline void ip_vs_bind_xmit_v6(struct ip_vs_conn *cp)
415 {
416         switch (IP_VS_FWD_METHOD(cp)) {
417         case IP_VS_CONN_F_MASQ:
418                 cp->packet_xmit = ip_vs_nat_xmit_v6;
419                 break;
420
421         case IP_VS_CONN_F_TUNNEL:
422                 cp->packet_xmit = ip_vs_tunnel_xmit_v6;
423                 break;
424
425         case IP_VS_CONN_F_DROUTE:
426                 cp->packet_xmit = ip_vs_dr_xmit_v6;
427                 break;
428
429         case IP_VS_CONN_F_LOCALNODE:
430                 cp->packet_xmit = ip_vs_null_xmit;
431                 break;
432
433         case IP_VS_CONN_F_BYPASS:
434                 cp->packet_xmit = ip_vs_bypass_xmit_v6;
435                 break;
436         }
437 }
438 #endif
439
440
441 static inline int ip_vs_dest_totalconns(struct ip_vs_dest *dest)
442 {
443         return atomic_read(&dest->activeconns)
444                 + atomic_read(&dest->inactconns);
445 }
446
447 /*
448  *      Bind a connection entry with a virtual service destination
449  *      Called just after a new connection entry is created.
450  */
451 static inline void
452 ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest)
453 {
454         /* if dest is NULL, then return directly */
455         if (!dest)
456                 return;
457
458         /* Increase the refcnt counter of the dest */
459         atomic_inc(&dest->refcnt);
460
461         /* Bind with the destination and its corresponding transmitter */
462         if ((cp->flags & IP_VS_CONN_F_SYNC) &&
463             (!(cp->flags & IP_VS_CONN_F_TEMPLATE)))
464                 /* if the connection is not template and is created
465                  * by sync, preserve the activity flag.
466                  */
467                 cp->flags |= atomic_read(&dest->conn_flags) &
468                              (~IP_VS_CONN_F_INACTIVE);
469         else
470                 cp->flags |= atomic_read(&dest->conn_flags);
471         cp->dest = dest;
472
473         IP_VS_DBG_BUF(7, "Bind-dest %s c:%s:%d v:%s:%d "
474                       "d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
475                       "dest->refcnt:%d\n",
476                       ip_vs_proto_name(cp->protocol),
477                       IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
478                       IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
479                       IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport),
480                       ip_vs_fwd_tag(cp), cp->state,
481                       cp->flags, atomic_read(&cp->refcnt),
482                       atomic_read(&dest->refcnt));
483
484         /* Update the connection counters */
485         if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
486                 /* It is a normal connection, so increase the inactive
487                    connection counter because it is in TCP SYNRECV
488                    state (inactive) or other protocol inacive state */
489                 if ((cp->flags & IP_VS_CONN_F_SYNC) &&
490                     (!(cp->flags & IP_VS_CONN_F_INACTIVE)))
491                         atomic_inc(&dest->activeconns);
492                 else
493                         atomic_inc(&dest->inactconns);
494         } else {
495                 /* It is a persistent connection/template, so increase
496                    the peristent connection counter */
497                 atomic_inc(&dest->persistconns);
498         }
499
500         if (dest->u_threshold != 0 &&
501             ip_vs_dest_totalconns(dest) >= dest->u_threshold)
502                 dest->flags |= IP_VS_DEST_F_OVERLOAD;
503 }
504
505
506 /*
507  * Check if there is a destination for the connection, if so
508  * bind the connection to the destination.
509  */
510 struct ip_vs_dest *ip_vs_try_bind_dest(struct ip_vs_conn *cp)
511 {
512         struct ip_vs_dest *dest;
513
514         if ((cp) && (!cp->dest)) {
515                 dest = ip_vs_find_dest(cp->af, &cp->daddr, cp->dport,
516                                        &cp->vaddr, cp->vport,
517                                        cp->protocol);
518                 ip_vs_bind_dest(cp, dest);
519                 return dest;
520         } else
521                 return NULL;
522 }
523
524
525 /*
526  *      Unbind a connection entry with its VS destination
527  *      Called by the ip_vs_conn_expire function.
528  */
529 static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp)
530 {
531         struct ip_vs_dest *dest = cp->dest;
532
533         if (!dest)
534                 return;
535
536         IP_VS_DBG_BUF(7, "Unbind-dest %s c:%s:%d v:%s:%d "
537                       "d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
538                       "dest->refcnt:%d\n",
539                       ip_vs_proto_name(cp->protocol),
540                       IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
541                       IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
542                       IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport),
543                       ip_vs_fwd_tag(cp), cp->state,
544                       cp->flags, atomic_read(&cp->refcnt),
545                       atomic_read(&dest->refcnt));
546
547         /* Update the connection counters */
548         if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
549                 /* It is a normal connection, so decrease the inactconns
550                    or activeconns counter */
551                 if (cp->flags & IP_VS_CONN_F_INACTIVE) {
552                         atomic_dec(&dest->inactconns);
553                 } else {
554                         atomic_dec(&dest->activeconns);
555                 }
556         } else {
557                 /* It is a persistent connection/template, so decrease
558                    the peristent connection counter */
559                 atomic_dec(&dest->persistconns);
560         }
561
562         if (dest->l_threshold != 0) {
563                 if (ip_vs_dest_totalconns(dest) < dest->l_threshold)
564                         dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
565         } else if (dest->u_threshold != 0) {
566                 if (ip_vs_dest_totalconns(dest) * 4 < dest->u_threshold * 3)
567                         dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
568         } else {
569                 if (dest->flags & IP_VS_DEST_F_OVERLOAD)
570                         dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
571         }
572
573         /*
574          * Simply decrease the refcnt of the dest, because the
575          * dest will be either in service's destination list
576          * or in the trash.
577          */
578         atomic_dec(&dest->refcnt);
579 }
580
581
582 /*
583  *      Checking if the destination of a connection template is available.
584  *      If available, return 1, otherwise invalidate this connection
585  *      template and return 0.
586  */
587 int ip_vs_check_template(struct ip_vs_conn *ct)
588 {
589         struct ip_vs_dest *dest = ct->dest;
590
591         /*
592          * Checking the dest server status.
593          */
594         if ((dest == NULL) ||
595             !(dest->flags & IP_VS_DEST_F_AVAILABLE) ||
596             (sysctl_ip_vs_expire_quiescent_template &&
597              (atomic_read(&dest->weight) == 0))) {
598                 IP_VS_DBG_BUF(9, "check_template: dest not available for "
599                               "protocol %s s:%s:%d v:%s:%d "
600                               "-> d:%s:%d\n",
601                               ip_vs_proto_name(ct->protocol),
602                               IP_VS_DBG_ADDR(ct->af, &ct->caddr),
603                               ntohs(ct->cport),
604                               IP_VS_DBG_ADDR(ct->af, &ct->vaddr),
605                               ntohs(ct->vport),
606                               IP_VS_DBG_ADDR(ct->af, &ct->daddr),
607                               ntohs(ct->dport));
608
609                 /*
610                  * Invalidate the connection template
611                  */
612                 if (ct->vport != htons(0xffff)) {
613                         if (ip_vs_conn_unhash(ct)) {
614                                 ct->dport = htons(0xffff);
615                                 ct->vport = htons(0xffff);
616                                 ct->cport = 0;
617                                 ip_vs_conn_hash(ct);
618                         }
619                 }
620
621                 /*
622                  * Simply decrease the refcnt of the template,
623                  * don't restart its timer.
624                  */
625                 atomic_dec(&ct->refcnt);
626                 return 0;
627         }
628         return 1;
629 }
630
631 static void ip_vs_conn_expire(unsigned long data)
632 {
633         struct ip_vs_conn *cp = (struct ip_vs_conn *)data;
634
635         cp->timeout = 60*HZ;
636
637         /*
638          *      hey, I'm using it
639          */
640         atomic_inc(&cp->refcnt);
641
642         /*
643          *      do I control anybody?
644          */
645         if (atomic_read(&cp->n_control))
646                 goto expire_later;
647
648         /*
649          *      unhash it if it is hashed in the conn table
650          */
651         if (!ip_vs_conn_unhash(cp))
652                 goto expire_later;
653
654         /*
655          *      refcnt==1 implies I'm the only one referrer
656          */
657         if (likely(atomic_read(&cp->refcnt) == 1)) {
658                 /* delete the timer if it is activated by other users */
659                 if (timer_pending(&cp->timer))
660                         del_timer(&cp->timer);
661
662                 /* does anybody control me? */
663                 if (cp->control)
664                         ip_vs_control_del(cp);
665
666                 if (unlikely(cp->app != NULL))
667                         ip_vs_unbind_app(cp);
668                 ip_vs_unbind_dest(cp);
669                 if (cp->flags & IP_VS_CONN_F_NO_CPORT)
670                         atomic_dec(&ip_vs_conn_no_cport_cnt);
671                 atomic_dec(&ip_vs_conn_count);
672
673                 kmem_cache_free(ip_vs_conn_cachep, cp);
674                 return;
675         }
676
677         /* hash it back to the table */
678         ip_vs_conn_hash(cp);
679
680   expire_later:
681         IP_VS_DBG(7, "delayed: conn->refcnt-1=%d conn->n_control=%d\n",
682                   atomic_read(&cp->refcnt)-1,
683                   atomic_read(&cp->n_control));
684
685         ip_vs_conn_put(cp);
686 }
687
688
689 void ip_vs_conn_expire_now(struct ip_vs_conn *cp)
690 {
691         if (del_timer(&cp->timer))
692                 mod_timer(&cp->timer, jiffies);
693 }
694
695
696 /*
697  *      Create a new connection entry and hash it into the ip_vs_conn_tab
698  */
699 struct ip_vs_conn *
700 ip_vs_conn_new(int af, int proto, const union nf_inet_addr *caddr, __be16 cport,
701                const union nf_inet_addr *vaddr, __be16 vport,
702                const union nf_inet_addr *daddr, __be16 dport, unsigned flags,
703                struct ip_vs_dest *dest)
704 {
705         struct ip_vs_conn *cp;
706         struct ip_vs_protocol *pp = ip_vs_proto_get(proto);
707
708         cp = kmem_cache_zalloc(ip_vs_conn_cachep, GFP_ATOMIC);
709         if (cp == NULL) {
710                 IP_VS_ERR_RL("%s(): no memory\n", __func__);
711                 return NULL;
712         }
713
714         INIT_LIST_HEAD(&cp->c_list);
715         setup_timer(&cp->timer, ip_vs_conn_expire, (unsigned long)cp);
716         cp->af             = af;
717         cp->protocol       = proto;
718         ip_vs_addr_copy(af, &cp->caddr, caddr);
719         cp->cport          = cport;
720         ip_vs_addr_copy(af, &cp->vaddr, vaddr);
721         cp->vport          = vport;
722         /* proto should only be IPPROTO_IP if d_addr is a fwmark */
723         ip_vs_addr_copy(proto == IPPROTO_IP ? AF_UNSPEC : af,
724                         &cp->daddr, daddr);
725         cp->dport          = dport;
726         cp->flags          = flags;
727         spin_lock_init(&cp->lock);
728
729         /*
730          * Set the entry is referenced by the current thread before hashing
731          * it in the table, so that other thread run ip_vs_random_dropentry
732          * but cannot drop this entry.
733          */
734         atomic_set(&cp->refcnt, 1);
735
736         atomic_set(&cp->n_control, 0);
737         atomic_set(&cp->in_pkts, 0);
738
739         atomic_inc(&ip_vs_conn_count);
740         if (flags & IP_VS_CONN_F_NO_CPORT)
741                 atomic_inc(&ip_vs_conn_no_cport_cnt);
742
743         /* Bind the connection with a destination server */
744         ip_vs_bind_dest(cp, dest);
745
746         /* Set its state and timeout */
747         cp->state = 0;
748         cp->timeout = 3*HZ;
749
750         /* Bind its packet transmitter */
751 #ifdef CONFIG_IP_VS_IPV6
752         if (af == AF_INET6)
753                 ip_vs_bind_xmit_v6(cp);
754         else
755 #endif
756                 ip_vs_bind_xmit(cp);
757
758         if (unlikely(pp && atomic_read(&pp->appcnt)))
759                 ip_vs_bind_app(cp, pp);
760
761         /* Hash it in the ip_vs_conn_tab finally */
762         ip_vs_conn_hash(cp);
763
764         return cp;
765 }
766
767
768 /*
769  *      /proc/net/ip_vs_conn entries
770  */
771 #ifdef CONFIG_PROC_FS
772
773 static void *ip_vs_conn_array(struct seq_file *seq, loff_t pos)
774 {
775         int idx;
776         struct ip_vs_conn *cp;
777
778         for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
779                 ct_read_lock_bh(idx);
780                 list_for_each_entry(cp, &ip_vs_conn_tab[idx], c_list) {
781                         if (pos-- == 0) {
782                                 seq->private = &ip_vs_conn_tab[idx];
783                                 return cp;
784                         }
785                 }
786                 ct_read_unlock_bh(idx);
787         }
788
789         return NULL;
790 }
791
792 static void *ip_vs_conn_seq_start(struct seq_file *seq, loff_t *pos)
793 {
794         seq->private = NULL;
795         return *pos ? ip_vs_conn_array(seq, *pos - 1) :SEQ_START_TOKEN;
796 }
797
798 static void *ip_vs_conn_seq_next(struct seq_file *seq, void *v, loff_t *pos)
799 {
800         struct ip_vs_conn *cp = v;
801         struct list_head *e, *l = seq->private;
802         int idx;
803
804         ++*pos;
805         if (v == SEQ_START_TOKEN)
806                 return ip_vs_conn_array(seq, 0);
807
808         /* more on same hash chain? */
809         if ((e = cp->c_list.next) != l)
810                 return list_entry(e, struct ip_vs_conn, c_list);
811
812         idx = l - ip_vs_conn_tab;
813         ct_read_unlock_bh(idx);
814
815         while (++idx < ip_vs_conn_tab_size) {
816                 ct_read_lock_bh(idx);
817                 list_for_each_entry(cp, &ip_vs_conn_tab[idx], c_list) {
818                         seq->private = &ip_vs_conn_tab[idx];
819                         return cp;
820                 }
821                 ct_read_unlock_bh(idx);
822         }
823         seq->private = NULL;
824         return NULL;
825 }
826
827 static void ip_vs_conn_seq_stop(struct seq_file *seq, void *v)
828 {
829         struct list_head *l = seq->private;
830
831         if (l)
832                 ct_read_unlock_bh(l - ip_vs_conn_tab);
833 }
834
835 static int ip_vs_conn_seq_show(struct seq_file *seq, void *v)
836 {
837
838         if (v == SEQ_START_TOKEN)
839                 seq_puts(seq,
840    "Pro FromIP   FPrt ToIP     TPrt DestIP   DPrt State       Expires\n");
841         else {
842                 const struct ip_vs_conn *cp = v;
843
844 #ifdef CONFIG_IP_VS_IPV6
845                 if (cp->af == AF_INET6)
846                         seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X %pI6 %04X %-11s %7lu\n",
847                                 ip_vs_proto_name(cp->protocol),
848                                 &cp->caddr.in6, ntohs(cp->cport),
849                                 &cp->vaddr.in6, ntohs(cp->vport),
850                                 &cp->daddr.in6, ntohs(cp->dport),
851                                 ip_vs_state_name(cp->protocol, cp->state),
852                                 (cp->timer.expires-jiffies)/HZ);
853                 else
854 #endif
855                         seq_printf(seq,
856                                 "%-3s %08X %04X %08X %04X"
857                                 " %08X %04X %-11s %7lu\n",
858                                 ip_vs_proto_name(cp->protocol),
859                                 ntohl(cp->caddr.ip), ntohs(cp->cport),
860                                 ntohl(cp->vaddr.ip), ntohs(cp->vport),
861                                 ntohl(cp->daddr.ip), ntohs(cp->dport),
862                                 ip_vs_state_name(cp->protocol, cp->state),
863                                 (cp->timer.expires-jiffies)/HZ);
864         }
865         return 0;
866 }
867
868 static const struct seq_operations ip_vs_conn_seq_ops = {
869         .start = ip_vs_conn_seq_start,
870         .next  = ip_vs_conn_seq_next,
871         .stop  = ip_vs_conn_seq_stop,
872         .show  = ip_vs_conn_seq_show,
873 };
874
875 static int ip_vs_conn_open(struct inode *inode, struct file *file)
876 {
877         return seq_open(file, &ip_vs_conn_seq_ops);
878 }
879
880 static const struct file_operations ip_vs_conn_fops = {
881         .owner   = THIS_MODULE,
882         .open    = ip_vs_conn_open,
883         .read    = seq_read,
884         .llseek  = seq_lseek,
885         .release = seq_release,
886 };
887
888 static const char *ip_vs_origin_name(unsigned flags)
889 {
890         if (flags & IP_VS_CONN_F_SYNC)
891                 return "SYNC";
892         else
893                 return "LOCAL";
894 }
895
896 static int ip_vs_conn_sync_seq_show(struct seq_file *seq, void *v)
897 {
898
899         if (v == SEQ_START_TOKEN)
900                 seq_puts(seq,
901    "Pro FromIP   FPrt ToIP     TPrt DestIP   DPrt State       Origin Expires\n");
902         else {
903                 const struct ip_vs_conn *cp = v;
904
905 #ifdef CONFIG_IP_VS_IPV6
906                 if (cp->af == AF_INET6)
907                         seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X %pI6 %04X %-11s %-6s %7lu\n",
908                                 ip_vs_proto_name(cp->protocol),
909                                 &cp->caddr.in6, ntohs(cp->cport),
910                                 &cp->vaddr.in6, ntohs(cp->vport),
911                                 &cp->daddr.in6, ntohs(cp->dport),
912                                 ip_vs_state_name(cp->protocol, cp->state),
913                                 ip_vs_origin_name(cp->flags),
914                                 (cp->timer.expires-jiffies)/HZ);
915                 else
916 #endif
917                         seq_printf(seq,
918                                 "%-3s %08X %04X %08X %04X "
919                                 "%08X %04X %-11s %-6s %7lu\n",
920                                 ip_vs_proto_name(cp->protocol),
921                                 ntohl(cp->caddr.ip), ntohs(cp->cport),
922                                 ntohl(cp->vaddr.ip), ntohs(cp->vport),
923                                 ntohl(cp->daddr.ip), ntohs(cp->dport),
924                                 ip_vs_state_name(cp->protocol, cp->state),
925                                 ip_vs_origin_name(cp->flags),
926                                 (cp->timer.expires-jiffies)/HZ);
927         }
928         return 0;
929 }
930
931 static const struct seq_operations ip_vs_conn_sync_seq_ops = {
932         .start = ip_vs_conn_seq_start,
933         .next  = ip_vs_conn_seq_next,
934         .stop  = ip_vs_conn_seq_stop,
935         .show  = ip_vs_conn_sync_seq_show,
936 };
937
938 static int ip_vs_conn_sync_open(struct inode *inode, struct file *file)
939 {
940         return seq_open(file, &ip_vs_conn_sync_seq_ops);
941 }
942
943 static const struct file_operations ip_vs_conn_sync_fops = {
944         .owner   = THIS_MODULE,
945         .open    = ip_vs_conn_sync_open,
946         .read    = seq_read,
947         .llseek  = seq_lseek,
948         .release = seq_release,
949 };
950
951 #endif
952
953
954 /*
955  *      Randomly drop connection entries before running out of memory
956  */
957 static inline int todrop_entry(struct ip_vs_conn *cp)
958 {
959         /*
960          * The drop rate array needs tuning for real environments.
961          * Called from timer bh only => no locking
962          */
963         static const char todrop_rate[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
964         static char todrop_counter[9] = {0};
965         int i;
966
967         /* if the conn entry hasn't lasted for 60 seconds, don't drop it.
968            This will leave enough time for normal connection to get
969            through. */
970         if (time_before(cp->timeout + jiffies, cp->timer.expires + 60*HZ))
971                 return 0;
972
973         /* Don't drop the entry if its number of incoming packets is not
974            located in [0, 8] */
975         i = atomic_read(&cp->in_pkts);
976         if (i > 8 || i < 0) return 0;
977
978         if (!todrop_rate[i]) return 0;
979         if (--todrop_counter[i] > 0) return 0;
980
981         todrop_counter[i] = todrop_rate[i];
982         return 1;
983 }
984
985 /* Called from keventd and must protect itself from softirqs */
986 void ip_vs_random_dropentry(void)
987 {
988         int idx;
989         struct ip_vs_conn *cp;
990
991         /*
992          * Randomly scan 1/32 of the whole table every second
993          */
994         for (idx = 0; idx < (ip_vs_conn_tab_size>>5); idx++) {
995                 unsigned hash = net_random() & ip_vs_conn_tab_mask;
996
997                 /*
998                  *  Lock is actually needed in this loop.
999                  */
1000                 ct_write_lock_bh(hash);
1001
1002                 list_for_each_entry(cp, &ip_vs_conn_tab[hash], c_list) {
1003                         if (cp->flags & IP_VS_CONN_F_TEMPLATE)
1004                                 /* connection template */
1005                                 continue;
1006
1007                         if (cp->protocol == IPPROTO_TCP) {
1008                                 switch(cp->state) {
1009                                 case IP_VS_TCP_S_SYN_RECV:
1010                                 case IP_VS_TCP_S_SYNACK:
1011                                         break;
1012
1013                                 case IP_VS_TCP_S_ESTABLISHED:
1014                                         if (todrop_entry(cp))
1015                                                 break;
1016                                         continue;
1017
1018                                 default:
1019                                         continue;
1020                                 }
1021                         } else {
1022                                 if (!todrop_entry(cp))
1023                                         continue;
1024                         }
1025
1026                         IP_VS_DBG(4, "del connection\n");
1027                         ip_vs_conn_expire_now(cp);
1028                         if (cp->control) {
1029                                 IP_VS_DBG(4, "del conn template\n");
1030                                 ip_vs_conn_expire_now(cp->control);
1031                         }
1032                 }
1033                 ct_write_unlock_bh(hash);
1034         }
1035 }
1036
1037
1038 /*
1039  *      Flush all the connection entries in the ip_vs_conn_tab
1040  */
1041 static void ip_vs_conn_flush(void)
1042 {
1043         int idx;
1044         struct ip_vs_conn *cp;
1045
1046   flush_again:
1047         for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
1048                 /*
1049                  *  Lock is actually needed in this loop.
1050                  */
1051                 ct_write_lock_bh(idx);
1052
1053                 list_for_each_entry(cp, &ip_vs_conn_tab[idx], c_list) {
1054
1055                         IP_VS_DBG(4, "del connection\n");
1056                         ip_vs_conn_expire_now(cp);
1057                         if (cp->control) {
1058                                 IP_VS_DBG(4, "del conn template\n");
1059                                 ip_vs_conn_expire_now(cp->control);
1060                         }
1061                 }
1062                 ct_write_unlock_bh(idx);
1063         }
1064
1065         /* the counter may be not NULL, because maybe some conn entries
1066            are run by slow timer handler or unhashed but still referred */
1067         if (atomic_read(&ip_vs_conn_count) != 0) {
1068                 schedule();
1069                 goto flush_again;
1070         }
1071 }
1072
1073
1074 int __init ip_vs_conn_init(void)
1075 {
1076         int idx;
1077
1078         /* Compute size and mask */
1079         ip_vs_conn_tab_size = 1 << ip_vs_conn_tab_bits;
1080         ip_vs_conn_tab_mask = ip_vs_conn_tab_size - 1;
1081
1082         /*
1083          * Allocate the connection hash table and initialize its list heads
1084          */
1085         ip_vs_conn_tab = vmalloc(ip_vs_conn_tab_size *
1086                                  sizeof(struct list_head));
1087         if (!ip_vs_conn_tab)
1088                 return -ENOMEM;
1089
1090         /* Allocate ip_vs_conn slab cache */
1091         ip_vs_conn_cachep = kmem_cache_create("ip_vs_conn",
1092                                               sizeof(struct ip_vs_conn), 0,
1093                                               SLAB_HWCACHE_ALIGN, NULL);
1094         if (!ip_vs_conn_cachep) {
1095                 vfree(ip_vs_conn_tab);
1096                 return -ENOMEM;
1097         }
1098
1099         pr_info("Connection hash table configured "
1100                 "(size=%d, memory=%ldKbytes)\n",
1101                 ip_vs_conn_tab_size,
1102                 (long)(ip_vs_conn_tab_size*sizeof(struct list_head))/1024);
1103         IP_VS_DBG(0, "Each connection entry needs %Zd bytes at least\n",
1104                   sizeof(struct ip_vs_conn));
1105
1106         for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
1107                 INIT_LIST_HEAD(&ip_vs_conn_tab[idx]);
1108         }
1109
1110         for (idx = 0; idx < CT_LOCKARRAY_SIZE; idx++)  {
1111                 rwlock_init(&__ip_vs_conntbl_lock_array[idx].l);
1112         }
1113
1114         proc_net_fops_create(&init_net, "ip_vs_conn", 0, &ip_vs_conn_fops);
1115         proc_net_fops_create(&init_net, "ip_vs_conn_sync", 0, &ip_vs_conn_sync_fops);
1116
1117         /* calculate the random value for connection hash */
1118         get_random_bytes(&ip_vs_conn_rnd, sizeof(ip_vs_conn_rnd));
1119
1120         return 0;
1121 }
1122
1123
1124 void ip_vs_conn_cleanup(void)
1125 {
1126         /* flush all the connection entries first */
1127         ip_vs_conn_flush();
1128
1129         /* Release the empty cache */
1130         kmem_cache_destroy(ip_vs_conn_cachep);
1131         proc_net_remove(&init_net, "ip_vs_conn");
1132         proc_net_remove(&init_net, "ip_vs_conn_sync");
1133         vfree(ip_vs_conn_tab);
1134 }