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