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