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