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