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