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