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