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