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