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