unix cm rx-oblivious connection pooling
[openafs.git] / src / afs / afs_conn.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * Implements:
12  */
13 #include <afsconfig.h>
14 #include "afs/param.h"
15
16
17 #include "afs/stds.h"
18 #include "afs/sysincludes.h"    /* Standard vendor system headers */
19
20 #if !defined(UKERNEL)
21 #if !defined(AFS_LINUX20_ENV)
22 #include <net/if.h>
23 #endif
24 #include <netinet/in.h>
25
26 #ifdef AFS_SGI62_ENV
27 #include "h/hashing.h"
28 #endif
29 #if !defined(AFS_HPUX110_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV)
30 #include <netinet/in_var.h>
31 #endif /* ! AFS_HPUX110_ENV */
32 #endif /* !defined(UKERNEL) */
33
34 #include "afsincludes.h"        /* Afs-based standard headers */
35 #include "afs/afs_stats.h"      /* afs statistics */
36
37 #if     defined(AFS_SUN56_ENV)
38 #include <inet/led.h>
39 #include <inet/common.h>
40 #if     defined(AFS_SUN58_ENV)
41 #include <netinet/ip6.h>
42 #endif
43 #include <inet/ip.h>
44 #endif
45
46 /* Exported variables */
47 afs_rwlock_t afs_xconn;         /* allocation lock for new things */
48 afs_rwlock_t afs_xinterface;    /* for multiple client address */
49 afs_int32 cryptall = 0;         /* encrypt all communications */
50
51 /* some connection macros */
52
53 /* a constructor */
54 #define new_conn_vector(xcv) \
55 do { \
56         xcv = (struct sa_conn_vector *) \
57         afs_osi_Alloc(sizeof(struct sa_conn_vector)); \
58         if (xcv) { \
59                 memset((char *)xcv, 0, sizeof(struct sa_conn_vector)); \
60         } \
61 } while (0);
62
63 /* select a connection to return (if no connection has lower utilization
64  * than any other) */
65 #define conn_vec_select_conn(xcv, bix, conn) \
66 do { \
67     (bix) = ((xcv)->select_index)++ % CVEC_LEN; \
68     (conn) = &((xcv)->cvec[bix]); \
69 } while (0);
70
71 #define struct_conn(s) ((struct afs_conn *)(s))
72
73 #define REPORT_CONNECTIONS_ISSUED 0 /* enable to see utilization */
74
75 /**
76  * Find a connection with call slots available, allocating one
77  * if nothing is available and we find an allocated slot
78  * @param xcv  A connection vector
79  * @param create  If set, a new connection may be created
80  */
81 static struct afs_conn *
82 find_preferred_connection(struct sa_conn_vector *xcv, int create)
83 {
84     afs_int32 cix, bix;
85     struct afs_conn *tc = NULL;
86
87     bix = -1;
88     for(cix = 0; cix < CVEC_LEN; ++cix) {
89         tc = &(xcv->cvec[cix]);
90         if (!tc->id) {
91             if (create) {
92                 tc->parent = xcv;
93                 tc->forceConnectFS = 1;
94                 tc->activated = 1;
95                 bix = cix;
96                 break;
97             } /* create */
98         } else {
99             if (tc->refCount < (RX_MAXCALLS-1)) {
100                 bix = cix;
101                 goto f_conn;
102             } else if (cix == (CVEC_LEN-1))
103                 conn_vec_select_conn(xcv, bix, tc);
104         } /* tc->id */
105     } /* for cix < CVEC_LEN */
106
107     if (bix < 0) {
108         afs_warn("find_preferred_connection: no connection and !create\n");
109         tc = NULL;
110         goto out;
111     }
112
113 f_conn:
114     tc->refCount++;
115     xcv->refCount++;
116
117 #if REPORT_CONNECTIONS_ISSUED
118     afs_warn("Issuing conn %d refCount=%d parent refCount=%d\n", bix,
119              tc->refCount, xcv->refCount);
120 #endif
121
122 out:
123     return (tc);
124
125 }        /* find_preferred_connection */
126
127
128 /**
129  * Release all connections for unix user xu at server xs
130  * @param xu
131  * @param xs
132  */
133 static void
134 release_conns_user_server(struct unixuser *xu, struct server *xs)
135 {
136     int cix, glocked;
137     struct srvAddr *sa;
138     struct afs_conn *tc;
139     struct sa_conn_vector *tcv, **lcv;
140     for (sa = (xs)->addr; sa; sa = sa->next_sa) {
141         lcv = &sa->conns;
142         for (tcv = *lcv; tcv; lcv = &tcv->next, tcv = *lcv) {
143             if (tcv->user == (xu) && tcv->refCount == 0) {
144                 *lcv = tcv->next;
145                 /* our old friend, the GLOCK */
146                 glocked = ISAFS_GLOCK();
147                 if (glocked)
148                     AFS_GUNLOCK();
149                 for(cix = 0; cix < CVEC_LEN; ++cix) {
150                     tc = &(tcv->cvec[cix]);
151                     if (tc->activated)
152                         rx_DestroyConnection(tc->id);
153                 }
154                 if (glocked)
155                     AFS_GLOCK();
156                 afs_osi_Free(tcv, sizeof(struct sa_conn_vector));
157                 break;    /* at most one instance per server */
158             } /*Found unreferenced connection for user */
159         }
160     } /*For each connection on the server */
161
162 }        /* release_conns_user_server */
163
164
165 static void
166 release_conns_vector(struct sa_conn_vector *xcv)
167 {
168     int cix, glocked;
169     struct afs_conn *tc;
170     struct sa_conn_vector *tcv = NULL;
171     struct sa_conn_vector **lcv = NULL;
172     for (tcv = xcv; tcv; lcv = &tcv->next, tcv = *lcv) {
173         *lcv = tcv->next;
174         /* you know it, you love it, the GLOCK */
175         glocked = ISAFS_GLOCK();
176         if (glocked)
177             AFS_GUNLOCK(); \
178         for(cix = 0; cix < CVEC_LEN; ++cix) {
179             tc = &(tcv->cvec[cix]);
180             if (tc->activated)
181                 rx_DestroyConnection( tc->id );
182         }
183         if (glocked)
184             AFS_GLOCK();
185         afs_osi_Free(tcv, sizeof(struct sa_conn_vector));
186     }
187
188 }        /* release_conns_vector */
189
190
191 unsigned int VNOSERVERS = 0;
192
193 /**
194  * Pick a security object to use for a connection to a given server,
195  * by a given user
196  *
197  * @param[in] conn
198  *      The AFS connection for which the security object is required
199  * @param[out] secLevel
200  *      The security level of the returned object
201  *
202  * @return
203  *      An rx security object. This function is guaranteed to return
204  *      an object, although that object may be rxnull (with a secLevel
205  *      of 0)
206  */
207 static struct rx_securityClass *
208 afs_pickSecurityObject(struct afs_conn *conn, int *secLevel)
209 {
210     struct rx_securityClass *secObj = NULL;
211     union tokenUnion *token;
212
213     /* Do we have tokens ? */
214     if (conn->parent->user->states & UHasTokens) {
215         token = afs_FindToken(conn->parent->user->tokens, RX_SECIDX_KAD);
216         if (token) {
217             *secLevel = RX_SECIDX_KAD;
218             /* kerberos tickets on channel 2 */
219             secObj = rxkad_NewClientSecurityObject(
220                          cryptall ? rxkad_crypt : rxkad_clear,
221                          (struct ktc_encryptionKey *)
222                                token->rxkad.clearToken.HandShakeKey,
223                          token->rxkad.clearToken.AuthHandle,
224                          token->rxkad.ticketLen, token->rxkad.ticket);
225             /* We're going to use this token, so populate the viced */
226             conn->parent->user->viceId = token->rxkad.clearToken.ViceId;
227         }
228      }
229      if (secObj == NULL) {
230         *secLevel = 0;
231         secObj = rxnull_NewClientSecurityObject();
232      }
233
234      return secObj;
235 }
236
237
238 /**
239  * Try setting up a connection to the server containing the specified fid.
240  * Gets the volume, checks if it's up and does the connection by server address.
241  *
242  * @param afid
243  * @param areq Request filled in by the caller.
244  * @param locktype Type of lock that will be used.
245  *
246  * @return The conn struct, or NULL.
247  */
248 struct afs_conn *
249 afs_Conn(struct VenusFid *afid, struct vrequest *areq,
250          afs_int32 locktype)
251 {
252     u_short fsport = AFS_FSPORT;
253     struct volume *tv;
254     struct afs_conn *tconn = NULL;
255     struct srvAddr *lowp = NULL;
256     struct unixuser *tu;
257     int notbusy;
258     int i;
259     struct srvAddr *sa1p;
260
261     AFS_STATCNT(afs_Conn);
262     /* Get fid's volume. */
263     tv = afs_GetVolume(afid, areq, READ_LOCK);
264     if (!tv) {
265         if (areq) {
266             afs_FinalizeReq(areq);
267             areq->volumeError = 1;
268         }
269         return NULL;
270     }
271
272     if (tv->serverHost[0] && tv->serverHost[0]->cell) {
273         fsport = tv->serverHost[0]->cell->fsport;
274     } else {
275         VNOSERVERS++;
276     }
277
278     /* First is always lowest rank, if it's up */
279     if ((tv->status[0] == not_busy) && tv->serverHost[0]
280         && !(tv->serverHost[0]->addr->sa_flags & SRVR_ISDOWN) &&
281         !(((areq->idleError > 0) || (areq->tokenError > 0))
282           && (areq->skipserver[0] == 1)))
283         lowp = tv->serverHost[0]->addr;
284
285     /* Otherwise we look at all of them. There are seven levels of
286      * not_busy. This means we will check a volume seven times before it
287      * is marked offline. Ideally, we only need two levels, but this
288      * serves a second purpose of waiting some number of seconds before
289      * the client decides the volume is offline (ie: a clone could finish
290      * in this time).
291      */
292     for (notbusy = not_busy; (!lowp && (notbusy <= end_not_busy)); notbusy++) {
293         for (i = 0; i < AFS_MAXHOSTS && tv->serverHost[i]; i++) {
294             if (((areq->tokenError > 0)||(areq->idleError > 0))
295                 && (areq->skipserver[i] == 1))
296                 continue;
297             if (tv->status[i] != notbusy) {
298                 if (tv->status[i] == rd_busy || tv->status[i] == rdwr_busy) {
299                     if (!areq->busyCount)
300                         areq->busyCount++;
301                 } else if (tv->status[i] == offline) {
302                     if (!areq->volumeError)
303                         areq->volumeError = VOLMISSING;
304                 }
305                 continue;
306             }
307             for (sa1p = tv->serverHost[i]->addr; sa1p; sa1p = sa1p->next_sa) {
308                 if (sa1p->sa_flags & SRVR_ISDOWN)
309                     continue;
310                 if (!lowp || (lowp->sa_iprank > sa1p->sa_iprank))
311                     lowp = sa1p;
312             }
313         }
314     }
315     afs_PutVolume(tv, READ_LOCK);
316
317     if (lowp) {
318         tu = afs_GetUser(areq->uid, afid->Cell, SHARED_LOCK);
319         tconn = afs_ConnBySA(lowp, fsport, afid->Cell, tu, 0 /*!force */ ,
320                              1 /*create */ , locktype);
321
322         afs_PutUser(tu, SHARED_LOCK);
323     }
324
325     return tconn;
326 }                               /*afs_Conn */
327
328
329 /**
330  * Connects to a server by it's server address.
331  *
332  * @param sap Server address.
333  * @param aport Server port.
334  * @param acell
335  * @param tu Connect as this user.
336  * @param force_if_down
337  * @param create
338  * @param locktype Specifies type of lock to be used for this function.
339  *
340  * @return The new connection.
341  */
342 struct afs_conn *
343 afs_ConnBySA(struct srvAddr *sap, unsigned short aport, afs_int32 acell,
344              struct unixuser *tu, int force_if_down, afs_int32 create,
345              afs_int32 locktype)
346 {
347     int glocked, foundvec;
348     struct afs_conn *tc = NULL;
349     struct sa_conn_vector *tcv = NULL;
350     struct rx_securityClass *csec; /*Security class object */
351     int isec; /*Security index */
352     int service;
353
354     /* find cached connection */
355     ObtainSharedLock(&afs_xconn, 15);
356     foundvec = 0;
357     for (tcv = sap->conns; tcv; tcv = tcv->next) {
358         if (tcv->user == tu && tcv->port == aport) {
359             /* return most eligible conn */
360             if (!foundvec)
361                 foundvec = 1;
362             UpgradeSToWLock(&afs_xconn, 37);
363             tc = find_preferred_connection(tcv, create);
364             ConvertWToSLock(&afs_xconn);
365             break;
366         }
367     }
368
369     if (!tc && !create) {
370         /* Not found and can't create a new one. */
371         ReleaseSharedLock(&afs_xconn);
372         return NULL;
373     }
374
375     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
376         afs_warnuser("afs_ConnBySA: disconnected\n");
377         ReleaseSharedLock(&afs_xconn);
378         return NULL;
379     }
380
381     if (!foundvec && create) {
382         /* No such connection vector exists.  Create one and splice it in.
383          * Make sure the server record has been marked as used (for the purposes
384          * of calculating up & down times, it's now considered to be an
385          * ``active'' server).  Also make sure the server's lastUpdateEvalTime
386          * gets set, marking the time of its ``birth''.
387          */
388         UpgradeSToWLock(&afs_xconn, 37);
389         new_conn_vector(tcv);
390
391         tcv->user = tu;
392         tcv->port = aport;
393         tcv->srvr = sap;
394         tcv->next = sap->conns;
395         sap->conns = tcv;
396
397         /* all struct afs_conn ptrs come from here */
398         tc = find_preferred_connection(tcv, create);
399
400         afs_ActivateServer(sap);
401
402         ConvertWToSLock(&afs_xconn);
403     } /* end of if (!tcv) */
404
405     if (!tc) {
406         /* Not found and no alternatives. */
407         ReleaseSharedLock(&afs_xconn);
408         return NULL;
409     }
410
411     if (tu->states & UTokensBad) {
412         /* we may still have an authenticated RPC connection here,
413          * we'll have to create a new, unauthenticated, connection.
414          * Perhaps a better way to do this would be to set
415          * conn->forceConnectFS on all conns when the token first goes
416          * bad, but that's somewhat trickier, due to locking
417          * constraints (though not impossible).
418          */
419         if (tc->id && (rx_SecurityClassOf(tc->id) != 0)) {
420             tc->forceConnectFS = 1;     /* force recreation of connection */
421         }
422         tu->states &= ~UHasTokens;      /* remove the authentication info */
423     }
424
425     glocked = ISAFS_GLOCK();
426     if (tc->forceConnectFS) {
427         UpgradeSToWLock(&afs_xconn, 38);
428         csec = (struct rx_securityClass *)0;
429         if (tc->id) {
430             if (glocked)
431                 AFS_GUNLOCK();
432             rx_DestroyConnection(tc->id);
433             if (glocked)
434                 AFS_GLOCK();
435         }
436         /*
437          * Stupid hack to determine if using vldb service or file system
438          * service.
439          */
440         if (aport == sap->server->cell->vlport)
441             service = 52;
442         else
443             service = 1;
444         isec = 0;
445
446         csec = afs_pickSecurityObject(tc, &isec);
447
448         if (glocked)
449             AFS_GUNLOCK();
450         tc->id = rx_NewConnection(sap->sa_ip, aport, service, csec, isec);
451         if (glocked)
452             AFS_GLOCK();
453         if (service == 52) {
454             rx_SetConnHardDeadTime(tc->id, afs_rx_harddead);
455         }
456         /* set to a RX_CALL_TIMEOUT error to allow MTU retry to trigger */
457         rx_SetServerConnIdleDeadErr(tc->id, RX_CALL_DEAD);
458         rx_SetConnIdleDeadTime(tc->id, afs_rx_idledead);
459         rx_SetMsgsizeRetryErr(tc->id, RX_MSGSIZE);
460
461         /*
462          * Only do this for the base connection, not per-user.
463          * Will need to be revisited if/when CB gets security.
464          */
465         if ((isec == 0) && (service != 52) && !(tu->states & UTokensBad) &&
466             (tu->viceId == UNDEFVID))
467             rx_SetConnSecondsUntilNatPing(tc->id, 20);
468
469         tc->forceConnectFS = 0; /* apparently we're appropriately connected now */
470         if (csec)
471             rxs_Release(csec);
472         ConvertWToSLock(&afs_xconn);
473     } /* end of if (tc->forceConnectFS)*/
474
475     ReleaseSharedLock(&afs_xconn);
476     return tc;
477 }
478
479 /**
480  * forceConnectFS is set whenever we must recompute the connection. UTokensBad
481  * is true only if we know that the tokens are bad.  We thus clear this flag
482  * when we get a new set of tokens..
483  * Having force... true and UTokensBad true simultaneously means that the tokens
484  * went bad and we're supposed to create a new, unauthenticated, connection.
485  *
486  * @param aserver Server to connect to.
487  * @param aport Connection port.
488  * @param acell The cell where all of this happens.
489  * @param areq The request.
490  * @param aforce Force connection?
491  * @param locktype Type of lock to be used.
492  *
493  * @return The established connection.
494  */
495 struct afs_conn *
496 afs_ConnByHost(struct server *aserver, unsigned short aport, afs_int32 acell,
497                struct vrequest *areq, int aforce, afs_int32 locktype)
498 {
499     struct unixuser *tu;
500     struct afs_conn *tc = NULL;
501     struct srvAddr *sa = NULL;
502
503     AFS_STATCNT(afs_ConnByHost);
504
505     if (AFS_IS_DISCONNECTED && !AFS_IN_SYNC) {
506         afs_warnuser("afs_ConnByHost: disconnected\n");
507         return NULL;
508     }
509
510 /*
511   1.  look for an existing connection
512   2.  create a connection at an address believed to be up
513       (if aforce is true, create a connection at the first address)
514 */
515
516     tu = afs_GetUser(areq->uid, acell, SHARED_LOCK);
517
518     for (sa = aserver->addr; sa; sa = sa->next_sa) {
519         tc = afs_ConnBySA(sa, aport, acell, tu, aforce,
520                           0 /*don't create one */ ,
521                           locktype);
522         if (tc)
523             break;
524     }
525
526     if (!tc) {
527         for (sa = aserver->addr; sa; sa = sa->next_sa) {
528             tc = afs_ConnBySA(sa, aport, acell, tu, aforce,
529                               1 /*create one */ ,
530                               locktype);
531             if (tc)
532                 break;
533         }
534     }
535
536     afs_PutUser(tu, SHARED_LOCK);
537     return tc;
538
539 }                               /*afs_ConnByHost */
540
541
542 /**
543  * Connect by multiple hosts.
544  * Try to connect to one of the hosts from the ahosts array.
545  *
546  * @param ahosts Multiple hosts to connect to.
547  * @param aport Connection port.
548  * @param acell The cell where all of this happens.
549  * @param areq The request.
550  * @param locktype Type of lock to be used.
551  *
552  * @return The established connection or NULL.
553  */
554 struct afs_conn *
555 afs_ConnByMHosts(struct server *ahosts[], unsigned short aport,
556                  afs_int32 acell, struct vrequest *areq,
557                  afs_int32 locktype)
558 {
559     afs_int32 i;
560     struct afs_conn *tconn;
561     struct server *ts;
562
563     /* try to find any connection from the set */
564     AFS_STATCNT(afs_ConnByMHosts);
565     for (i = 0; i < AFS_MAXCELLHOSTS; i++) {
566         if ((ts = ahosts[i]) == NULL)
567             break;
568         tconn = afs_ConnByHost(ts, aport, acell, areq, 0, locktype);
569         if (tconn) {
570             return tconn;
571         }
572     }
573     return NULL;
574
575 }                               /*afs_ConnByMHosts */
576
577
578 /**
579  * Decrement reference count to this connection.
580  * @param ac
581  * @param locktype
582  */
583 void
584 afs_PutConn(struct afs_conn *ac, afs_int32 locktype)
585 {
586     AFS_STATCNT(afs_PutConn);
587     ac->refCount--;
588     ac->parent->refCount--;
589 }                               /*afs_PutConn */
590
591
592 /**
593  * Free up a connection vector, allowing, eg, code in afs_user.c
594  * to ignore how connections are stored/pooled
595  * @param tcv
596  */
597 void
598 afs_ReleaseConns(struct sa_conn_vector *tcv) {
599     release_conns_vector(tcv);
600 }
601
602
603 /**
604  * Free connection vector(s) for a user
605  * @param au
606  */
607 void
608 afs_ReleaseConnsUser(struct unixuser *au) {
609
610     int i;
611     struct server *ts;
612
613     for (i = 0; i < NSERVERS; i++) {
614         for (ts = afs_servers[i]; ts; ts = ts->next) {
615             release_conns_user_server(au, ts);
616         }       /*For each server on chain */
617     } /*For each chain */
618 }
619
620
621 /**
622  * For multi homed clients, a RPC may timeout because of a
623  * client network interface going down. We need to reopen new
624  * connections in this case.
625  *
626  * @param sap Server address.
627  */
628 void
629 ForceNewConnections(struct srvAddr *sap)
630 {
631     int cix;
632     struct afs_conn *tc = NULL;
633     struct sa_conn_vector *tcv = NULL;
634
635     if (!sap)
636         return; /* defensive check */
637
638     ObtainWriteLock(&afs_xconn, 413);
639     for (tcv = sap->conns; tcv; tcv = tcv->next) {
640         for(cix = 0; cix < CVEC_LEN; ++cix) {
641             tc = &(tcv->cvec[cix]);
642             if (tc->activated)
643                 tc->forceConnectFS = 1;
644         }
645     }
646     ReleaseWriteLock(&afs_xconn);
647 }
648
649