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