Handle more RPC service names
[openafs.git] / src / WINNT / afsd / cm_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 #include <afs/param.h>
11 #include <afs/stds.h>
12
13 #include <windows.h>
14 #include <string.h>
15 #include <malloc.h>
16 #include <osi.h>
17 #include "afsd.h"
18 #include <rx/rx.h>
19 #include <rx/rxkad.h>
20 #include <afs/unified_afs.h>
21 #include <afs/vlserver.h>
22 #include <WINNT/afsreg.h>
23
24 osi_rwlock_t cm_connLock;
25
26 DWORD RDRtimeout = CM_CONN_DEFAULTRDRTIMEOUT;
27 unsigned short ConnDeadtimeout = CM_CONN_CONNDEADTIME;
28 unsigned short HardDeadtimeout = CM_CONN_HARDDEADTIME;
29 unsigned short IdleDeadtimeout = CM_CONN_IDLEDEADTIME;
30
31 #define LANMAN_WKS_PARAM_KEY "SYSTEM\\CurrentControlSet\\Services\\lanmanworkstation\\parameters"
32 #define LANMAN_WKS_SESSION_TIMEOUT "SessTimeout"
33 #define LANMAN_WKS_EXT_SESSION_TIMEOUT "ExtendedSessTimeout"
34
35 afs_uint32 cryptall = 0;
36 afs_uint32 cm_anonvldb = 0;
37
38 void cm_PutConn(cm_conn_t *connp)
39 {
40     afs_int32 refCount = InterlockedDecrement(&connp->refCount);
41     osi_assertx(refCount >= 0, "cm_conn_t refcount underflow");
42 }
43
44 void cm_InitConn(void)
45 {
46     static osi_once_t once;
47     long code;
48     DWORD dwValue;
49     DWORD dummyLen;
50     HKEY parmKey;
51         
52     if (osi_Once(&once)) {
53         lock_InitializeRWLock(&cm_connLock, "connection global lock",
54                                LOCK_HIERARCHY_CONN_GLOBAL);
55
56         /* keisa - read timeout value for lanmanworkstation  service.
57          * jaltman - as per 
58          *   http://support.microsoft.com:80/support/kb/articles/Q102/0/67.asp&NoWebContent=1
59          * the SessTimeout is a minimum timeout not a maximum timeout.  Therefore, 
60          * I believe that the default should not be short.  Instead, we should wait until
61          * RX times out before reporting a timeout to the SMB client.
62          */
63         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LANMAN_WKS_PARAM_KEY,
64                             0, KEY_QUERY_VALUE, &parmKey);
65         if (code == ERROR_SUCCESS)
66         {
67             BOOL extTimeouts = msftSMBRedirectorSupportsExtendedTimeouts();
68
69             if (extTimeouts) {
70                 /* 
71                  * The default value is 1000 seconds.  However, this default
72                  * will not apply to "\\AFS" unless "AFS" is listed in 
73                  * ServersWithExtendedSessTimeout which we will add when we
74                  * create the ExtendedSessTimeout value in smb_Init()
75                  */
76                 dummyLen = sizeof(DWORD);
77                 code = RegQueryValueEx(parmKey, 
78                                        LANMAN_WKS_EXT_SESSION_TIMEOUT,
79                                         NULL, NULL,
80                                         (BYTE *) &dwValue, &dummyLen);
81                 if (code == ERROR_SUCCESS) {
82                     RDRtimeout = dwValue;
83                     afsi_log("lanmanworkstation : ExtSessTimeout %u", RDRtimeout);
84                 }
85             } 
86             if (!extTimeouts || code != ERROR_SUCCESS) {
87                 dummyLen = sizeof(DWORD);
88                 code = RegQueryValueEx(parmKey, 
89                                        LANMAN_WKS_SESSION_TIMEOUT,
90                                        NULL, NULL,
91                                        (BYTE *) &dwValue, &dummyLen);
92                 if (code == ERROR_SUCCESS) {
93                     RDRtimeout = dwValue;
94                     afsi_log("lanmanworkstation : SessTimeout %u", RDRtimeout);
95                 }
96             }
97             RegCloseKey(parmKey);
98         }
99
100         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
101                              0, KEY_QUERY_VALUE, &parmKey);
102         if (code == ERROR_SUCCESS) {
103             dummyLen = sizeof(DWORD);
104             code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
105                                     (BYTE *) &dwValue, &dummyLen);
106             if (code == ERROR_SUCCESS) {
107                 ConnDeadtimeout = (unsigned short)dwValue;
108                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
109             }
110             dummyLen = sizeof(DWORD);
111             code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
112                                     (BYTE *) &dwValue, &dummyLen);
113             if (code == ERROR_SUCCESS) {
114                 HardDeadtimeout = (unsigned short)dwValue;
115                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
116             }
117             dummyLen = sizeof(DWORD);
118             code = RegQueryValueEx(parmKey, "IdleDeadTimeout", NULL, NULL,
119                                     (BYTE *) &dwValue, &dummyLen);
120             if (code == ERROR_SUCCESS) {
121                 IdleDeadtimeout = (unsigned short)dwValue;
122                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
123             }
124             RegCloseKey(parmKey);
125         }
126
127         /* 
128          * If these values were not set via cpp macro or obtained 
129          * from the registry, we use a value that is derived from
130          * the smb redirector session timeout (RDRtimeout).
131          *
132          * The UNIX cache manager uses 120 seconds for the hard dead
133          * timeout and 50 seconds for the connection and idle timeouts.
134          *
135          * We base our values on those while making sure we leave 
136          * enough time for overhead.  
137          */
138         if (ConnDeadtimeout == 0) {
139             ConnDeadtimeout = (unsigned short) ((RDRtimeout / 2) < 50 ? (RDRtimeout / 2) : 50);
140             afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
141         }
142         if (HardDeadtimeout == 0) {
143             HardDeadtimeout = (unsigned short) (RDRtimeout > 125 ? 120 : (RDRtimeout - 5));
144             afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
145         }
146         if (IdleDeadtimeout == 0) {
147             IdleDeadtimeout = (unsigned short) ConnDeadtimeout;
148             afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
149         }
150         osi_EndOnce(&once);
151     }
152 }
153
154 void cm_InitReq(cm_req_t *reqp)
155 {
156         memset((char *)reqp, 0, sizeof(cm_req_t));
157         reqp->startTime = GetTickCount();
158 }
159
160 static long cm_GetServerList(struct cm_fid *fidp, struct cm_user *userp,
161         struct cm_req *reqp, cm_serverRef_t ***serversppp)
162 {
163     long code;
164     cm_volume_t *volp = NULL;
165     cm_cell_t *cellp = NULL;
166
167     if (!fidp) {
168         *serversppp = NULL;
169         return CM_ERROR_INVAL;
170     }
171
172     cellp = cm_FindCellByID(fidp->cell, 0);
173     if (!cellp) 
174         return CM_ERROR_NOSUCHCELL;
175
176     code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, CM_GETVOL_FLAG_CREATE, &volp);
177     if (code) 
178         return code;
179     
180     *serversppp = cm_GetVolServers(volp, fidp->volume, userp, reqp);
181
182     lock_ObtainRead(&cm_volumeLock);
183     cm_PutVolume(volp);
184     lock_ReleaseRead(&cm_volumeLock);
185     return (*serversppp ? 0 : CM_ERROR_NOSUCHVOLUME);
186 }
187
188 /*
189  * Analyze the error return from an RPC.  Determine whether or not to retry,
190  * and if we're going to retry, determine whether failover is appropriate,
191  * and whether timed backoff is appropriate.
192  *
193  * If the error code is from cm_ConnFromFID() or friends, it will be a CM_ERROR code.
194  * Otherwise it will be an RPC code.  This may be a UNIX code (e.g. EDQUOT), or
195  * it may be an RX code, or it may be a special code (e.g. VNOVOL), or it may
196  * be a security code (e.g. RXKADEXPIRED).
197  *
198  * If the error code is from cm_ConnFromFID() or friends, connp will be NULL.
199  *
200  * For VLDB calls, fidp will be NULL.
201  *
202  * volSyncp and/or cbrp may also be NULL.
203  */
204 int
205 cm_Analyze(cm_conn_t *connp, cm_user_t *userp, cm_req_t *reqp,
206            struct cm_fid *fidp, 
207            AFSVolSync *volSyncp, 
208            cm_serverRef_t * serversp,
209            cm_callbackRequest_t *cbrp, long errorCode)
210 {
211     cm_server_t *serverp = NULL;
212     cm_serverRef_t **serverspp = NULL;
213     cm_serverRef_t *tsrp;
214     cm_cell_t  *cellp = NULL;
215     cm_ucell_t *ucellp;
216     cm_volume_t * volp = NULL;
217     cm_vol_state_t *statep = NULL;
218     int retry = 0;
219     int free_svr_list = 0;
220     int dead_session;
221     long timeUsed, timeLeft;
222     long code;
223     char addr[16]="unknown";
224     int forcing_new = 0;
225
226     osi_Log2(afsd_logp, "cm_Analyze connp 0x%p, code 0x%x",
227              connp, errorCode);
228
229     /* no locking required, since connp->serverp never changes after
230      * creation */
231     dead_session = (userp->cellInfop == NULL);
232     if (connp)
233         serverp = connp->serverp;
234
235     /* Update callback pointer */
236     if (cbrp && serverp && errorCode == 0) {
237         if (cbrp->serverp) {
238             if ( cbrp->serverp != serverp ) {
239                 lock_ObtainWrite(&cm_serverLock);
240                 cm_PutServerNoLock(cbrp->serverp);
241                 cm_GetServerNoLock(serverp);
242                 lock_ReleaseWrite(&cm_serverLock);
243             }
244         } else {
245             cm_GetServer(serverp);
246         }
247         lock_ObtainWrite(&cm_callbackLock);
248         cbrp->serverp = serverp;
249         lock_ReleaseWrite(&cm_callbackLock);
250     }
251
252     /* if timeout - check that it did not exceed the HardDead timeout
253      * and retry */
254     
255     /* timeleft - get if from reqp the same way as cmXonnByMServers does */
256     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
257             
258     /* leave 5 seconds margin for sleep */
259     if (reqp->flags & CM_REQ_NORETRY)
260         timeLeft = 0;
261     else
262         timeLeft = HardDeadtimeout - timeUsed;
263
264     /* get a pointer to the cell */
265     if (errorCode) {
266         if (cellp == NULL && serverp)
267             cellp = serverp->cellp;
268         if (cellp == NULL && serversp) {
269             struct cm_serverRef * refp;
270             for ( refp=serversp ; cellp == NULL && refp != NULL; refp=refp->next) {
271                 if (refp->status == srv_deleted)
272                     continue;
273                 if ( refp->server )
274                     cellp = refp->server->cellp;
275             }
276         } 
277         if (cellp == NULL && fidp) {
278             cellp = cm_FindCellByID(fidp->cell, 0);
279         }
280     }
281
282     if (errorCode == CM_ERROR_TIMEDOUT) {
283         if ( timeLeft > 5 ) {
284             thrd_Sleep(3000);
285             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, cellp);
286             retry = 1;
287         }
288     }
289
290     else if (errorCode == UAEWOULDBLOCK || errorCode == EWOULDBLOCK ||
291               errorCode == UAEAGAIN || errorCode == EAGAIN) {
292         osi_Log0(afsd_logp, "cm_Analyze passed EWOULDBLOCK or EAGAIN.");
293         if ( timeLeft > 5 ) {
294             thrd_Sleep(1000);
295             retry = 1;
296         }
297     }
298
299     /* if there is nosuchvolume, then we have a situation in which a 
300      * previously known volume no longer has a set of servers 
301      * associated with it.  Either the volume has moved or
302      * the volume has been deleted.  Try to find a new server list
303      * until the timeout period expires.
304      */
305     else if (errorCode == CM_ERROR_NOSUCHVOLUME) {
306         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_NOSUCHVOLUME.");
307         /* 
308          * The VNOVOL or VL_NOENT error has already been translated
309          * to CM_ERROR_NOSUCHVOLUME.  There is nothing for us to do.
310          */
311     }
312
313     else if (errorCode == CM_ERROR_ALLDOWN) {
314         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLDOWN.");
315         /* Servers marked DOWN will be restored by the background daemon
316          * thread as they become available.  The volume status is 
317          * updated as the server state changes.
318          */
319     }
320
321     else if (errorCode == CM_ERROR_ALLOFFLINE) {
322         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE.");
323         /* Volume instances marked offline will be restored by the 
324          * background daemon thread as they become available 
325          */
326         if (fidp) {
327             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, 
328                                       CM_GETVOL_FLAG_NO_LRU_UPDATE, 
329                                       &volp);
330             if (code == 0) {
331                 if (timeLeft > 7) {
332                     thrd_Sleep(5000);
333
334                     /* cm_CheckOfflineVolume() resets the serverRef state */
335                     if (cm_CheckOfflineVolume(volp, fidp->volume))
336                         retry = 1;
337                 } else {
338                     cm_UpdateVolumeStatus(volp, fidp->volume);
339                 }
340                 lock_ObtainRead(&cm_volumeLock);
341                 cm_PutVolume(volp);
342                 lock_ReleaseRead(&cm_volumeLock);
343                 volp = NULL;
344             }
345         } 
346     }
347     else if (errorCode == CM_ERROR_ALLBUSY) {
348         /* Volumes that are busy cannot be determined to be non-busy 
349          * without actually attempting to access them.
350          */
351         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY.");
352
353         if (fidp) { /* File Server query */
354             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, 
355                                      CM_GETVOL_FLAG_NO_LRU_UPDATE, 
356                                      &volp);
357             if (code == 0) {
358                 if (timeLeft > 7) {
359                     thrd_Sleep(5000);
360                     
361                     statep = cm_VolumeStateByID(volp, fidp->volume);
362                     if (statep->state != vl_offline && 
363                          statep->state != vl_busy &&
364                          statep->state != vl_unknown) {
365                         retry = 1;
366                     } else {
367                         if (!serversp) {
368                             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
369                             if (code == 0) {
370                                 serversp = *serverspp;
371                                 free_svr_list = 1;
372                             }
373                         }
374                         lock_ObtainWrite(&cm_serverLock);
375                         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
376                             if (tsrp->status == srv_deleted)
377                                 continue;
378                             if (tsrp->status == srv_busy) {
379                                 tsrp->status = srv_not_busy;
380                             }       
381                         }
382                         lock_ReleaseWrite(&cm_serverLock);
383                         if (free_svr_list) {
384                             cm_FreeServerList(serverspp, 0);
385                             serverspp = NULL;
386                             serversp = NULL;
387                             free_svr_list = 0;
388                         }
389
390                         cm_UpdateVolumeStatus(volp, fidp->volume);
391                         retry = 1;
392                     }
393                 } else {
394                     cm_UpdateVolumeStatus(volp, fidp->volume);
395                 }
396
397                 lock_ObtainRead(&cm_volumeLock);
398                 cm_PutVolume(volp);
399                 lock_ReleaseRead(&cm_volumeLock);
400                 volp = NULL;
401             }
402         } else {    /* VL Server query */
403             if (timeLeft > 7) {
404                 thrd_Sleep(5000);
405
406                 if (serversp) {
407                     lock_ObtainWrite(&cm_serverLock);
408                     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
409                         if (tsrp->status == srv_deleted)
410                             continue;
411                         if (tsrp->status == srv_busy) {
412                             tsrp->status = srv_not_busy;
413                         }
414                     }
415                     lock_ReleaseWrite(&cm_serverLock);
416                     retry = 1;
417                 }
418             }
419         }
420     }
421
422     /* special codes:  VBUSY and VRESTARTING */
423     else if (errorCode == VBUSY || errorCode == VRESTARTING) {
424         if (!serversp && fidp) {
425             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
426             if (code == 0) {
427                 serversp = *serverspp;
428                 free_svr_list = 1;
429             }
430         }
431         lock_ObtainWrite(&cm_serverLock);
432         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
433             if (tsrp->status == srv_deleted)
434                 continue;
435             if (tsrp->server == serverp && tsrp->status == srv_not_busy) {
436                 tsrp->status = srv_busy;
437                 if (fidp) { /* File Server query */
438                     lock_ReleaseWrite(&cm_serverLock);
439                     code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, 
440                                              CM_GETVOL_FLAG_NO_LRU_UPDATE, 
441                                              &volp);
442                     if (code == 0)
443                         statep = cm_VolumeStateByID(volp, fidp->volume);
444                     lock_ObtainWrite(&cm_serverLock);
445                 }
446                 break;
447             }
448         }
449         lock_ReleaseWrite(&cm_serverLock);
450         
451         if (statep) {
452             cm_UpdateVolumeStatus(volp, statep->ID);
453             lock_ObtainRead(&cm_volumeLock);
454             cm_PutVolume(volp);
455             lock_ReleaseRead(&cm_volumeLock);
456             volp = NULL;
457         }
458
459         if (free_svr_list) {
460             cm_FreeServerList(serverspp, 0);
461             serverspp = NULL;
462             serversp = NULL;
463             free_svr_list = 0;
464         }
465         retry = 1;
466     }
467
468     /* special codes:  missing volumes */
469     else if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE ||
470              errorCode == VSALVAGE || errorCode == VNOSERVICE || errorCode == VIO) 
471     {       
472         char addr[16];
473         char *format;
474         DWORD msgID;
475
476         /* In case of timeout */
477         reqp->volumeError = errorCode;
478
479         switch ( errorCode ) {
480         case VNOVOL:
481             msgID = MSG_SERVER_REPORTS_VNOVOL;
482             format = "Server %s reported volume %d as not attached (does not exist).";
483             break;
484         case VMOVED:
485             msgID = MSG_SERVER_REPORTS_VMOVED;
486             format = "Server %s reported volume %d as moved.";
487             break;
488         case VOFFLINE:
489             msgID = MSG_SERVER_REPORTS_VOFFLINE;
490             format = "Server %s reported volume %d as offline.";
491             break;
492         case VSALVAGE:
493             msgID = MSG_SERVER_REPORTS_VSALVAGE;
494             format = "Server %s reported volume %d as needs salvage.";
495             break;
496         case VNOSERVICE:
497             msgID = MSG_SERVER_REPORTS_VNOSERVICE;
498             format = "Server %s reported volume %d as not in service.";
499             break;
500         case VIO:
501             msgID = MSG_SERVER_REPORTS_VIO;
502             format = "Server %s reported volume %d as temporarily unaccessible.";
503             break;
504         }
505
506         if (serverp && fidp) {
507             /* Log server being offline for this volume */
508             sprintf(addr, "%d.%d.%d.%d", 
509                    ((serverp->addr.sin_addr.s_addr & 0xff)),
510                    ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
511                    ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
512                    ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
513
514             osi_Log2(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume);
515             LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume);
516         }
517
518         /* 
519          * Mark server offline for this volume or delete the volume
520          * from the server list if it was moved or is not present.
521          */
522         if (!serversp && fidp) {
523             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
524             if (code == 0) {
525                 serversp = *serverspp;
526                 free_svr_list = 1;
527             }
528         }
529
530         lock_ObtainWrite(&cm_serverLock);
531         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
532             if (tsrp->status == srv_deleted)
533                 continue;
534
535             sprintf(addr, "%d.%d.%d.%d",
536                      ((tsrp->server->addr.sin_addr.s_addr & 0xff)),
537                      ((tsrp->server->addr.sin_addr.s_addr & 0xff00)>> 8),
538                      ((tsrp->server->addr.sin_addr.s_addr & 0xff0000)>> 16),
539                      ((tsrp->server->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
540
541             if (tsrp->server == serverp) {
542                 /* REDIRECT */
543                 if (errorCode == VMOVED || errorCode == VNOVOL) {
544                     osi_Log2(afsd_logp, "volume %d not present on server %s", 
545                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
546                     tsrp->status = srv_deleted;
547                     if (fidp)
548                         cm_RemoveVolumeFromServer(serverp, fidp->volume);
549                 } else {
550                     osi_Log2(afsd_logp, "volume %d instance on server %s marked offline", 
551                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
552                     tsrp->status = srv_offline;
553                 }
554                 /* break; */
555             } else {
556                 osi_Log3(afsd_logp, "volume %d exists on server %s with status %u", 
557                          fidp->volume, osi_LogSaveString(afsd_logp,addr), tsrp->status);
558             }
559         }   
560         lock_ReleaseWrite(&cm_serverLock);
561
562         /* Free the server list before cm_ForceUpdateVolume is called */
563         if (free_svr_list) {
564             cm_FreeServerList(serverspp, 0);
565             serverspp = NULL;
566             serversp = NULL;
567             free_svr_list = 0;
568         }
569
570         if (fidp) { /* File Server query */
571             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, 
572                                       CM_GETVOL_FLAG_NO_LRU_UPDATE, 
573                                       &volp);
574             if (code == 0)
575                 statep = cm_VolumeStateByID(volp, fidp->volume);
576
577             if ((errorCode == VMOVED || errorCode == VNOVOL) &&
578                 !(reqp->flags & CM_REQ_VOLUME_UPDATED)) 
579             {
580                 code = cm_ForceUpdateVolume(fidp, userp, reqp);
581                 if (code) 
582                     timeLeft = 0;   /* prevent a retry on failure */
583                 else
584                     reqp->flags |= CM_REQ_VOLUME_UPDATED;
585                 osi_Log3(afsd_logp, "cm_Analyze called cm_ForceUpdateVolume cell %u vol %u code 0x%x",
586                         fidp->cell, fidp->volume, code);
587             }
588
589             if (statep) {
590                 cm_UpdateVolumeStatus(volp, statep->ID);
591                 osi_Log3(afsd_logp, "cm_Analyze NewVolState cell %u vol %u state %u", 
592                          fidp->cell, fidp->volume, statep->state);
593             }
594
595             if (volp) {
596                 lock_ObtainRead(&cm_volumeLock);
597                 cm_PutVolume(volp);
598                 lock_ReleaseRead(&cm_volumeLock);
599                 volp = NULL;
600             }
601         }
602
603         if ( timeLeft > 2 )
604             retry = 1;
605     } else if ( errorCode == VNOVNODE ) {
606         if ( fidp ) {
607             cm_scache_t * scp;
608             osi_Log4(afsd_logp, "cm_Analyze passed VNOVNODE cell %u vol %u vn %u uniq %u.",
609                       fidp->cell, fidp->volume, fidp->vnode, fidp->unique);
610
611             scp = cm_FindSCache(fidp);
612             if (scp) {
613                 cm_scache_t *pscp = NULL;
614
615                 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
616                     pscp = cm_FindSCacheParent(scp);
617
618                 lock_ObtainWrite(&scp->rw);
619                 lock_ObtainWrite(&cm_scacheLock);
620                 cm_RemoveSCacheFromHashTable(scp);
621                 lock_ReleaseWrite(&cm_scacheLock);
622                 cm_LockMarkSCacheLost(scp);
623                 scp->flags |= CM_SCACHEFLAG_DELETED;
624                 lock_ReleaseWrite(&scp->rw);
625                 cm_ReleaseSCache(scp);
626
627                 if (pscp) {
628                     if (cm_HaveCallback(pscp)) {
629                         lock_ObtainWrite(&pscp->rw);
630                         cm_DiscardSCache(pscp);
631                         lock_ReleaseWrite(&pscp->rw);
632                     }
633                     cm_ReleaseSCache(pscp);
634                 }
635             }
636         } else {
637             osi_Log0(afsd_logp, "cm_Analyze passed VNOVNODE unknown fid.");
638         }
639     }
640
641     /* RX codes */
642     else if (errorCode == RX_CALL_TIMEOUT) {
643         /* RPC took longer than hardDeadTime or the server
644          * reported idle for longer than idleDeadTime
645          * don't mark server as down but don't retry
646          * this is to prevent the SMB session from timing out
647          * In addition, we log an event to the event log 
648          */
649
650         if (serverp) {
651             sprintf(addr, "%d.%d.%d.%d", 
652                     ((serverp->addr.sin_addr.s_addr & 0xff)),
653                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
654                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
655                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
656
657             LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_HARD_DEAD_TIME_EXCEEDED, addr);
658             osi_Log1(afsd_logp, "cm_Analyze: hardDeadTime or idleDeadtime exceeded addr[%s]",
659                      osi_LogSaveString(afsd_logp,addr));
660             reqp->tokenIdleErrorServp = serverp;
661             reqp->idleError++;
662
663             if (timeLeft > 2) {
664                 if (!fidp) { /* vldb */
665                     retry = 1;
666                 } else { /* file */
667                     cm_volume_t *volp = cm_GetVolumeByFID(fidp);
668                     if (volp) {
669                         if (fidp->volume == cm_GetROVolumeID(volp))
670                             retry = 1;
671                         cm_PutVolume(volp);
672                     }
673                 }
674             }
675         }
676     }
677     else if (errorCode >= -64 && errorCode < 0) {
678         /* mark server as down */
679         sprintf(addr, "%d.%d.%d.%d", 
680                 ((serverp->addr.sin_addr.s_addr & 0xff)),
681                 ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
682                 ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
683                 ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
684
685         if (errorCode == RX_CALL_DEAD)
686             osi_Log2(afsd_logp, "cm_Analyze: Rx Call Dead addr[%s] forcedNew[%s]",
687                      osi_LogSaveString(afsd_logp,addr), 
688                      (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
689         else
690             osi_Log3(afsd_logp, "cm_Analyze: Rx Misc Error[%d] addr[%s] forcedNew[%s]",
691                      errorCode,
692                      osi_LogSaveString(afsd_logp,addr), 
693                      (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
694
695         lock_ObtainMutex(&serverp->mx);
696         if (errorCode != RX_CALL_DEAD || 
697             (reqp->flags & CM_REQ_NEW_CONN_FORCED)) {
698             if (!(serverp->flags & CM_SERVERFLAG_DOWN)) {
699                 serverp->flags |= CM_SERVERFLAG_DOWN;
700                 serverp->downTime = time(NULL);
701             }
702         } else {
703             reqp->flags |= CM_REQ_NEW_CONN_FORCED;
704             forcing_new = 1;
705         }
706         lock_ReleaseMutex(&serverp->mx);
707         cm_ForceNewConnections(serverp);
708         if ( timeLeft > 2 )
709             retry = 1;
710     }
711     else if (errorCode == RXKADEXPIRED) {
712         if (!dead_session) {
713             lock_ObtainMutex(&userp->mx);
714             ucellp = cm_GetUCell(userp, serverp->cellp);
715             if (ucellp->ticketp) {
716                 free(ucellp->ticketp);
717                 ucellp->ticketp = NULL;
718             }
719             ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
720             ucellp->gen++;
721             lock_ReleaseMutex(&userp->mx);
722             if ( timeLeft > 2 )
723                 retry = 1;
724         }
725     } else if (errorCode >= ERROR_TABLE_BASE_RXK && errorCode < ERROR_TABLE_BASE_RXK + 256) {
726         if (serverp) {
727         reqp->tokenIdleErrorServp = serverp;
728         reqp->tokenError = errorCode;
729         retry = 1;
730         }
731     } else if (errorCode >= ERROR_TABLE_BASE_U && errorCode < ERROR_TABLE_BASE_U + 256) {
732         /*
733          * We received a ubik error.  its possible that the server we are
734          * communicating with has a corrupted database or is partitioned
735          * from the rest of the servers and another server might be able
736          * to answer our query.  Therefore, we will retry the request
737          * and force the use of another server.
738          */
739         if (serverp) {
740             reqp->tokenIdleErrorServp = serverp;
741             reqp->tokenError = errorCode;
742             retry = 1;
743         }
744     } else if (errorCode == VICECONNBAD || errorCode == VICETOKENDEAD) {
745         cm_ForceNewConnections(serverp);
746         if ( timeLeft > 2 )
747             retry = 1;
748     } else {
749         if (errorCode) {
750             char * s = "unknown error";
751             switch ( errorCode ) {
752             case RXKADINCONSISTENCY: s = "RXKADINCONSISTENCY"; break;
753             case RXKADPACKETSHORT  : s = "RXKADPACKETSHORT";   break;
754             case RXKADLEVELFAIL    : s = "RXKADLEVELFAIL";     break;
755             case RXKADTICKETLEN    : s = "RXKADTICKETLEN";     break;
756             case RXKADOUTOFSEQUENCE: s = "RXKADOUTOFSEQUENCE"; break;
757             case RXKADNOAUTH       : s = "RXKADNOAUTH";        break;
758             case RXKADBADKEY       : s = "RXKADBADKEY";        break;
759             case RXKADBADTICKET    : s = "RXKADBADTICKET";     break;
760             case RXKADUNKNOWNKEY   : s = "RXKADUNKNOWNKEY";    break;
761             case RXKADEXPIRED      : s = "RXKADEXPIRED";       break;
762             case RXKADSEALEDINCON  : s = "RXKADSEALEDINCON";   break;
763             case RXKADDATALEN      : s = "RXKADDATALEN";       break;
764             case RXKADILLEGALLEVEL : s = "RXKADILLEGALLEVEL";  break;
765             case VSALVAGE          : s = "VSALVAGE";           break;
766             case VNOVNODE          : s = "VNOVNODE";           break;
767             case VNOVOL            : s = "VNOVOL";             break;
768             case VVOLEXISTS        : s = "VVOLEXISTS";         break;
769             case VNOSERVICE        : s = "VNOSERVICE";         break;
770             case VOFFLINE          : s = "VOFFLINE";           break;
771             case VONLINE           : s = "VONLINE";            break;
772             case VDISKFULL         : s = "VDISKFULL";          break;
773             case VOVERQUOTA        : s = "VOVERQUOTA";         break;
774             case VBUSY             : s = "VBUSY";              break;
775             case VMOVED            : s = "VMOVED";             break;
776             case VIO               : s = "VIO";                break;
777             case VRESTRICTED       : s = "VRESTRICTED";        break;
778             case VRESTARTING       : s = "VRESTARTING";        break;
779             case VREADONLY         : s = "VREADONLY";          break;
780             case EAGAIN            : s = "EAGAIN";             break;
781             case UAEAGAIN          : s = "UAEAGAIN";           break;
782             case EINVAL            : s = "EINVAL";             break;
783             case UAEINVAL          : s = "UAEINVAL";           break;
784             case EACCES            : s = "EACCES";             break;
785             case UAEACCES          : s = "UAEACCES";           break;
786             case ENOENT            : s = "ENOENT";             break;
787             case UAENOENT          : s = "UAENOENT";           break;
788             case EEXIST            : s = "EEXIST";             break;
789             case UAEEXIST          : s = "UAEEXIST";           break;
790             case VICECONNBAD       : s = "VICECONNBAD";        break;
791             case VICETOKENDEAD     : s = "VICETOKENDEAD";      break;
792             case WSAEWOULDBLOCK    : s = "WSAEWOULDBLOCK";     break;
793             case UAEWOULDBLOCK     : s = "UAEWOULDBLOCK";      break;
794             case VL_IDEXIST        : s = "VL_IDEXIST";         break;
795             case VL_IO             : s = "VL_IO";              break;
796             case VL_NAMEEXIST      : s = "VL_NAMEEXIST";       break;
797             case VL_CREATEFAIL     : s = "VL_CREATEFAIL";      break;
798             case VL_NOENT          : s = "VL_NOENT";           break;
799             case VL_EMPTY          : s = "VL_EMPTY";           break;
800             case VL_ENTDELETED     : s = "VL_ENTDELETED";      break;
801             case VL_BADNAME        : s = "VL_BADNAME";         break;
802             case VL_BADINDEX       : s = "VL_BADINDEX";        break;
803             case VL_BADVOLTYPE     : s = "VL_BADVOLTYPE";      break;
804             case VL_BADSERVER      : s = "VL_BADSERVER";       break;
805             case VL_BADPARTITION   : s = "VL_BADPARTITION";    break;
806             case VL_REPSFULL       : s = "VL_REPSFULL";        break;
807             case VL_NOREPSERVER    : s = "VL_NOREPSERVER";     break;
808             case VL_DUPREPSERVER   : s = "VL_DUPREPSERVER";    break;
809             case VL_RWNOTFOUND     : s = "VL_RWNOTFOUND";      break;
810             case VL_BADREFCOUNT    : s = "VL_BADREFCOUNT";     break;
811             case VL_SIZEEXCEEDED   : s = "VL_SIZEEXCEEDED";    break;
812             case VL_BADENTRY       : s = "VL_BADENTRY";        break;
813             case VL_BADVOLIDBUMP   : s = "VL_BADVOLIDBUMP";    break;
814             case VL_IDALREADYHASHED: s = "VL_IDALREADYHASHED"; break;
815             case VL_ENTRYLOCKED    : s = "VL_ENTRYLOCKED";     break;
816             case VL_BADVOLOPER     : s = "VL_BADVOLOPER";      break;
817             case VL_BADRELLOCKTYPE : s = "VL_BADRELLOCKTYPE";  break;
818             case VL_RERELEASE      : s = "VL_RERELEASE";       break;
819             case VL_BADSERVERFLAG  : s = "VL_BADSERVERFLAG";   break;
820             case VL_PERM           : s = "VL_PERM";            break;
821             case VL_NOMEM          : s = "VL_NOMEM";           break;
822             case VL_BADVERSION     : s = "VL_BADVERSION";      break;
823             case VL_INDEXERANGE    : s = "VL_INDEXERANGE";     break;
824             case VL_MULTIPADDR     : s = "VL_MULTIPADDR";      break;
825             case VL_BADMASK        : s = "VL_BADMASK";         break;
826             case CM_ERROR_NOSUCHCELL        : s = "CM_ERROR_NOSUCHCELL";         break;                         
827             case CM_ERROR_NOSUCHVOLUME      : s = "CM_ERROR_NOSUCHVOLUME";       break;                         
828             case CM_ERROR_TIMEDOUT          : s = "CM_ERROR_TIMEDOUT";           break;                 
829             case CM_ERROR_RETRY             : s = "CM_ERROR_RETRY";              break; 
830             case CM_ERROR_NOACCESS          : s = "CM_ERROR_NOACCESS";           break; 
831             case CM_ERROR_NOSUCHFILE        : s = "CM_ERROR_NOSUCHFILE";         break;                         
832             case CM_ERROR_STOPNOW           : s = "CM_ERROR_STOPNOW";            break;                         
833             case CM_ERROR_TOOBIG            : s = "CM_ERROR_TOOBIG";             break;                                 
834             case CM_ERROR_INVAL             : s = "CM_ERROR_INVAL";              break;                                 
835             case CM_ERROR_BADFD             : s = "CM_ERROR_BADFD";              break;                                 
836             case CM_ERROR_BADFDOP           : s = "CM_ERROR_BADFDOP";            break;                         
837             case CM_ERROR_EXISTS            : s = "CM_ERROR_EXISTS";             break;                                 
838             case CM_ERROR_CROSSDEVLINK      : s = "CM_ERROR_CROSSDEVLINK";       break;                         
839             case CM_ERROR_BADOP             : s = "CM_ERROR_BADOP";              break;                                 
840             case CM_ERROR_BADPASSWORD       : s = "CM_ERROR_BADPASSWORD";        break;         
841             case CM_ERROR_NOTDIR            : s = "CM_ERROR_NOTDIR";             break;                                 
842             case CM_ERROR_ISDIR             : s = "CM_ERROR_ISDIR";              break;                                 
843             case CM_ERROR_READONLY          : s = "CM_ERROR_READONLY";           break;                         
844             case CM_ERROR_WOULDBLOCK        : s = "CM_ERROR_WOULDBLOCK";         break;                         
845             case CM_ERROR_QUOTA             : s = "CM_ERROR_QUOTA";              break;                                 
846             case CM_ERROR_SPACE             : s = "CM_ERROR_SPACE";              break;                                 
847             case CM_ERROR_BADSHARENAME      : s = "CM_ERROR_BADSHARENAME";       break;                         
848             case CM_ERROR_BADTID            : s = "CM_ERROR_BADTID";             break;                                 
849             case CM_ERROR_UNKNOWN           : s = "CM_ERROR_UNKNOWN";            break;                         
850             case CM_ERROR_NOMORETOKENS      : s = "CM_ERROR_NOMORETOKENS";       break;                         
851             case CM_ERROR_NOTEMPTY          : s = "CM_ERROR_NOTEMPTY";           break;                         
852             case CM_ERROR_USESTD            : s = "CM_ERROR_USESTD";             break;                                 
853             case CM_ERROR_REMOTECONN        : s = "CM_ERROR_REMOTECONN";         break;                         
854             case CM_ERROR_ATSYS             : s = "CM_ERROR_ATSYS";              break;                                 
855             case CM_ERROR_NOSUCHPATH        : s = "CM_ERROR_NOSUCHPATH";         break;                         
856             case CM_ERROR_CLOCKSKEW         : s = "CM_ERROR_CLOCKSKEW";          break;                         
857             case CM_ERROR_BADSMB            : s = "CM_ERROR_BADSMB";             break;                                 
858             case CM_ERROR_ALLBUSY           : s = "CM_ERROR_ALLBUSY";            break;                         
859             case CM_ERROR_NOFILES           : s = "CM_ERROR_NOFILES";            break;                         
860             case CM_ERROR_PARTIALWRITE      : s = "CM_ERROR_PARTIALWRITE";       break;                         
861             case CM_ERROR_NOIPC             : s = "CM_ERROR_NOIPC";              break;                                 
862             case CM_ERROR_BADNTFILENAME     : s = "CM_ERROR_BADNTFILENAME";      break;                         
863             case CM_ERROR_BUFFERTOOSMALL    : s = "CM_ERROR_BUFFERTOOSMALL";     break;                         
864             case CM_ERROR_RENAME_IDENTICAL  : s = "CM_ERROR_RENAME_IDENTICAL";   break;                 
865             case CM_ERROR_ALLOFFLINE        : s = "CM_ERROR_ALLOFFLINE";         break;          
866             case CM_ERROR_AMBIGUOUS_FILENAME: s = "CM_ERROR_AMBIGUOUS_FILENAME"; break;  
867             case CM_ERROR_BADLOGONTYPE      : s = "CM_ERROR_BADLOGONTYPE";       break;             
868             case CM_ERROR_GSSCONTINUE       : s = "CM_ERROR_GSSCONTINUE";        break;         
869             case CM_ERROR_TIDIPC            : s = "CM_ERROR_TIDIPC";             break;              
870             case CM_ERROR_TOO_MANY_SYMLINKS : s = "CM_ERROR_TOO_MANY_SYMLINKS";  break;   
871             case CM_ERROR_PATH_NOT_COVERED  : s = "CM_ERROR_PATH_NOT_COVERED";   break;    
872             case CM_ERROR_LOCK_CONFLICT     : s = "CM_ERROR_LOCK_CONFLICT";      break;       
873             case CM_ERROR_SHARING_VIOLATION : s = "CM_ERROR_SHARING_VIOLATION";  break;   
874             case CM_ERROR_ALLDOWN           : s = "CM_ERROR_ALLDOWN";            break;             
875             case CM_ERROR_TOOFEWBUFS        : s = "CM_ERROR_TOOFEWBUFS";         break;                         
876             case CM_ERROR_TOOMANYBUFS       : s = "CM_ERROR_TOOMANYBUFS";        break;                         
877             }
878             osi_Log2(afsd_logp, "cm_Analyze: ignoring error code 0x%x (%s)", 
879                      errorCode, s);
880             retry = 0;
881         }
882     }
883
884     /* If not allowed to retry, don't */
885     if (!forcing_new && (reqp->flags & CM_REQ_NORETRY))
886         retry = 0;
887     else if (retry && dead_session)
888         retry = 0;
889
890   out:
891     /* drop this on the way out */
892     if (connp)
893         cm_PutConn(connp);
894
895     /* 
896      * clear the volume updated flag if we succeed.
897      * this way the flag will not prevent a subsequent volume 
898      * from being updated if necessary.
899      */
900     if (errorCode == 0)
901     {
902         reqp->flags &= ~CM_REQ_VOLUME_UPDATED;
903     }
904
905     /* retry until we fail to find a connection */
906     return retry;
907 }
908
909 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
910         cm_req_t *reqp, cm_conn_t **connpp)
911 {
912     long code;
913     cm_serverRef_t *tsrp;
914     cm_server_t *tsp;
915     long firstError = 0;
916     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
917 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
918     long timeUsed, timeLeft, hardTimeLeft;
919 #endif
920     *connpp = NULL;
921
922     if (serversp == NULL) {
923         osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", CM_ERROR_ALLDOWN);
924         return CM_ERROR_ALLDOWN;
925     }
926
927 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
928     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
929         
930     /* leave 5 seconds margin of safety */
931     timeLeft =  ConnDeadtimeout - timeUsed - 5;
932     hardTimeLeft = HardDeadtimeout - timeUsed - 5;
933 #endif
934
935     lock_ObtainRead(&cm_serverLock);
936     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
937         if (tsrp->status == srv_deleted)
938             continue;
939
940         tsp = tsrp->server;
941         if (reqp->tokenIdleErrorServp) {
942             /* 
943              * search the list until we find the server
944              * that failed last time.  When we find it
945              * clear the error, skip it and try the one
946              * in the list.
947              */
948             if (tsp == reqp->tokenIdleErrorServp)
949                 reqp->tokenIdleErrorServp = NULL;
950             continue;
951         }
952         if (tsp) {
953             cm_GetServerNoLock(tsp);
954             lock_ReleaseRead(&cm_serverLock);
955             if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
956                 allDown = 0;
957                 if (tsrp->status == srv_busy) {
958                     allOffline = 0;
959                     someBusy = 1;
960                 } else if (tsrp->status == srv_offline) {
961                     allBusy = 0;
962                     someOffline = 1;
963                 } else {
964                     allOffline = 0;
965                     allBusy = 0;
966                     code = cm_ConnByServer(tsp, usersp, connpp);
967                     if (code == 0) {        /* cm_CBS only returns 0 */
968                         cm_PutServer(tsp);
969 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
970                         /* Set RPC timeout */
971                         if (timeLeft > ConnDeadtimeout)
972                             timeLeft = ConnDeadtimeout;
973
974                         if (hardTimeLeft > HardDeadtimeout) 
975                             hardTimeLeft = HardDeadtimeout;
976
977                         lock_ObtainMutex(&(*connpp)->mx);
978                         rx_SetConnDeadTime((*connpp)->rxconnp, timeLeft);
979                         rx_SetConnHardDeadTime((*connpp)->rxconnp, (u_short) hardTimeLeft);
980                         lock_ReleaseMutex(&(*connpp)->mx);
981 #endif
982                         return 0;
983                     }
984
985                     /* therefore, this code is never executed */
986                     if (firstError == 0)
987                         firstError = code;
988                 }
989             }
990             lock_ObtainRead(&cm_serverLock);
991             cm_PutServerNoLock(tsp);
992         }
993     }   
994     lock_ReleaseRead(&cm_serverLock);
995
996     if (firstError == 0) {
997         if (allDown) 
998             firstError = (reqp->tokenError ? reqp->tokenError : 
999                           (reqp->idleError ? RX_CALL_TIMEOUT : CM_ERROR_ALLDOWN));
1000         else if (allBusy) 
1001             firstError = CM_ERROR_ALLBUSY;
1002         else if (allOffline || (someBusy && someOffline))
1003             firstError = CM_ERROR_ALLOFFLINE;
1004         else {
1005             osi_Log0(afsd_logp, "cm_ConnByMServers returning impossible error TIMEDOUT");
1006             firstError = CM_ERROR_TIMEDOUT;
1007         }
1008     }
1009
1010     osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", firstError);
1011     return firstError;
1012 }
1013
1014 /* called with a held server to GC all bad connections hanging off of the server */
1015 void cm_GCConnections(cm_server_t *serverp)
1016 {
1017     cm_conn_t *tcp;
1018     cm_conn_t **lcpp;
1019     cm_user_t *userp;
1020
1021     lock_ObtainWrite(&cm_connLock);
1022     lcpp = &serverp->connsp;
1023     for (tcp = *lcpp; tcp; tcp = *lcpp) {
1024         userp = tcp->userp;
1025         if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
1026             /* do the deletion of this guy */
1027             cm_PutServer(tcp->serverp);
1028             cm_ReleaseUser(userp);
1029             *lcpp = tcp->nextp;
1030             rx_DestroyConnection(tcp->rxconnp);
1031             lock_FinalizeMutex(&tcp->mx);
1032             free(tcp);
1033         }
1034         else {
1035             /* just advance to the next */
1036             lcpp = &tcp->nextp;
1037         }
1038     }
1039     lock_ReleaseWrite(&cm_connLock);
1040 }
1041
1042 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
1043                                cm_server_t *serverp)
1044 {
1045     unsigned short port;
1046     int serviceID;
1047     int secIndex;
1048     struct rx_securityClass *secObjp;
1049
1050     if (serverp->type == CM_SERVER_VLDB) {
1051         port = htons(7003);
1052         serviceID = 52;
1053     }
1054     else {
1055         osi_assertx(serverp->type == CM_SERVER_FILE, "incorrect server type");
1056         port = htons(7000);
1057         serviceID = 1;
1058     }
1059     if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
1060         secIndex = 2;
1061         switch (cryptall) {
1062         case 0:
1063             tcp->cryptlevel = rxkad_clear;
1064             break;
1065         case 2:
1066             tcp->cryptlevel = rxkad_auth;
1067             break;
1068         default:
1069             tcp->cryptlevel = rxkad_crypt;
1070         }
1071         secObjp = rxkad_NewClientSecurityObject(tcp->cryptlevel,
1072                                                 &ucellp->sessionKey, ucellp->kvno,
1073                                                 ucellp->ticketLen, ucellp->ticketp);    
1074     } else {
1075         /* normal auth */
1076         secIndex = 0;
1077         tcp->cryptlevel = rxkad_clear;
1078         secObjp = rxnull_NewClientSecurityObject();
1079     }
1080     osi_assertx(secObjp != NULL, "null rx_securityClass");
1081     tcp->rxconnp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
1082                                   port,
1083                                   serviceID,
1084                                   secObjp,
1085                                   secIndex);
1086     rx_SetConnDeadTime(tcp->rxconnp, ConnDeadtimeout);
1087     rx_SetConnHardDeadTime(tcp->rxconnp, HardDeadtimeout);
1088     rx_SetConnIdleDeadTime(tcp->rxconnp, IdleDeadtimeout);
1089     tcp->ucgen = ucellp->gen;
1090     if (secObjp)
1091         rxs_Release(secObjp);   /* Decrement the initial refCount */
1092 }
1093
1094 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
1095 {
1096     cm_conn_t *tcp;
1097     cm_ucell_t *ucellp;
1098
1099     *connpp = NULL;
1100
1101     if (cm_anonvldb && serverp->type == CM_SERVER_VLDB)
1102         userp = cm_rootUserp;
1103
1104     lock_ObtainMutex(&userp->mx);
1105     lock_ObtainRead(&cm_connLock);
1106     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1107         if (tcp->userp == userp) 
1108             break;
1109     }
1110     
1111     /* find ucell structure */
1112     ucellp = cm_GetUCell(userp, serverp->cellp);
1113     if (!tcp) {
1114         lock_ConvertRToW(&cm_connLock);
1115         for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1116             if (tcp->userp == userp) 
1117                 break;
1118         }
1119         if (tcp) {
1120             lock_ReleaseWrite(&cm_connLock);
1121             goto haveconn;
1122         }
1123         cm_GetServer(serverp);
1124         tcp = malloc(sizeof(*tcp));
1125         memset(tcp, 0, sizeof(*tcp));
1126         tcp->nextp = serverp->connsp;
1127         serverp->connsp = tcp;
1128         cm_HoldUser(userp);
1129         tcp->userp = userp;
1130         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex", LOCK_HIERARCHY_CONN);
1131         lock_ObtainMutex(&tcp->mx);
1132         tcp->serverp = serverp;
1133         tcp->cryptlevel = rxkad_clear;
1134         cm_NewRXConnection(tcp, ucellp, serverp);
1135         tcp->refCount = 1;
1136         lock_ReleaseMutex(&tcp->mx);
1137         lock_ReleaseWrite(&cm_connLock);
1138     } else {
1139         lock_ReleaseRead(&cm_connLock);
1140       haveconn:
1141         InterlockedIncrement(&tcp->refCount);
1142
1143         lock_ObtainMutex(&tcp->mx);
1144         if ((tcp->flags & CM_CONN_FLAG_FORCE_NEW) ||
1145             (tcp->ucgen < ucellp->gen) ||
1146             (tcp->cryptlevel != (ucellp->flags & CM_UCELLFLAG_RXKAD ? (cryptall == 1 ? rxkad_crypt : (cryptall == 2 ? rxkad_auth : rxkad_clear)) : rxkad_clear)))
1147         {
1148             if (tcp->ucgen < ucellp->gen)
1149                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to token update");
1150             else
1151                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to crypt change");
1152             tcp->flags &= ~CM_CONN_FLAG_FORCE_NEW;
1153             rx_DestroyConnection(tcp->rxconnp);
1154             cm_NewRXConnection(tcp, ucellp, serverp);
1155         }
1156         lock_ReleaseMutex(&tcp->mx);
1157     }
1158     lock_ReleaseMutex(&userp->mx);
1159
1160     /* return this pointer to our caller */
1161     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%p", tcp);
1162     *connpp = tcp;
1163
1164     return 0;
1165 }
1166
1167 long cm_ServerAvailable(struct cm_fid *fidp, struct cm_user *userp)
1168 {
1169     long code;
1170     cm_req_t req;
1171     cm_serverRef_t **serverspp;
1172     cm_serverRef_t *tsrp;
1173     cm_server_t *tsp;
1174     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
1175
1176     cm_InitReq(&req);
1177
1178     code = cm_GetServerList(fidp, userp, &req, &serverspp);
1179     if (code)
1180         return 0;
1181
1182     lock_ObtainRead(&cm_serverLock);
1183     for (tsrp = *serverspp; tsrp; tsrp=tsrp->next) {
1184         if (tsrp->status == srv_deleted)
1185             continue;
1186         tsp = tsrp->server;
1187         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1188             allDown = 0;
1189             if (tsrp->status == srv_busy) {
1190                 allOffline = 0;
1191                 someBusy = 1;
1192             } else if (tsrp->status == srv_offline) {
1193                 allBusy = 0;
1194                 someOffline = 1;
1195             } else {
1196                 allOffline = 0;
1197                 allBusy = 0;
1198             }
1199         }
1200     }   
1201     lock_ReleaseRead(&cm_serverLock);
1202     cm_FreeServerList(serverspp, 0);
1203
1204     if (allDown)
1205         return 0;
1206     else if (allBusy) 
1207         return 0;
1208     else if (allOffline || (someBusy && someOffline))
1209         return 0;
1210     else
1211         return 1;
1212 }
1213
1214 /* 
1215  * The returned cm_conn_t ** object is released in the subsequent call
1216  * to cm_Analyze().  
1217  */
1218 long cm_ConnFromFID(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
1219                     cm_conn_t **connpp)
1220 {
1221     long code;
1222     cm_serverRef_t **serverspp;
1223
1224     *connpp = NULL;
1225
1226     code = cm_GetServerList(fidp, userp, reqp, &serverspp);
1227     if (code) {
1228         return code;
1229     }
1230
1231     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
1232     cm_FreeServerList(serverspp, 0);
1233     return code;
1234 }
1235
1236
1237 long cm_ConnFromVolume(struct cm_volume *volp, unsigned long volid, struct cm_user *userp, cm_req_t *reqp,
1238                        cm_conn_t **connpp)
1239 {
1240     long code;
1241     cm_serverRef_t **serverspp;
1242
1243     *connpp = NULL;
1244
1245     serverspp = cm_GetVolServers(volp, volid, userp, reqp);
1246
1247     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
1248     cm_FreeServerList(serverspp, 0);
1249     return code;
1250 }
1251
1252
1253 extern struct rx_connection *
1254 cm_GetRxConn(cm_conn_t *connp)
1255 {
1256     struct rx_connection * rxconnp;
1257     lock_ObtainMutex(&connp->mx);
1258     rxconnp = connp->rxconnp;
1259     rx_GetConnection(rxconnp);
1260     lock_ReleaseMutex(&connp->mx);
1261     return rxconnp;
1262 }
1263
1264 void cm_ForceNewConnections(cm_server_t *serverp)
1265 {
1266     cm_conn_t *tcp;
1267
1268     lock_ObtainWrite(&cm_connLock);
1269     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1270         lock_ObtainMutex(&tcp->mx);
1271         tcp->flags |= CM_CONN_FLAG_FORCE_NEW;
1272         lock_ReleaseMutex(&tcp->mx);
1273     }
1274     lock_ReleaseWrite(&cm_connLock);
1275 }