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