Windows: handle CM_ERROR_RETRY in cm_Analyze()
[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 <afsconfig.h>
11 #include <afs/param.h>
12 #include <roken.h>
13
14 #include <afs/stds.h>
15
16 #include <windows.h>
17 #include <string.h>
18 #include <malloc.h>
19 #include <osi.h>
20 #include "afsd.h"
21 #include <rx/rx.h>
22 #include <rx/rxkad.h>
23 #include <afs/unified_afs.h>
24 #include <afs/vlserver.h>
25 #include <WINNT/afsreg.h>
26
27 osi_rwlock_t cm_connLock;
28
29 DWORD RDRtimeout = CM_CONN_DEFAULTRDRTIMEOUT;
30 unsigned short ConnDeadtimeout = CM_CONN_CONNDEADTIME;
31 unsigned short HardDeadtimeout = CM_CONN_HARDDEADTIME;
32 unsigned short IdleDeadtimeout = CM_CONN_IDLEDEADTIME;
33 unsigned short ReplicaIdleDeadtimeout = CM_CONN_IDLEDEADTIME_REP;
34 unsigned short NatPingInterval = CM_CONN_NATPINGINTERVAL;
35
36 #define LANMAN_WKS_PARAM_KEY "SYSTEM\\CurrentControlSet\\Services\\lanmanworkstation\\parameters"
37 #define LANMAN_WKS_SESSION_TIMEOUT "SessTimeout"
38 #define LANMAN_WKS_EXT_SESSION_TIMEOUT "ExtendedSessTimeout"
39
40 afs_uint32 cryptall = 0;
41 afs_uint32 cm_anonvldb = 0;
42 afs_uint32 rx_pmtu_discovery = 0;
43
44 void cm_PutConn(cm_conn_t *connp)
45 {
46     afs_int32 refCount = InterlockedDecrement(&connp->refCount);
47     osi_assertx(refCount >= 0, "cm_conn_t refcount underflow");
48 }
49
50 void cm_InitConn(void)
51 {
52     static osi_once_t once;
53     long code;
54     DWORD dwValue;
55     DWORD dummyLen;
56     HKEY parmKey;
57
58     if (osi_Once(&once)) {
59         lock_InitializeRWLock(&cm_connLock, "connection global lock",
60                                LOCK_HIERARCHY_CONN_GLOBAL);
61
62         /* keisa - read timeout value for lanmanworkstation  service.
63          * jaltman - as per
64          *   http://support.microsoft.com:80/support/kb/articles/Q102/0/67.asp&NoWebContent=1
65          * the SessTimeout is a minimum timeout not a maximum timeout.  Therefore,
66          * I believe that the default should not be short.  Instead, we should wait until
67          * RX times out before reporting a timeout to the SMB client.
68          */
69         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LANMAN_WKS_PARAM_KEY,
70                             0, KEY_QUERY_VALUE, &parmKey);
71         if (code == ERROR_SUCCESS)
72         {
73             BOOL extTimeouts = msftSMBRedirectorSupportsExtendedTimeouts();
74
75             if (extTimeouts) {
76                 /*
77                  * The default value is 1000 seconds.  However, this default
78                  * will not apply to "\\AFS" unless "AFS" is listed in
79                  * ServersWithExtendedSessTimeout which we will add when we
80                  * create the ExtendedSessTimeout value in smb_Init()
81                  */
82                 dummyLen = sizeof(DWORD);
83                 code = RegQueryValueEx(parmKey,
84                                        LANMAN_WKS_EXT_SESSION_TIMEOUT,
85                                         NULL, NULL,
86                                         (BYTE *) &dwValue, &dummyLen);
87                 if (code == ERROR_SUCCESS) {
88                     RDRtimeout = dwValue;
89                     afsi_log("lanmanworkstation : ExtSessTimeout %u", RDRtimeout);
90                 }
91             }
92             if (!extTimeouts || code != ERROR_SUCCESS) {
93                 dummyLen = sizeof(DWORD);
94                 code = RegQueryValueEx(parmKey,
95                                        LANMAN_WKS_SESSION_TIMEOUT,
96                                        NULL, NULL,
97                                        (BYTE *) &dwValue, &dummyLen);
98                 if (code == ERROR_SUCCESS) {
99                     RDRtimeout = dwValue;
100                     afsi_log("lanmanworkstation : SessTimeout %u", RDRtimeout);
101                 }
102             }
103             RegCloseKey(parmKey);
104         }
105
106         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
107                              0, KEY_QUERY_VALUE, &parmKey);
108         if (code == ERROR_SUCCESS) {
109             dummyLen = sizeof(DWORD);
110             code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
111                                     (BYTE *) &dwValue, &dummyLen);
112             if (code == ERROR_SUCCESS) {
113                 ConnDeadtimeout = (unsigned short)dwValue;
114                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
115             }
116             dummyLen = sizeof(DWORD);
117             code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
118                                     (BYTE *) &dwValue, &dummyLen);
119             if (code == ERROR_SUCCESS) {
120                 HardDeadtimeout = (unsigned short)dwValue;
121                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
122             }
123             dummyLen = sizeof(DWORD);
124             code = RegQueryValueEx(parmKey, "IdleDeadTimeout", NULL, NULL,
125                                     (BYTE *) &dwValue, &dummyLen);
126             if (code == ERROR_SUCCESS) {
127                 IdleDeadtimeout = (unsigned short)dwValue;
128                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
129             }
130             dummyLen = sizeof(DWORD);
131             code = RegQueryValueEx(parmKey, "ReplicaIdleDeadTimeout", NULL, NULL,
132                                     (BYTE *) &dwValue, &dummyLen);
133             if (code == ERROR_SUCCESS) {
134                 ReplicaIdleDeadtimeout = (unsigned short)dwValue;
135                 afsi_log("ReplicaIdleDeadTimeout is %d", ReplicaIdleDeadtimeout);
136             }
137             dummyLen = sizeof(DWORD);
138             code = RegQueryValueEx(parmKey, "NatPingInterval", NULL, NULL,
139                                     (BYTE *) &dwValue, &dummyLen);
140             if (code == ERROR_SUCCESS) {
141                 NatPingInterval = (unsigned short)dwValue;
142             }
143             afsi_log("NatPingInterval is %d", NatPingInterval);
144             RegCloseKey(parmKey);
145         }
146
147         /*
148          * If these values were not set via cpp macro or obtained
149          * from the registry, we use a value that is derived from
150          * the smb redirector session timeout (RDRtimeout).
151          *
152          * The UNIX cache manager uses 120 seconds for the hard dead
153          * timeout and 50 seconds for the connection and idle timeouts.
154          *
155          * We base our values on those while making sure we leave
156          * enough time for overhead.
157          *
158          * To further complicate matters we need to take into account
159          * file server hard dead timeouts as they affect the length
160          * of time it takes the file server to give up when attempting
161          * to break callbacks to unresponsive clients.  The file
162          * server hard dead timeout is 120 seconds.
163          *
164          * For SMB, we have no choice but to timeout quickly.  For
165          * the AFS redirector, we can wait.
166          */
167         if (smb_Enabled) {
168             afsi_log("lanmanworkstation : SessTimeout %u", RDRtimeout);
169             if (ConnDeadtimeout == 0) {
170                 ConnDeadtimeout = (unsigned short) ((RDRtimeout / 2) < 50 ? (RDRtimeout / 2) : 50);
171                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
172             }
173             if (HardDeadtimeout == 0) {
174                 HardDeadtimeout = (unsigned short) (RDRtimeout > 125 ? 120 : (RDRtimeout - 5));
175                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
176             }
177             if (IdleDeadtimeout == 0) {
178                 IdleDeadtimeout = 10 * (unsigned short) HardDeadtimeout;
179                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
180             }
181             if (ReplicaIdleDeadtimeout == 0) {
182                 ReplicaIdleDeadtimeout = (unsigned short) HardDeadtimeout;
183                 afsi_log("ReplicaIdleDeadTimeout is %d", ReplicaIdleDeadtimeout);
184             }
185         } else {
186             if (ConnDeadtimeout == 0) {
187                 ConnDeadtimeout = CM_CONN_IFS_CONNDEADTIME;
188                 afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
189             }
190             if (HardDeadtimeout == 0) {
191                 HardDeadtimeout = CM_CONN_IFS_HARDDEADTIME;
192                 afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
193             }
194             if (IdleDeadtimeout == 0) {
195                 IdleDeadtimeout = CM_CONN_IFS_IDLEDEADTIME;
196                 afsi_log("IdleDeadTimeout is %d", IdleDeadtimeout);
197             }
198             if (IdleDeadtimeout == 0) {
199                 ReplicaIdleDeadtimeout = CM_CONN_IFS_IDLEDEADTIME_REP;
200                 afsi_log("ReplicaIdleDeadTimeout is %d", ReplicaIdleDeadtimeout);
201             }
202         }
203         osi_EndOnce(&once);
204     }
205 }
206
207 void cm_InitReq(cm_req_t *reqp)
208 {
209         memset(reqp, 0, sizeof(cm_req_t));
210         reqp->startTime = GetTickCount();
211 }
212
213 long cm_GetVolServerList(cm_volume_t *volp, afs_uint32 volid, struct cm_user *userp,
214         struct cm_req *reqp, afs_uint32 *replicated, cm_serverRef_t ***serversppp)
215 {
216     *serversppp = cm_GetVolServers(volp, volid, userp, reqp, replicated);
217     return (*serversppp ? 0 : CM_ERROR_NOSUCHVOLUME);
218 }
219
220 long cm_GetServerList(struct cm_fid *fidp, struct cm_user *userp,
221         struct cm_req *reqp, afs_uint32 *replicated, cm_serverRef_t ***serversppp)
222 {
223     long code;
224     cm_volume_t *volp = NULL;
225     cm_cell_t *cellp = NULL;
226
227     if (!fidp) {
228         *serversppp = NULL;
229         return CM_ERROR_INVAL;
230     }
231
232     cellp = cm_FindCellByID(fidp->cell, 0);
233     if (!cellp)
234         return CM_ERROR_NOSUCHCELL;
235
236     code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, CM_GETVOL_FLAG_CREATE, &volp);
237     if (code)
238         return code;
239
240     *serversppp = cm_GetVolServers(volp, fidp->volume, userp, reqp, replicated);
241
242     lock_ObtainRead(&cm_volumeLock);
243     cm_PutVolume(volp);
244     lock_ReleaseRead(&cm_volumeLock);
245     return (*serversppp ? 0 : CM_ERROR_NOSUCHVOLUME);
246 }
247
248 void
249 cm_SetServerBusyStatus(cm_serverRef_t *serversp, cm_server_t *serverp)
250 {
251     cm_serverRef_t *tsrp;
252
253     lock_ObtainWrite(&cm_serverLock);
254     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
255         if (tsrp->status == srv_deleted)
256             continue;
257         if (cm_ServerEqual(tsrp->server, serverp) && tsrp->status == srv_not_busy) {
258             tsrp->status = srv_busy;
259             break;
260         }
261     }
262     lock_ReleaseWrite(&cm_serverLock);
263 }
264
265 void
266 cm_ResetServerBusyStatus(cm_serverRef_t *serversp)
267 {
268     cm_serverRef_t *tsrp;
269
270     lock_ObtainWrite(&cm_serverLock);
271     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
272         if (tsrp->status == srv_deleted)
273             continue;
274         if (tsrp->status == srv_busy) {
275             tsrp->status = srv_not_busy;
276         }
277     }
278     lock_ReleaseWrite(&cm_serverLock);
279 }
280
281 /*
282  * Analyze the error return from an RPC.  Determine whether or not to retry,
283  * and if we're going to retry, determine whether failover is appropriate,
284  * and whether timed backoff is appropriate.
285  *
286  * If the error code is from cm_ConnFromFID() or friends, it will be a CM_ERROR code.
287  * Otherwise it will be an RPC code.  This may be a UNIX code (e.g. EDQUOT), or
288  * it may be an RX code, or it may be a special code (e.g. VNOVOL), or it may
289  * be a security code (e.g. RXKADEXPIRED).
290  *
291  * If the error code is from cm_ConnFromFID() or friends, connp will be NULL.
292  *
293  * For VLDB calls, fidp will be NULL and cellp will not be.
294  *
295  * volSyncp and/or cbrp may also be NULL.
296  */
297 int
298 cm_Analyze(cm_conn_t *connp,
299            cm_user_t *userp,
300            cm_req_t *reqp,
301            struct cm_fid *fidp,
302            cm_cell_t *cellp,
303            afs_uint32 storeOp,
304            AFSFetchStatus *statusp,
305            AFSVolSync *volSyncp,
306            cm_serverRef_t * serversp,
307            cm_callbackRequest_t *cbrp,
308            long errorCode)
309 {
310     cm_server_t *serverp = NULL;
311     cm_serverRef_t **serverspp = NULL;
312     cm_serverRef_t *tsrp;
313     cm_ucell_t *ucellp;
314     cm_volume_t * volp = NULL;
315     cm_vol_state_t *statep = NULL;
316     cm_scache_t * scp = NULL;
317     afs_uint32 replicated = 0;
318     int retry = 0;
319     int free_svr_list = 0;
320     int dead_session = (userp->cellInfop == NULL);
321     long timeUsed, timeLeft;
322     long code = 0;
323     char addr[16]="unknown";
324     int forcing_new = 0;
325     int location_updated = 0;
326     char *format;
327     DWORD msgID;
328     int invalid_status = 0;
329
330     osi_Log2(afsd_logp, "cm_Analyze connp 0x%p, code 0x%x",
331              connp, errorCode);
332
333     /* no locking required, since connp->serverp never changes after
334      * creation */
335     if (connp)
336         serverp = connp->serverp;
337
338     /* Update callback pointer */
339     if (cbrp && serverp && errorCode == 0) {
340         if (cbrp->serverp) {
341             if ( cbrp->serverp != serverp ) {
342                 lock_ObtainWrite(&cm_serverLock);
343                 cm_PutServerNoLock(cbrp->serverp);
344                 cm_GetServerNoLock(serverp);
345                 lock_ReleaseWrite(&cm_serverLock);
346             }
347         } else {
348             cm_GetServer(serverp);
349         }
350         cbrp->serverp = serverp;
351     }
352
353     /* if timeout - check that it did not exceed the HardDead timeout
354      * and retry */
355
356     /* timeleft - get it from reqp the same way as cm_ConnByMServers does */
357     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
358     if ( reqp->flags & CM_REQ_SOURCE_SMB )
359         timeLeft = HardDeadtimeout - timeUsed;
360     else
361         timeLeft = 0x0FFFFFFF;
362
363     /*
364      * Similar to the UNIX cache manager, if the AFSFetchStatus info
365      * returned by the file server is invalid, consider the response
366      * as being equivalent to VBUSY so that another file server can
367      * be queried if there is one.  If there is no replica, then the
368      * request will fail.
369      */
370     if (errorCode == 0 && statusp && !cm_IsStatusValid(statusp)) {
371         invalid_status = 1;
372         errorCode = VBUSY;
373     }
374
375     /* get a pointer to the cell */
376     if (errorCode) {
377         if (cellp == NULL && serverp)
378             cellp = serverp->cellp;
379         if (cellp == NULL && serversp) {
380             struct cm_serverRef * refp;
381             for ( refp=serversp ; cellp == NULL && refp != NULL; refp=refp->next) {
382                 if (refp->status == srv_deleted)
383                     continue;
384                 if ( refp->server )
385                     cellp = refp->server->cellp;
386             }
387         }
388         if (cellp == NULL && fidp) {
389             cellp = cm_FindCellByID(fidp->cell, 0);
390         }
391     }
392
393     if (errorCode == CM_ERROR_TIMEDOUT) {
394         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_TIMEDOUT");
395         if ( timeLeft > 5 ) {
396             thrd_Sleep(3000);
397             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, cellp);
398             retry = 1;
399         }
400     }
401
402     else if (errorCode == CM_ERROR_RETRY) {
403         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_RETRY");
404         retry = 1;
405     }
406
407     else if (errorCode == UAEWOULDBLOCK || errorCode == EWOULDBLOCK ||
408               errorCode == UAEAGAIN || errorCode == EAGAIN) {
409         osi_Log0(afsd_logp, "cm_Analyze passed EWOULDBLOCK or EAGAIN.");
410         if ( timeLeft > 5 ) {
411             thrd_Sleep(1000);
412             retry = 1;
413         }
414     }
415
416     /* if there is nosuchvolume, then we have a situation in which a
417      * previously known volume no longer has a set of servers
418      * associated with it.  Either the volume has moved or
419      * the volume has been deleted.  Try to find a new server list
420      * until the timeout period expires.
421      */
422     else if (errorCode == CM_ERROR_NOSUCHVOLUME) {
423         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_NOSUCHVOLUME.");
424         /*
425          * The VNOVOL or VL_NOENT error has already been translated
426          * to CM_ERROR_NOSUCHVOLUME.  There is nothing for us to do.
427          */
428     }
429
430     else if (errorCode == CM_ERROR_EMPTY) {
431         /*
432          * The server list is empty (or all entries have been deleted).
433          * If fidp is NULL, this was a vlServer list and we can attempt
434          * to force a cell lookup.  If fidp is not NULL, we can attempt
435          * to refresh the volume location list.
436          */
437         if (fidp) {
438             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
439                                      CM_GETVOL_FLAG_NO_LRU_UPDATE,
440                                      &volp);
441             if (code == 0) {
442                 lock_ObtainWrite(&volp->rw);
443                 if (cm_UpdateVolumeLocation(cellp, userp, reqp, volp) == 0) {
444                     lock_ReleaseWrite(&volp->rw);
445                     code = cm_GetVolServerList(volp, fidp->volume, userp, reqp, &replicated, &serverspp);
446                     if (code == 0) {
447                         if (!cm_IsServerListEmpty(*serverspp))
448                             retry = 1;
449                         cm_FreeServerList(serverspp, 0);
450                     }
451                 } else {
452                     lock_ReleaseWrite(&volp->rw);
453                 }
454                 lock_ObtainRead(&cm_volumeLock);
455                 cm_PutVolume(volp);
456                 lock_ReleaseRead(&cm_volumeLock);
457                 volp = NULL;
458             }
459         } else {
460             cm_cell_t * newCellp = cm_UpdateCell( cellp, 0);
461             if (newCellp)
462                 retry = 1;
463         }
464     }
465     else if (errorCode == CM_ERROR_ALLDOWN) {
466         /* Servers marked DOWN will be restored by the background daemon
467          * thread as they become available.  The volume status is
468          * updated as the server state changes.
469          */
470         if (fidp) {
471             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_DOWN (FS cell %s vol 0x%x)",
472                       cellp->name, fidp->volume);
473             msgID = MSG_ALL_SERVERS_DOWN;
474             format = "All servers are unreachable when accessing cell %s volume %d.";
475             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
476         } else {
477             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLDOWN (VL Server)");
478         }
479     }
480     else if (errorCode == CM_ERROR_ALLOFFLINE) {
481         /* Volume instances marked offline will be restored by the
482          * background daemon thread as they become available
483          */
484         if (fidp) {
485             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE (FS cell %s vol 0x%x)",
486                       cellp->name, fidp->volume);
487             msgID = MSG_ALL_SERVERS_OFFLINE;
488             format = "All servers are offline when accessing cell %s volume %d.";
489             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
490
491             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
492                                       CM_GETVOL_FLAG_NO_LRU_UPDATE,
493                                       &volp);
494             if (code == 0) {
495                 if (!serversp) {
496                     code = cm_GetVolServerList(volp, fidp->volume, userp, reqp, &replicated, &serverspp);
497                     if (code == 0) {
498                         serversp = *serverspp;
499                         free_svr_list = 1;
500                     }
501                 }
502                 cm_ResetServerBusyStatus(serversp);
503                 if (free_svr_list) {
504                     cm_FreeServerList(serverspp, 0);
505                     free_svr_list = 0;
506                     serversp = NULL;
507                 }
508
509                 /*
510                  * Do not perform a cm_CheckOfflineVolume() if cm_Analyze()
511                  * was called by cm_CheckOfflineVolumeState().
512                  */
513                 if (!(reqp->flags & CM_REQ_OFFLINE_VOL_CHK) && timeLeft > 7) {
514                     thrd_Sleep(5000);
515
516                     /* cm_CheckOfflineVolume() resets the serverRef state */
517                     if (cm_CheckOfflineVolume(volp, fidp->volume))
518                         retry = 1;
519                 } else {
520                     cm_UpdateVolumeStatus(volp, fidp->volume);
521                 }
522                 lock_ObtainRead(&cm_volumeLock);
523                 cm_PutVolume(volp);
524                 lock_ReleaseRead(&cm_volumeLock);
525                 volp = NULL;
526             }
527         } else {
528             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE (VL Server)");
529         }
530     }
531     else if (errorCode == CM_ERROR_ALLBUSY) {
532         /* Volumes that are busy cannot be determined to be non-busy
533          * without actually attempting to access them.
534          */
535         if (fidp) { /* File Server query */
536             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY (FS cell %s vol 0x%x)",
537                      cellp->name, fidp->volume);
538             msgID = MSG_ALL_SERVERS_BUSY;
539             format = "All servers are busy when accessing cell %s volume %d.";
540             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
541
542             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
543                                      CM_GETVOL_FLAG_NO_LRU_UPDATE,
544                                      &volp);
545             if (code == 0) {
546                 if (!serversp) {
547                     code = cm_GetVolServerList(volp, fidp->volume, userp, reqp, &replicated, &serverspp);
548                     if (code == 0) {
549                         serversp = *serverspp;
550                         free_svr_list = 1;
551                     }
552                 }
553                 cm_ResetServerBusyStatus(serversp);
554                 if (free_svr_list) {
555                     cm_FreeServerList(serverspp, 0);
556                     free_svr_list = 0;
557                     serversp = NULL;
558                 }
559
560                 if (timeLeft > 7) {
561                     thrd_Sleep(5000);
562                     statep = cm_VolumeStateByID(volp, fidp->volume);
563                     retry = 1;
564                 }
565                 cm_UpdateVolumeStatus(volp, fidp->volume);
566
567                 lock_ObtainRead(&cm_volumeLock);
568                 cm_PutVolume(volp);
569                 lock_ReleaseRead(&cm_volumeLock);
570                 volp = NULL;
571             }
572         } else {    /* VL Server query */
573             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY (VL Server).");
574
575             if (timeLeft > 7) {
576                 thrd_Sleep(5000);
577
578                 if (serversp) {
579                     cm_ResetServerBusyStatus(serversp);
580                     retry = 1;
581                 }
582             }
583         }
584     }
585
586     /* special codes:  VBUSY and VRESTARTING */
587     else if (errorCode == VBUSY || errorCode == VRESTARTING) {
588         if (fidp) {
589             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
590                                       CM_GETVOL_FLAG_NO_LRU_UPDATE,
591                                       &volp);
592             if (code == 0) {
593                 if (!serversp) {
594                     code = cm_GetVolServerList(volp, fidp->volume, userp, reqp, &replicated, &serverspp);
595                     if (code == 0) {
596                         serversp = *serverspp;
597                         free_svr_list = 1;
598                     }
599                 }
600
601                 statep = cm_VolumeStateByID(volp, fidp->volume);
602
603                 if (statep)
604                     cm_UpdateVolumeStatus(volp, statep->ID);
605
606                 lock_ObtainRead(&cm_volumeLock);
607                 cm_PutVolume(volp);
608                 lock_ReleaseRead(&cm_volumeLock);
609                 volp = NULL;
610             }
611         }
612
613         if (serverp) {
614             /* Log server being offline for this volume */
615             sprintf(addr, "%d.%d.%d.%d",
616                     ((serverp->addr.sin_addr.s_addr & 0xff)),
617                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
618                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
619                      ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
620
621             switch ( errorCode ) {
622             case VBUSY:
623                 if (invalid_status) {
624                     msgID = MSG_SERVER_REPLIED_BAD_STATUS;
625                     format = "Server %s replied with bad status info when accessing volume %d in cell %s.  Data discarded by cache manager.";
626                 } else {
627                     msgID = MSG_SERVER_REPORTS_VBUSY;
628                     format = "Server %s reported busy when accessing volume %d in cell %s.";
629                 }
630                 break;
631             case VRESTARTING:
632                 msgID = MSG_SERVER_REPORTS_VRESTARTING;
633                 format = "Server %s reported restarting when accessing volume %d in cell %s.";
634                 break;
635             }
636
637             osi_Log3(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
638             LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume, cellp->name);
639
640             cm_SetServerBusyStatus(serversp, serverp);
641         }
642
643         if (free_svr_list) {
644             cm_FreeServerList(serverspp, 0);
645             serversp = NULL;
646             free_svr_list = 0;
647         }
648         retry = 1;
649     }
650
651     /* special codes:  missing volumes */
652     else if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE ||
653              errorCode == VSALVAGE || errorCode == VIO)
654     {
655         /* In case of timeout */
656         reqp->volumeError = errorCode;
657
658         switch ( errorCode ) {
659         case VNOVOL:
660             msgID = MSG_SERVER_REPORTS_VNOVOL;
661             format = "Server %s reported volume %d in cell %s as not attached (may have been moved or deleted).";
662             break;
663         case VMOVED:
664             msgID = MSG_SERVER_REPORTS_VMOVED;
665             format = "Server %s reported volume %d in cell %s as moved.";
666             break;
667         case VOFFLINE:
668             msgID = MSG_SERVER_REPORTS_VOFFLINE;
669             format = "Server %s reported volume %d in cell %s as offline.";
670             break;
671         case VSALVAGE:
672             msgID = MSG_SERVER_REPORTS_VSALVAGE;
673             format = "Server %s reported volume %d in cell %s as needs salvage.";
674             break;
675         case VIO:
676             msgID = MSG_SERVER_REPORTS_VIO;
677             format = "Server %s reported volume %d in cell %s as temporarily unaccessible.";
678             break;
679         }
680
681         if (fidp) { /* File Server query */
682             if (serverp) {
683                 /* Log server being unavailable for this volume */
684                 sprintf(addr, "%d.%d.%d.%d",
685                          ((serverp->addr.sin_addr.s_addr & 0xff)),
686                          ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
687                          ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
688                          ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
689
690                 osi_Log3(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
691                 LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume, cellp->name);
692             }
693
694             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
695                                       CM_GETVOL_FLAG_NO_LRU_UPDATE,
696                                       &volp);
697             if (code == 0)
698                 statep = cm_VolumeStateByID(volp, fidp->volume);
699
700             if ((errorCode == VMOVED || errorCode == VNOVOL || errorCode == VOFFLINE) &&
701                 !(reqp->flags & CM_REQ_VOLUME_UPDATED))
702             {
703                 LONG_PTR oldSum, newSum;
704
705                 oldSum = cm_ChecksumVolumeServerList(fidp, userp, reqp);
706
707                 code = cm_ForceUpdateVolume(fidp, userp, reqp);
708                 if (code == 0) {
709                     location_updated = 1;
710                     newSum = cm_ChecksumVolumeServerList(fidp, userp, reqp);
711                 }
712
713                 /*
714                  * Even if the update fails, there might still be another replica.
715                  * If the volume location list changed, permit another update on
716                  * a subsequent error.
717                  */
718                 if (code || oldSum == newSum)
719                     reqp->flags |= CM_REQ_VOLUME_UPDATED;
720
721                 osi_Log3(afsd_logp, "cm_Analyze called cm_ForceUpdateVolume cell %u vol %u code 0x%x",
722                          fidp->cell, fidp->volume, code);
723             }
724
725             if (statep) {
726                 cm_UpdateVolumeStatus(volp, statep->ID);
727                 osi_Log3(afsd_logp, "cm_Analyze NewVolState cell %u vol %u state %u",
728                          fidp->cell, fidp->volume, statep->state);
729             }
730
731             if (volp) {
732                 lock_ObtainRead(&cm_volumeLock);
733                 cm_PutVolume(volp);
734                 lock_ReleaseRead(&cm_volumeLock);
735                 volp = NULL;
736             }
737
738             /*
739              * Mark server offline for this volume or delete the volume
740              * from the server list if it was moved or is not present.
741              */
742             if (!serversp || location_updated) {
743                 code = cm_GetServerList(fidp, userp, reqp, &replicated, &serverspp);
744                 if (code == 0) {
745                     serversp = *serverspp;
746                     free_svr_list = 1;
747                 }
748             }
749         }
750
751         lock_ObtainWrite(&cm_serverLock);
752         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
753             if (tsrp->status == srv_deleted)
754                 continue;
755
756             sprintf(addr, "%d.%d.%d.%d",
757                      ((tsrp->server->addr.sin_addr.s_addr & 0xff)),
758                      ((tsrp->server->addr.sin_addr.s_addr & 0xff00)>> 8),
759                      ((tsrp->server->addr.sin_addr.s_addr & 0xff0000)>> 16),
760                      ((tsrp->server->addr.sin_addr.s_addr & 0xff000000)>> 24));
761
762             if (cm_ServerEqual(tsrp->server, serverp)) {
763                 /* REDIRECT */
764                 switch (errorCode) {
765                 case VMOVED:
766                     osi_Log2(afsd_logp, "volume %u moved from server %s",
767                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
768                     tsrp->status = srv_deleted;
769                     if (fidp)
770                         cm_RemoveVolumeFromServer(serverp, fidp->volume);
771                     break;
772                 case VNOVOL:
773                     /*
774                      * The 1.6.0 and 1.6.1 file servers send transient VNOVOL errors which
775                      * are no indicative of the volume not being present.  For example,
776                      * VNOVOL can be sent during a transition to a VBUSY state prior to
777                      * salvaging or when cloning a .backup volume instance.  As a result
778                      * the cache manager must attempt at least one retry when a VNOVOL is
779                      * receive but there are no changes to the volume location information.
780                      */
781                     if (reqp->vnovolError > 0 && cm_ServerEqual(reqp->errorServp, serverp)) {
782                         osi_Log2(afsd_logp, "volume %u not present on server %s",
783                                   fidp->volume, osi_LogSaveString(afsd_logp,addr));
784                         tsrp->status = srv_deleted;
785                         if (fidp)
786                             cm_RemoveVolumeFromServer(serverp, fidp->volume);
787                     } else {
788                         osi_Log2(afsd_logp, "VNOVOL received for volume %u from server %s",
789                                  fidp->volume, osi_LogSaveString(afsd_logp,addr));
790                         if (replicated) {
791                             if (tsrp->status == srv_not_busy)
792                                 tsrp->status = srv_busy;
793                         } else {
794                             Sleep(2000);
795                         }
796                     }
797                     break;
798                 case VOFFLINE:
799                     osi_Log2(afsd_logp, "VOFFLINE received for volume %u from server %s",
800                               fidp->volume, osi_LogSaveString(afsd_logp,addr));
801                     tsrp->status = srv_offline;
802                     break;
803                 default:
804                     osi_Log3(afsd_logp, "volume %u exists on server %s with status %u",
805                              fidp->volume, osi_LogSaveString(afsd_logp,addr), tsrp->status);
806                 }
807             }
808         }
809         lock_ReleaseWrite(&cm_serverLock);
810
811         /* Remember that the VNOVOL error occurred */
812         if (errorCode == VNOVOL) {
813             reqp->errorServp = serverp;
814             reqp->vnovolError++;
815         }
816
817         /* Free the server list before cm_ForceUpdateVolume is called */
818         if (free_svr_list) {
819             cm_FreeServerList(serverspp, 0);
820             serversp = NULL;
821             free_svr_list = 0;
822         }
823
824         if ( timeLeft > 2 )
825             retry = 1;
826     } else if ( errorCode == VNOVNODE ) {
827         if ( fidp ) {
828             osi_Log4(afsd_logp, "cm_Analyze passed VNOVNODE cell %u vol %u vn %u uniq %u.",
829                       fidp->cell, fidp->volume, fidp->vnode, fidp->unique);
830
831             scp = cm_FindSCache(fidp);
832             if (scp) {
833                 cm_scache_t *pscp = NULL;
834
835                 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
836                     pscp = cm_FindSCacheParent(scp);
837
838                 lock_ObtainWrite(&scp->rw);
839                 scp->flags |= CM_SCACHEFLAG_DELETED;
840                 lock_ObtainWrite(&cm_scacheLock);
841                 cm_AdjustScacheLRU(scp);
842                 cm_RemoveSCacheFromHashTable(scp);
843                 lock_ReleaseWrite(&cm_scacheLock);
844                 cm_LockMarkSCacheLost(scp);
845                 lock_ReleaseWrite(&scp->rw);
846                 if (RDR_Initialized)
847                     RDR_InvalidateObject(scp->fid.cell, scp->fid.volume, scp->fid.vnode, scp->fid.unique,
848                                           scp->fid.hash, scp->fileType, AFS_INVALIDATE_DELETED);
849                 cm_ReleaseSCache(scp);
850
851                 if (pscp) {
852                     if (cm_HaveCallback(pscp)) {
853                         lock_ObtainWrite(&pscp->rw);
854                         cm_DiscardSCache(pscp);
855                         lock_ReleaseWrite(&pscp->rw);
856
857                         if (RDR_Initialized)
858                             RDR_InvalidateObject(pscp->fid.cell, pscp->fid.volume, pscp->fid.vnode, pscp->fid.unique,
859                                                  pscp->fid.hash, pscp->fileType, AFS_INVALIDATE_EXPIRED);
860
861                     }
862                     cm_ReleaseSCache(pscp);
863                 }
864             }
865         } else {
866             osi_Log0(afsd_logp, "cm_Analyze passed VNOVNODE unknown fid.");
867         }
868     }
869
870     /* RX codes */
871     else if (errorCode == RX_CALL_TIMEOUT) {
872         /* RPC took longer than hardDeadTime or the server
873          * reported idle for longer than idleDeadTime
874          * don't mark server as down but don't retry
875          * this is to prevent the SMB session from timing out
876          * In addition, we log an event to the event log
877          */
878
879         if (serverp) {
880             sprintf(addr, "%d.%d.%d.%d",
881                     ((serverp->addr.sin_addr.s_addr & 0xff)),
882                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
883                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
884                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
885
886             LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_HARD_DEAD_TIME_EXCEEDED, addr);
887             osi_Log1(afsd_logp, "cm_Analyze: hardDeadTime or idleDeadtime exceeded addr[%s]",
888                      osi_LogSaveString(afsd_logp,addr));
889             reqp->errorServp = serverp;
890             reqp->idleError++;
891         }
892
893         if (fidp && storeOp)
894             scp = cm_FindSCache(fidp);
895         if (scp) {
896             if (cm_HaveCallback(scp)) {
897                 lock_ObtainWrite(&scp->rw);
898                 cm_DiscardSCache(scp);
899                 lock_ReleaseWrite(&scp->rw);
900
901                 /*
902                 * We really should notify the redirector that we discarded
903                 * the status information but doing so in this case is not
904                 * safe as it can result in a deadlock with extent release
905                 * processing.
906                 */
907             }
908             cm_ReleaseSCache(scp);
909         }
910
911         if (timeLeft > 2) {
912             if (!fidp) { /* vldb */
913                 retry = 1;
914             } else { /* file */
915                 cm_volume_t *volp = cm_GetVolumeByFID(fidp);
916                 if (volp) {
917                     if (fidp->volume == cm_GetROVolumeID(volp))
918                         retry = 1;
919                     cm_PutVolume(volp);
920                 }
921             }
922         }
923     }
924     else if (errorCode == RX_MSGSIZE) {
925         /*
926          * RPC failed because a transmitted rx packet
927          * may have grown larger than the path mtu.
928          * Force a retry and the Rx library will try
929          * with a smaller mtu size.
930          */
931
932         if (serverp)
933             sprintf(addr, "%d.%d.%d.%d",
934                     ((serverp->addr.sin_addr.s_addr & 0xff)),
935                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
936                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
937                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
938
939         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_MSGSIZE_EXCEEDED, addr);
940         osi_Log1(afsd_logp, "cm_Analyze: Path MTU may have been exceeded addr[%s]",
941                  osi_LogSaveString(afsd_logp,addr));
942
943         retry = 1;
944     }
945     else if (errorCode == RX_CALL_BUSY) {
946         /*
947          * RPC failed because the selected call channel
948          * is currently busy on the server.  Unconditionally
949          * retry the request so an alternate call channel can be used.
950          */
951         if (serverp)
952             sprintf(addr, "%d.%d.%d.%d",
953                     ((serverp->addr.sin_addr.s_addr & 0xff)),
954                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
955                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
956                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
957
958         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_BUSY_CALL_CHANNEL, addr);
959         osi_Log1(afsd_logp, "cm_Analyze: Retry RPC due to busy call channel addr[%s]",
960                  osi_LogSaveString(afsd_logp,addr));
961         retry = 1;
962     }
963     else if (errorCode == VNOSERVICE) {
964         /*
965          * The server did not service the RPC.
966          * If this was a file server RPC it means that for at
967          * least the file server's idle dead timeout period the
968          * file server did not receive any new data packets from
969          * client.
970          *
971          * The RPC was not serviced so it can be retried and any
972          * existing status information is still valid.
973          */
974         if (fidp) {
975             if (serverp)
976                 sprintf(addr, "%d.%d.%d.%d",
977                         ((serverp->addr.sin_addr.s_addr & 0xff)),
978                         ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
979                         ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
980                         ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
981
982             LogEvent(EVENTLOG_WARNING_TYPE, MSG_SERVER_REPORTS_VNOSERVICE,
983                      addr, fidp->volume, cellp->name);
984             osi_Log3(afsd_logp, "Server %s reported rpc to volume %d in cell %s as not serviced.",
985                      osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
986         }
987
988         if (timeLeft > 2)
989             retry = 1;
990     }
991     else if (errorCode == RX_CALL_IDLE) {
992         /*
993          * RPC failed because the server failed to respond with data
994          * within the idle dead timeout period.  This could be for a variety
995          * of reasons:
996          *  1. The server could have a bad partition such as a failed
997          *     disk or iSCSI target and all I/O to that partition is
998          *     blocking on the server and will never complete.
999          *
1000          *  2. The server vnode may be locked by another client request
1001          *     that is taking a very long time.
1002          *
1003          *  3. The server may have a very long queue of requests
1004          *     pending and is unable to process this request.
1005          *
1006          *  4. The server could be malicious and is performing a denial
1007          *     of service attack against the client.
1008          *
1009          * If this is a request against a .readonly with alternate sites
1010          * the server should be marked down for this request and the
1011          * client should fail over to another server.  If this is a
1012          * request against a single source, the client may retry once.
1013          */
1014         if (serverp)
1015             sprintf(addr, "%d.%d.%d.%d",
1016                     ((serverp->addr.sin_addr.s_addr & 0xff)),
1017                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
1018                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
1019                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
1020
1021         if (fidp) {
1022             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
1023                                      CM_GETVOL_FLAG_NO_LRU_UPDATE,
1024                                      &volp);
1025             if (code == 0) {
1026                 statep = cm_VolumeStateByID(volp, fidp->volume);
1027
1028                 if (statep)
1029                     replicated = (statep->flags & CM_VOL_STATE_FLAG_REPLICATED);
1030
1031                 lock_ObtainRead(&cm_volumeLock);
1032                 cm_PutVolume(volp);
1033                 lock_ReleaseRead(&cm_volumeLock);
1034                 volp = NULL;
1035             }
1036
1037             if (storeOp)
1038                 scp = cm_FindSCache(fidp);
1039             if (scp) {
1040                 if (cm_HaveCallback(scp)) {
1041                     lock_ObtainWrite(&scp->rw);
1042                     cm_DiscardSCache(scp);
1043                     lock_ReleaseWrite(&scp->rw);
1044
1045                     /*
1046                      * We really should notify the redirector that we discarded
1047                      * the status information but doing so in this case is not
1048                      * safe as it can result in a deadlock with extent release
1049                      * processing.
1050                      */
1051                 }
1052                 cm_ReleaseSCache(scp);
1053             }
1054         }
1055
1056         if (replicated && serverp) {
1057             reqp->errorServp = serverp;
1058             reqp->tokenError = errorCode;
1059
1060             if (timeLeft > 2)
1061                 retry = 1;
1062         }
1063
1064         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_IDLE_DEAD_TIMEOUT, addr, retry);
1065         osi_Log2(afsd_logp, "cm_Analyze: RPC failed due to idle dead timeout addr[%s] retry=%u",
1066                  osi_LogSaveString(afsd_logp,addr), retry);
1067     }
1068     else if (errorCode == RX_CALL_DEAD) {
1069         /* mark server as down */
1070         if (serverp)
1071             sprintf(addr, "%d.%d.%d.%d",
1072                     ((serverp->addr.sin_addr.s_addr & 0xff)),
1073                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
1074                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
1075                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
1076
1077         osi_Log2(afsd_logp, "cm_Analyze: Rx Call Dead addr[%s] forcedNew[%s]",
1078                  osi_LogSaveString(afsd_logp,addr),
1079                  (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
1080
1081         if (serverp) {
1082             if ((reqp->flags & CM_REQ_NEW_CONN_FORCED)) {
1083                 lock_ObtainMutex(&serverp->mx);
1084                 if (!(serverp->flags & CM_SERVERFLAG_DOWN)) {
1085                     _InterlockedOr(&serverp->flags, CM_SERVERFLAG_DOWN);
1086                     serverp->downTime = time(NULL);
1087                 }
1088                 lock_ReleaseMutex(&serverp->mx);
1089             } else {
1090                 reqp->flags |= CM_REQ_NEW_CONN_FORCED;
1091                 forcing_new = 1;
1092                 cm_ForceNewConnections(serverp);
1093             }
1094         }
1095
1096         if (fidp && storeOp)
1097             scp = cm_FindSCache(fidp);
1098         if (scp) {
1099             if (cm_HaveCallback(scp)) {
1100                 lock_ObtainWrite(&scp->rw);
1101                 cm_DiscardSCache(scp);
1102                 lock_ReleaseWrite(&scp->rw);
1103
1104                 /*
1105                 * We really should notify the redirector that we discarded
1106                 * the status information but doing so in this case is not
1107                 * safe as it can result in a deadlock with extent release
1108                 * processing.
1109                 */
1110             }
1111             cm_ReleaseSCache(scp);
1112         }
1113
1114         if ( timeLeft > 2 )
1115             retry = 1;
1116     }
1117     else if (errorCode >= -64 && errorCode < 0) {
1118         /* mark server as down */
1119         if (serverp)
1120             sprintf(addr, "%d.%d.%d.%d",
1121                     ((serverp->addr.sin_addr.s_addr & 0xff)),
1122                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
1123                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
1124                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
1125
1126         osi_Log3(afsd_logp, "cm_Analyze: Rx Misc Error[%d] addr[%s] forcedNew[%s]",
1127                  errorCode,
1128                  osi_LogSaveString(afsd_logp,addr),
1129                  (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
1130
1131         if (serverp) {
1132             if (reqp->flags & CM_REQ_NEW_CONN_FORCED) {
1133                 reqp->errorServp = serverp;
1134                 reqp->tokenError = errorCode;
1135             } else {
1136                 reqp->flags |= CM_REQ_NEW_CONN_FORCED;
1137                 forcing_new = 1;
1138                 cm_ForceNewConnections(serverp);
1139             }
1140
1141             if ( timeLeft > 2 )
1142                 retry = 1;
1143         }
1144     }
1145     else if (errorCode == RXKADEXPIRED) {
1146         osi_Log1(afsd_logp, "cm_Analyze: rxkad error code 0x%x (RXKADEXPIRED)",
1147                  errorCode);
1148         if (!dead_session) {
1149             lock_ObtainMutex(&userp->mx);
1150             ucellp = cm_GetUCell(userp, cellp);
1151             if (ucellp->ticketp) {
1152                 free(ucellp->ticketp);
1153                 ucellp->ticketp = NULL;
1154             }
1155             _InterlockedAnd(&ucellp->flags, ~CM_UCELLFLAG_RXKAD);
1156             ucellp->gen++;
1157             lock_ReleaseMutex(&userp->mx);
1158             if ( timeLeft > 2 )
1159                 retry = 1;
1160         }
1161     } else if (errorCode >= ERROR_TABLE_BASE_RXK && errorCode < ERROR_TABLE_BASE_RXK + 256) {
1162         char * s = "unknown error";
1163         switch ( errorCode ) {
1164         case RXKADINCONSISTENCY: s = "RXKADINCONSISTENCY"; break;
1165         case RXKADPACKETSHORT  : s = "RXKADPACKETSHORT";   break;
1166         case RXKADLEVELFAIL    : s = "RXKADLEVELFAIL";     break;
1167         case RXKADTICKETLEN    : s = "RXKADTICKETLEN";     break;
1168         case RXKADOUTOFSEQUENCE: s = "RXKADOUTOFSEQUENCE"; break;
1169         case RXKADNOAUTH       : s = "RXKADNOAUTH";        break;
1170         case RXKADBADKEY       : s = "RXKADBADKEY";        break;
1171         case RXKADBADTICKET    : s = "RXKADBADTICKET";     break;
1172         case RXKADUNKNOWNKEY   : s = "RXKADUNKNOWNKEY";    break;
1173         case RXKADEXPIRED      : s = "RXKADEXPIRED";       break;
1174         case RXKADSEALEDINCON  : s = "RXKADSEALEDINCON";   break;
1175         case RXKADDATALEN      : s = "RXKADDATALEN";       break;
1176         case RXKADILLEGALLEVEL : s = "RXKADILLEGALLEVEL";  break;
1177         }
1178         osi_Log2(afsd_logp, "cm_Analyze: rxkad error code 0x%x (%s)",
1179                   errorCode, s);
1180
1181         if (serverp) {
1182             reqp->errorServp = serverp;
1183             reqp->tokenError = errorCode;
1184             retry = 1;
1185         }
1186     } else if (errorCode >= ERROR_TABLE_BASE_U && errorCode < ERROR_TABLE_BASE_U + 256) {
1187         /*
1188          * We received a ubik error.  its possible that the server we are
1189          * communicating with has a corrupted database or is partitioned
1190          * from the rest of the servers and another server might be able
1191          * to answer our query.  Therefore, we will retry the request
1192          * and force the use of another server.
1193          */
1194         if (serverp) {
1195             reqp->errorServp = serverp;
1196             reqp->tokenError = errorCode;
1197             retry = 1;
1198         }
1199     } else if (errorCode == VICECONNBAD || errorCode == VICETOKENDEAD) {
1200         cm_ForceNewConnections(serverp);
1201         if ( timeLeft > 2 )
1202             retry = 1;
1203     } else {
1204         if (errorCode) {
1205             char * s = "unknown error";
1206             switch ( errorCode ) {
1207             case VSALVAGE          : s = "VSALVAGE";           break;
1208             case VNOVNODE          : s = "VNOVNODE";           break;
1209             case VNOVOL            : s = "VNOVOL";             break;
1210             case VVOLEXISTS        : s = "VVOLEXISTS";         break;
1211             case VNOSERVICE        : s = "VNOSERVICE";         break;
1212             case VOFFLINE          : s = "VOFFLINE";           break;
1213             case VONLINE           : s = "VONLINE";            break;
1214             case VDISKFULL         : s = "VDISKFULL";          break;
1215             case VOVERQUOTA        : s = "VOVERQUOTA";         break;
1216             case VBUSY             : s = "VBUSY";              break;
1217             case VMOVED            : s = "VMOVED";             break;
1218             case VIO               : s = "VIO";                break;
1219             case VRESTRICTED       : s = "VRESTRICTED";        break;
1220             case VRESTARTING       : s = "VRESTARTING";        break;
1221             case VREADONLY         : s = "VREADONLY";          break;
1222             case EAGAIN            : s = "EAGAIN";             break;
1223             case UAEAGAIN          : s = "UAEAGAIN";           break;
1224             case EINVAL            : s = "EINVAL";             break;
1225             case UAEINVAL          : s = "UAEINVAL";           break;
1226             case EACCES            : s = "EACCES";             break;
1227             case UAEACCES          : s = "UAEACCES";           break;
1228             case ENOENT            : s = "ENOENT";             break;
1229             case UAENOENT          : s = "UAENOENT";           break;
1230             case EEXIST            : s = "EEXIST";             break;
1231             case UAEEXIST          : s = "UAEEXIST";           break;
1232             case VICECONNBAD       : s = "VICECONNBAD";        break;
1233             case VICETOKENDEAD     : s = "VICETOKENDEAD";      break;
1234             case WSAEWOULDBLOCK    : s = "WSAEWOULDBLOCK";     break;
1235             case UAEWOULDBLOCK     : s = "UAEWOULDBLOCK";      break;
1236             case VL_IDEXIST        : s = "VL_IDEXIST";         break;
1237             case VL_IO             : s = "VL_IO";              break;
1238             case VL_NAMEEXIST      : s = "VL_NAMEEXIST";       break;
1239             case VL_CREATEFAIL     : s = "VL_CREATEFAIL";      break;
1240             case VL_NOENT          : s = "VL_NOENT";           break;
1241             case VL_EMPTY          : s = "VL_EMPTY";           break;
1242             case VL_ENTDELETED     : s = "VL_ENTDELETED";      break;
1243             case VL_BADNAME        : s = "VL_BADNAME";         break;
1244             case VL_BADINDEX       : s = "VL_BADINDEX";        break;
1245             case VL_BADVOLTYPE     : s = "VL_BADVOLTYPE";      break;
1246             case VL_BADSERVER      : s = "VL_BADSERVER";       break;
1247             case VL_BADPARTITION   : s = "VL_BADPARTITION";    break;
1248             case VL_REPSFULL       : s = "VL_REPSFULL";        break;
1249             case VL_NOREPSERVER    : s = "VL_NOREPSERVER";     break;
1250             case VL_DUPREPSERVER   : s = "VL_DUPREPSERVER";    break;
1251             case VL_RWNOTFOUND     : s = "VL_RWNOTFOUND";      break;
1252             case VL_BADREFCOUNT    : s = "VL_BADREFCOUNT";     break;
1253             case VL_SIZEEXCEEDED   : s = "VL_SIZEEXCEEDED";    break;
1254             case VL_BADENTRY       : s = "VL_BADENTRY";        break;
1255             case VL_BADVOLIDBUMP   : s = "VL_BADVOLIDBUMP";    break;
1256             case VL_IDALREADYHASHED: s = "VL_IDALREADYHASHED"; break;
1257             case VL_ENTRYLOCKED    : s = "VL_ENTRYLOCKED";     break;
1258             case VL_BADVOLOPER     : s = "VL_BADVOLOPER";      break;
1259             case VL_BADRELLOCKTYPE : s = "VL_BADRELLOCKTYPE";  break;
1260             case VL_RERELEASE      : s = "VL_RERELEASE";       break;
1261             case VL_BADSERVERFLAG  : s = "VL_BADSERVERFLAG";   break;
1262             case VL_PERM           : s = "VL_PERM";            break;
1263             case VL_NOMEM          : s = "VL_NOMEM";           break;
1264             case VL_BADVERSION     : s = "VL_BADVERSION";      break;
1265             case VL_INDEXERANGE    : s = "VL_INDEXERANGE";     break;
1266             case VL_MULTIPADDR     : s = "VL_MULTIPADDR";      break;
1267             case VL_BADMASK        : s = "VL_BADMASK";         break;
1268             case CM_ERROR_NOSUCHCELL        : s = "CM_ERROR_NOSUCHCELL";         break;
1269             case CM_ERROR_NOSUCHVOLUME      : s = "CM_ERROR_NOSUCHVOLUME";       break;
1270             case CM_ERROR_NOACCESS          : s = "CM_ERROR_NOACCESS";           break;
1271             case CM_ERROR_NOSUCHFILE        : s = "CM_ERROR_NOSUCHFILE";         break;
1272             case CM_ERROR_STOPNOW           : s = "CM_ERROR_STOPNOW";            break;
1273             case CM_ERROR_TOOBIG            : s = "CM_ERROR_TOOBIG";             break;
1274             case CM_ERROR_INVAL             : s = "CM_ERROR_INVAL";              break;
1275             case CM_ERROR_BADFD             : s = "CM_ERROR_BADFD";              break;
1276             case CM_ERROR_BADFDOP           : s = "CM_ERROR_BADFDOP";            break;
1277             case CM_ERROR_EXISTS            : s = "CM_ERROR_EXISTS";             break;
1278             case CM_ERROR_CROSSDEVLINK      : s = "CM_ERROR_CROSSDEVLINK";       break;
1279             case CM_ERROR_BADOP             : s = "CM_ERROR_BADOP";              break;
1280             case CM_ERROR_BADPASSWORD       : s = "CM_ERROR_BADPASSWORD";        break;
1281             case CM_ERROR_NOTDIR            : s = "CM_ERROR_NOTDIR";             break;
1282             case CM_ERROR_ISDIR             : s = "CM_ERROR_ISDIR";              break;
1283             case CM_ERROR_READONLY          : s = "CM_ERROR_READONLY";           break;
1284             case CM_ERROR_WOULDBLOCK        : s = "CM_ERROR_WOULDBLOCK";         break;
1285             case CM_ERROR_QUOTA             : s = "CM_ERROR_QUOTA";              break;
1286             case CM_ERROR_SPACE             : s = "CM_ERROR_SPACE";              break;
1287             case CM_ERROR_BADSHARENAME      : s = "CM_ERROR_BADSHARENAME";       break;
1288             case CM_ERROR_BADTID            : s = "CM_ERROR_BADTID";             break;
1289             case CM_ERROR_UNKNOWN           : s = "CM_ERROR_UNKNOWN";            break;
1290             case CM_ERROR_NOMORETOKENS      : s = "CM_ERROR_NOMORETOKENS";       break;
1291             case CM_ERROR_NOTEMPTY          : s = "CM_ERROR_NOTEMPTY";           break;
1292             case CM_ERROR_USESTD            : s = "CM_ERROR_USESTD";             break;
1293             case CM_ERROR_REMOTECONN        : s = "CM_ERROR_REMOTECONN";         break;
1294             case CM_ERROR_ATSYS             : s = "CM_ERROR_ATSYS";              break;
1295             case CM_ERROR_NOSUCHPATH        : s = "CM_ERROR_NOSUCHPATH";         break;
1296             case CM_ERROR_CLOCKSKEW         : s = "CM_ERROR_CLOCKSKEW";          break;
1297             case CM_ERROR_BADSMB            : s = "CM_ERROR_BADSMB";             break;
1298             case CM_ERROR_ALLBUSY           : s = "CM_ERROR_ALLBUSY";            break;
1299             case CM_ERROR_NOFILES           : s = "CM_ERROR_NOFILES";            break;
1300             case CM_ERROR_PARTIALWRITE      : s = "CM_ERROR_PARTIALWRITE";       break;
1301             case CM_ERROR_NOIPC             : s = "CM_ERROR_NOIPC";              break;
1302             case CM_ERROR_BADNTFILENAME     : s = "CM_ERROR_BADNTFILENAME";      break;
1303             case CM_ERROR_BUFFERTOOSMALL    : s = "CM_ERROR_BUFFERTOOSMALL";     break;
1304             case CM_ERROR_RENAME_IDENTICAL  : s = "CM_ERROR_RENAME_IDENTICAL";   break;
1305             case CM_ERROR_ALLOFFLINE        : s = "CM_ERROR_ALLOFFLINE";         break;
1306             case CM_ERROR_AMBIGUOUS_FILENAME: s = "CM_ERROR_AMBIGUOUS_FILENAME"; break;
1307             case CM_ERROR_BADLOGONTYPE      : s = "CM_ERROR_BADLOGONTYPE";       break;
1308             case CM_ERROR_GSSCONTINUE       : s = "CM_ERROR_GSSCONTINUE";        break;
1309             case CM_ERROR_TIDIPC            : s = "CM_ERROR_TIDIPC";             break;
1310             case CM_ERROR_TOO_MANY_SYMLINKS : s = "CM_ERROR_TOO_MANY_SYMLINKS";  break;
1311             case CM_ERROR_PATH_NOT_COVERED  : s = "CM_ERROR_PATH_NOT_COVERED";   break;
1312             case CM_ERROR_LOCK_CONFLICT     : s = "CM_ERROR_LOCK_CONFLICT";      break;
1313             case CM_ERROR_SHARING_VIOLATION : s = "CM_ERROR_SHARING_VIOLATION";  break;
1314             case CM_ERROR_ALLDOWN           : s = "CM_ERROR_ALLDOWN";            break;
1315             case CM_ERROR_TOOFEWBUFS        : s = "CM_ERROR_TOOFEWBUFS";         break;
1316             case CM_ERROR_TOOMANYBUFS       : s = "CM_ERROR_TOOMANYBUFS";        break;
1317             case UAEIO                      : s = "UAEIO";                       break;
1318             case EIO                        : s = "EIO";                         break;
1319             }
1320             osi_Log2(afsd_logp, "cm_Analyze: ignoring error code 0x%x (%s)",
1321                      errorCode, s);
1322             retry = 0;
1323         }
1324     }
1325
1326     /* If not allowed to retry, don't */
1327     if (dead_session ||
1328         !forcing_new && (reqp->flags & CM_REQ_NORETRY) &&
1329         !(errorCode > -64 && errorCode <= RX_INVALID_OPERATION))
1330         retry = 0;
1331
1332     /* drop this on the way out */
1333     if (connp)
1334         cm_PutConn(connp);
1335
1336     /*
1337      * clear the volume updated flag if we succeed.
1338      * this way the flag will not prevent a subsequent volume
1339      * from being updated if necessary.
1340      */
1341     if (errorCode == 0)
1342     {
1343         reqp->flags &= ~CM_REQ_VOLUME_UPDATED;
1344     }
1345
1346     if ( serversp &&
1347          errorCode != VBUSY &&
1348          errorCode != VRESTARTING &&
1349          errorCode != CM_ERROR_ALLBUSY)
1350     {
1351         cm_ResetServerBusyStatus(serversp);
1352     }
1353
1354     /* retry until we fail to find a connection */
1355     return retry;
1356 }
1357
1358 long cm_ConnByMServers(cm_serverRef_t *serversp, afs_uint32 replicated, cm_user_t *usersp,
1359                        cm_req_t *reqp, cm_conn_t **connpp)
1360 {
1361     long code;
1362     cm_serverRef_t *tsrp;
1363     cm_server_t *tsp;
1364     long firstError = 0;
1365     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1, allDeleted = 1;
1366 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1367     long timeUsed, timeLeft, hardTimeLeft;
1368 #endif
1369     *connpp = NULL;
1370
1371     if (serversp == NULL) {
1372         osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", CM_ERROR_EMPTY);
1373         return CM_ERROR_EMPTY;
1374     }
1375
1376 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1377     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
1378
1379     /* leave 5 seconds margin of safety */
1380     timeLeft =  ConnDeadtimeout - timeUsed - 5;
1381     hardTimeLeft = HardDeadtimeout - timeUsed - 5;
1382 #endif
1383
1384     lock_ObtainRead(&cm_serverLock);
1385     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
1386         if (tsrp->status == srv_deleted)
1387             continue;
1388
1389         allDeleted = 0;
1390
1391         tsp = tsrp->server;
1392         if (reqp->errorServp) {
1393             /*
1394              * search the list until we find the server
1395              * that failed last time.  When we find it
1396              * clear the error, skip it and try the next one
1397              * in the list.
1398              */
1399             if (tsp == reqp->errorServp)
1400                 reqp->errorServp = NULL;
1401             continue;
1402         }
1403         if (tsp) {
1404             cm_GetServerNoLock(tsp);
1405             lock_ReleaseRead(&cm_serverLock);
1406             if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1407                 allDown = 0;
1408                 if (tsrp->status == srv_busy) {
1409                     allOffline = 0;
1410                     someBusy = 1;
1411                 } else if (tsrp->status == srv_offline) {
1412                     allBusy = 0;
1413                     someOffline = 1;
1414                 } else {
1415                     allOffline = 0;
1416                     allBusy = 0;
1417                     code = cm_ConnByServer(tsp, usersp, replicated, connpp);
1418                     if (code == 0) {        /* cm_CBS only returns 0 */
1419                         cm_PutServer(tsp);
1420 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1421                         /* Set RPC timeout */
1422                         if (timeLeft > ConnDeadtimeout)
1423                             timeLeft = ConnDeadtimeout;
1424
1425                         if (hardTimeLeft > HardDeadtimeout)
1426                             hardTimeLeft = HardDeadtimeout;
1427
1428                         lock_ObtainMutex(&(*connpp)->mx);
1429                         rx_SetConnDeadTime((*connpp)->rxconnp, timeLeft);
1430                         rx_SetConnHardDeadTime((*connpp)->rxconnp, (u_short) hardTimeLeft);
1431                         lock_ReleaseMutex(&(*connpp)->mx);
1432 #endif
1433                         return 0;
1434                     }
1435
1436                     /* therefore, this code is never executed */
1437                     if (firstError == 0)
1438                         firstError = code;
1439                 }
1440             }
1441             lock_ObtainRead(&cm_serverLock);
1442             cm_PutServerNoLock(tsp);
1443         }
1444     }
1445     lock_ReleaseRead(&cm_serverLock);
1446
1447     if (firstError == 0) {
1448         if (allDeleted) {
1449             firstError = CM_ERROR_EMPTY;
1450         } else if (allDown) {
1451             firstError = (reqp->tokenError ? reqp->tokenError :
1452                           (reqp->idleError ? RX_CALL_TIMEOUT : CM_ERROR_ALLDOWN));
1453             /*
1454              * if we experienced either a token error or and idle dead time error
1455              * and now all of the servers are down, we have either tried them
1456              * all or lost connectivity.  Clear the error we are returning so
1457              * we will not return it indefinitely if the request is retried.
1458              */
1459             reqp->idleError = reqp->tokenError = 0;
1460         } else if (allBusy) {
1461             firstError = CM_ERROR_ALLBUSY;
1462         } else if (allOffline || (someBusy && someOffline)) {
1463             firstError = CM_ERROR_ALLOFFLINE;
1464         } else {
1465             osi_Log0(afsd_logp, "cm_ConnByMServers returning impossible error TIMEDOUT");
1466             firstError = CM_ERROR_TIMEDOUT;
1467         }
1468     }
1469
1470     osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", firstError);
1471     return firstError;
1472 }
1473
1474 /* called with a held server to GC all bad connections hanging off of the server */
1475 void cm_GCConnections(cm_server_t *serverp)
1476 {
1477     cm_conn_t *tcp;
1478     cm_conn_t **lcpp;
1479     cm_user_t *userp;
1480
1481     lock_ObtainWrite(&cm_connLock);
1482     lcpp = &serverp->connsp;
1483     for (tcp = *lcpp; tcp; tcp = *lcpp) {
1484         userp = tcp->userp;
1485         if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
1486             /* do the deletion of this guy */
1487             cm_PutServer(tcp->serverp);
1488             cm_ReleaseUser(userp);
1489             *lcpp = tcp->nextp;
1490             rx_SetConnSecondsUntilNatPing(tcp->rxconnp, 0);
1491             rx_DestroyConnection(tcp->rxconnp);
1492             lock_FinalizeMutex(&tcp->mx);
1493             free(tcp);
1494         }
1495         else {
1496             /* just advance to the next */
1497             lcpp = &tcp->nextp;
1498         }
1499     }
1500     lock_ReleaseWrite(&cm_connLock);
1501 }
1502
1503 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
1504                                cm_server_t *serverp, afs_uint32 replicated)
1505 {
1506     unsigned short port;
1507     int serviceID;
1508     int secIndex;
1509     struct rx_securityClass *secObjp;
1510
1511     port = serverp->addr.sin_port;
1512     switch (serverp->type) {
1513     case CM_SERVER_VLDB:
1514         if (port == 0)
1515             port = htons(7003);
1516         serviceID = 52;
1517         break;
1518     case CM_SERVER_FILE:
1519         if (port == 0)
1520             port = htons(7000);
1521         serviceID = 1;
1522         break;
1523     default:
1524         osi_panic("unknown server type", __FILE__, __LINE__);
1525     }
1526
1527     if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
1528         secIndex = 2;
1529         switch (cryptall) {
1530         case 0:
1531             tcp->cryptlevel = rxkad_clear;
1532             break;
1533         case 2:
1534             tcp->cryptlevel = rxkad_auth;
1535             break;
1536         default:
1537             tcp->cryptlevel = rxkad_crypt;
1538         }
1539         secObjp = rxkad_NewClientSecurityObject(tcp->cryptlevel,
1540                                                 &ucellp->sessionKey, ucellp->kvno,
1541                                                 ucellp->ticketLen, ucellp->ticketp);
1542     } else {
1543         /* normal auth */
1544         secIndex = 0;
1545         tcp->cryptlevel = rxkad_clear;
1546         secObjp = rxnull_NewClientSecurityObject();
1547     }
1548     osi_assertx(secObjp != NULL, "null rx_securityClass");
1549     tcp->rxconnp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
1550                                     port,
1551                                     serviceID,
1552                                     secObjp,
1553                                     secIndex);
1554     rx_SetConnDeadTime(tcp->rxconnp, ConnDeadtimeout);
1555     rx_SetConnHardDeadTime(tcp->rxconnp, HardDeadtimeout);
1556
1557     /*
1558      * Setting idle dead timeout to a non-zero value activates RX_CALL_IDLE errors
1559      */
1560     if (replicated) {
1561         tcp->flags &= CM_CONN_FLAG_REPLICATION;
1562         rx_SetConnIdleDeadTime(tcp->rxconnp, ReplicaIdleDeadtimeout);
1563     } else {
1564         rx_SetConnIdleDeadTime(tcp->rxconnp, IdleDeadtimeout);
1565     }
1566
1567     /*
1568      * Let the Rx library know that we can auto-retry if an
1569      * RX_MSGSIZE error is returned.
1570      */
1571     if (rx_pmtu_discovery)
1572         rx_SetMsgsizeRetryErr(tcp->rxconnp, RX_MSGSIZE);
1573
1574     /*
1575      * Attempt to limit NAT pings to the anonymous file server connections.
1576      * Only file servers implement client callbacks and we only need one ping
1577      * to be sent to each server.
1578      */
1579     if (NatPingInterval && serverp->type == CM_SERVER_FILE &&
1580          (ucellp->flags & CM_UCELLFLAG_ROOTUSER)) {
1581         rx_SetConnSecondsUntilNatPing(tcp->rxconnp, NatPingInterval);
1582     }
1583
1584     tcp->ucgen = ucellp->gen;
1585     if (secObjp)
1586         rxs_Release(secObjp);   /* Decrement the initial refCount */
1587 }
1588
1589 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, afs_uint32 replicated, cm_conn_t **connpp)
1590 {
1591     cm_conn_t *tcp;
1592     cm_ucell_t *ucellp;
1593
1594     *connpp = NULL;
1595
1596     if (cm_anonvldb && serverp->type == CM_SERVER_VLDB)
1597         userp = cm_rootUserp;
1598
1599     lock_ObtainMutex(&userp->mx);
1600     lock_ObtainRead(&cm_connLock);
1601     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1602         if (tcp->userp == userp &&
1603             (replicated && (tcp->flags & CM_CONN_FLAG_REPLICATION) ||
1604              !replicated && !(tcp->flags & CM_CONN_FLAG_REPLICATION)))
1605             break;
1606     }
1607
1608     /* find ucell structure */
1609     ucellp = cm_GetUCell(userp, serverp->cellp);
1610     if (!tcp) {
1611         lock_ConvertRToW(&cm_connLock);
1612         for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1613             if (tcp->userp == userp)
1614                 break;
1615         }
1616         if (tcp) {
1617             InterlockedIncrement(&tcp->refCount);
1618             lock_ReleaseWrite(&cm_connLock);
1619             goto haveconn;
1620         }
1621         cm_GetServer(serverp);
1622         tcp = malloc(sizeof(*tcp));
1623         memset(tcp, 0, sizeof(*tcp));
1624         cm_HoldUser(userp);
1625         tcp->userp = userp;
1626         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex", LOCK_HIERARCHY_CONN);
1627         tcp->serverp = serverp;
1628         tcp->cryptlevel = rxkad_clear;
1629         cm_NewRXConnection(tcp, ucellp, serverp, replicated);
1630         tcp->refCount = 1;
1631         tcp->nextp = serverp->connsp;
1632         serverp->connsp = tcp;
1633         lock_ReleaseWrite(&cm_connLock);
1634         lock_ReleaseMutex(&userp->mx);
1635     } else {
1636         InterlockedIncrement(&tcp->refCount);
1637         lock_ReleaseRead(&cm_connLock);
1638       haveconn:
1639         lock_ReleaseMutex(&userp->mx);
1640
1641         lock_ObtainMutex(&tcp->mx);
1642         if ((tcp->flags & CM_CONN_FLAG_FORCE_NEW) ||
1643             (tcp->ucgen < ucellp->gen) ||
1644             (tcp->cryptlevel != (ucellp->flags & CM_UCELLFLAG_RXKAD ? (cryptall == 1 ? rxkad_crypt : (cryptall == 2 ? rxkad_auth : rxkad_clear)) : rxkad_clear)))
1645         {
1646             if (tcp->ucgen < ucellp->gen)
1647                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to token update");
1648             else
1649                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to crypt change");
1650             tcp->flags &= ~CM_CONN_FLAG_FORCE_NEW;
1651             rx_SetConnSecondsUntilNatPing(tcp->rxconnp, 0);
1652             rx_DestroyConnection(tcp->rxconnp);
1653             cm_NewRXConnection(tcp, ucellp, serverp, replicated);
1654         }
1655         lock_ReleaseMutex(&tcp->mx);
1656     }
1657
1658     /* return this pointer to our caller */
1659     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%p", tcp);
1660     *connpp = tcp;
1661
1662     return 0;
1663 }
1664
1665 long cm_ServerAvailable(struct cm_fid *fidp, struct cm_user *userp)
1666 {
1667     long code;
1668     cm_req_t req;
1669     cm_serverRef_t **serverspp;
1670     cm_serverRef_t *tsrp;
1671     cm_server_t *tsp;
1672     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
1673     afs_uint32 replicated;
1674
1675     cm_InitReq(&req);
1676
1677     code = cm_GetServerList(fidp, userp, &req, &replicated, &serverspp);
1678     if (code)
1679         return 0;
1680
1681     lock_ObtainRead(&cm_serverLock);
1682     for (tsrp = *serverspp; tsrp; tsrp=tsrp->next) {
1683         if (tsrp->status == srv_deleted)
1684             continue;
1685         tsp = tsrp->server;
1686         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1687             allDown = 0;
1688             if (tsrp->status == srv_busy) {
1689                 allOffline = 0;
1690                 someBusy = 1;
1691             } else if (tsrp->status == srv_offline) {
1692                 allBusy = 0;
1693                 someOffline = 1;
1694             } else {
1695                 allOffline = 0;
1696                 allBusy = 0;
1697             }
1698         }
1699     }
1700     lock_ReleaseRead(&cm_serverLock);
1701     cm_FreeServerList(serverspp, 0);
1702
1703     if (allDown)
1704         return 0;
1705     else if (allBusy)
1706         return 0;
1707     else if (allOffline || (someBusy && someOffline))
1708         return 0;
1709     else
1710         return 1;
1711 }
1712
1713 /*
1714  * The returned cm_conn_t ** object is released in the subsequent call
1715  * to cm_Analyze().
1716  */
1717 long cm_ConnFromFID(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
1718                     cm_conn_t **connpp)
1719 {
1720     long code;
1721     cm_serverRef_t **serverspp;
1722     afs_uint32 replicated;
1723
1724     *connpp = NULL;
1725
1726     code = cm_GetServerList(fidp, userp, reqp, &replicated, &serverspp);
1727     if (code)
1728         return code;
1729
1730     code = cm_ConnByMServers(*serverspp, replicated, userp, reqp, connpp);
1731     cm_FreeServerList(serverspp, 0);
1732     return code;
1733 }
1734
1735
1736 long cm_ConnFromVolume(struct cm_volume *volp, unsigned long volid, struct cm_user *userp, cm_req_t *reqp,
1737                        cm_conn_t **connpp)
1738 {
1739     long code;
1740     cm_serverRef_t **serverspp;
1741     afs_uint32 replicated;
1742
1743     *connpp = NULL;
1744
1745     code = cm_GetVolServerList(volp, volid, userp, reqp, &replicated, &serverspp);
1746     if (code)
1747         return code;
1748
1749     code = cm_ConnByMServers(*serverspp, replicated, userp, reqp, connpp);
1750     cm_FreeServerList(serverspp, 0);
1751     return code;
1752 }
1753
1754
1755 extern struct rx_connection *
1756 cm_GetRxConn(cm_conn_t *connp)
1757 {
1758     struct rx_connection * rxconnp;
1759     lock_ObtainMutex(&connp->mx);
1760     rxconnp = connp->rxconnp;
1761     rx_GetConnection(rxconnp);
1762     lock_ReleaseMutex(&connp->mx);
1763     return rxconnp;
1764 }
1765
1766 void cm_ForceNewConnections(cm_server_t *serverp)
1767 {
1768     cm_conn_t *tcp;
1769
1770     lock_ObtainWrite(&cm_connLock);
1771     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1772         lock_ObtainMutex(&tcp->mx);
1773         tcp->flags |= CM_CONN_FLAG_FORCE_NEW;
1774         lock_ReleaseMutex(&tcp->mx);
1775     }
1776     lock_ReleaseWrite(&cm_connLock);
1777 }