2134a96e18947dd21460b9b78983ed6652ca1724
[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                 if (timeLeft > 7) {
355                     thrd_Sleep(5000);
356
357                     /* cm_CheckOfflineVolume() resets the serverRef state */
358                     if (cm_CheckOfflineVolume(volp, fidp->volume))
359                         retry = 1;
360                 } else {
361                     cm_UpdateVolumeStatus(volp, fidp->volume);
362                 }
363                 lock_ObtainRead(&cm_volumeLock);
364                 cm_PutVolume(volp);
365                 lock_ReleaseRead(&cm_volumeLock);
366                 volp = NULL;
367             }
368         } else {
369             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE (VL Server)");
370         }
371     }
372     else if (errorCode == CM_ERROR_ALLBUSY) {
373         /* Volumes that are busy cannot be determined to be non-busy 
374          * without actually attempting to access them.
375          */
376         if (fidp) { /* File Server query */
377             osi_Log2(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY (FS cell %s vol 0x%x)",
378                      cellp->name, fidp->volume);
379             msgID = MSG_ALL_SERVERS_BUSY;
380             format = "All servers are busy when accessing cell %s volume %d.";
381             LogEvent(EVENTLOG_WARNING_TYPE, msgID, cellp->name, fidp->volume);
382
383             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, 
384                                      CM_GETVOL_FLAG_NO_LRU_UPDATE, 
385                                      &volp);
386             if (code == 0) {
387                 if (timeLeft > 7) {
388                     thrd_Sleep(5000);
389                     
390                     statep = cm_VolumeStateByID(volp, fidp->volume);
391                     if (statep->state != vl_offline && 
392                          statep->state != vl_busy &&
393                          statep->state != vl_unknown) {
394                         retry = 1;
395                     } else {
396                         if (!serversp) {
397                             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
398                             if (code == 0) {
399                                 serversp = *serverspp;
400                                 free_svr_list = 1;
401                             }
402                         }
403                         lock_ObtainWrite(&cm_serverLock);
404                         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
405                             if (tsrp->status == srv_deleted)
406                                 continue;
407                             if (tsrp->status == srv_busy) {
408                                 tsrp->status = srv_not_busy;
409                             }       
410                         }
411                         lock_ReleaseWrite(&cm_serverLock);
412                         if (free_svr_list) {
413                             cm_FreeServerList(serverspp, 0);
414                             serversp = NULL;
415                             free_svr_list = 0;
416                         }
417
418                         cm_UpdateVolumeStatus(volp, fidp->volume);
419                         retry = 1;
420                     }
421                 } else {
422                     cm_UpdateVolumeStatus(volp, fidp->volume);
423                 }
424
425                 lock_ObtainRead(&cm_volumeLock);
426                 cm_PutVolume(volp);
427                 lock_ReleaseRead(&cm_volumeLock);
428                 volp = NULL;
429             }
430         } else {    /* VL Server query */
431             osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY (VL Server).");
432
433             if (timeLeft > 7) {
434                 thrd_Sleep(5000);
435
436                 if (serversp) {
437                     lock_ObtainWrite(&cm_serverLock);
438                     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
439                         if (tsrp->status == srv_deleted)
440                             continue;
441                         if (tsrp->status == srv_busy) {
442                             tsrp->status = srv_not_busy;
443                         }
444                     }
445                     lock_ReleaseWrite(&cm_serverLock);
446                     retry = 1;
447                 }
448             }
449         }
450     }
451
452     /* special codes:  VBUSY and VRESTARTING */
453     else if (errorCode == VBUSY || errorCode == VRESTARTING) {
454         if (!serversp && fidp) {
455             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
456             if (code == 0) {
457                 serversp = *serverspp;
458                 free_svr_list = 1;
459             }
460         }
461
462         switch ( errorCode ) {
463         case VBUSY:
464             msgID = MSG_SERVER_REPORTS_VBUSY;
465             format = "Server %s reported busy when accessing volume %d in cell %s.";
466             break;
467         case VRESTARTING:
468             msgID = MSG_SERVER_REPORTS_VRESTARTING;
469             format = "Server %s reported restarting when accessing volume %d in cell %s.";
470             break;
471         }
472
473         if (serverp && fidp) {
474             /* Log server being offline for this volume */
475             sprintf(addr, "%d.%d.%d.%d",
476                    ((serverp->addr.sin_addr.s_addr & 0xff)),
477                    ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
478                    ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
479                    ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
480
481             osi_Log3(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
482             LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume, cellp->name);
483         }
484
485         lock_ObtainWrite(&cm_serverLock);
486         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
487             if (tsrp->status == srv_deleted)
488                 continue;
489             if (tsrp->server == serverp && tsrp->status == srv_not_busy) {
490                 tsrp->status = srv_busy;
491                 if (fidp) { /* File Server query */
492                     lock_ReleaseWrite(&cm_serverLock);
493                     code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp, 
494                                              CM_GETVOL_FLAG_NO_LRU_UPDATE, 
495                                              &volp);
496                     if (code == 0)
497                         statep = cm_VolumeStateByID(volp, fidp->volume);
498                     lock_ObtainWrite(&cm_serverLock);
499                 }
500                 break;
501             }
502         }
503         lock_ReleaseWrite(&cm_serverLock);
504         
505         if (statep) {
506             cm_UpdateVolumeStatus(volp, statep->ID);
507             lock_ObtainRead(&cm_volumeLock);
508             cm_PutVolume(volp);
509             lock_ReleaseRead(&cm_volumeLock);
510             volp = NULL;
511         }
512
513         if (free_svr_list) {
514             cm_FreeServerList(serverspp, 0);
515             serversp = NULL;
516             free_svr_list = 0;
517         }
518         retry = 1;
519     }
520
521     /* special codes:  missing volumes */
522     else if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE ||
523              errorCode == VSALVAGE || errorCode == VNOSERVICE || errorCode == VIO) 
524     {       
525         /* In case of timeout */
526         reqp->volumeError = errorCode;
527
528         switch ( errorCode ) {
529         case VNOVOL:
530             msgID = MSG_SERVER_REPORTS_VNOVOL;
531             format = "Server %s reported volume %d in cell %s as not attached (may have been moved or deleted).";
532             break;
533         case VMOVED:
534             msgID = MSG_SERVER_REPORTS_VMOVED;
535             format = "Server %s reported volume %d in cell %s as moved.";
536             break;
537         case VOFFLINE:
538             msgID = MSG_SERVER_REPORTS_VOFFLINE;
539             format = "Server %s reported volume %d in cell %s as offline.";
540             break;
541         case VSALVAGE:
542             msgID = MSG_SERVER_REPORTS_VSALVAGE;
543             format = "Server %s reported volume %d in cell %s as needs salvage.";
544             break;
545         case VNOSERVICE:
546             msgID = MSG_SERVER_REPORTS_VNOSERVICE;
547             format = "Server %s reported volume %d in cell %s as not in service.";
548             break;
549         case VIO:
550             msgID = MSG_SERVER_REPORTS_VIO;
551             format = "Server %s reported volume %d in cell %s as temporarily unaccessible.";
552             break;
553         }
554
555         if (fidp) { /* File Server query */
556             if (serverp) {
557                 /* Log server being unavailable for this volume */
558                 sprintf(addr, "%d.%d.%d.%d",
559                          ((serverp->addr.sin_addr.s_addr & 0xff)),
560                          ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
561                          ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
562                          ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
563
564                 osi_Log3(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume, cellp->name);
565                 LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume, cellp->name);
566             }
567
568             code = cm_FindVolumeByID(cellp, fidp->volume, userp, reqp,
569                                       CM_GETVOL_FLAG_NO_LRU_UPDATE,
570                                       &volp);
571             if (code == 0)
572                 statep = cm_VolumeStateByID(volp, fidp->volume);
573
574             if ((errorCode == VMOVED || errorCode == VNOVOL || errorCode == VOFFLINE) &&
575                 !(reqp->flags & CM_REQ_VOLUME_UPDATED))
576             {
577                 code = cm_ForceUpdateVolume(fidp, userp, reqp);
578                 if (code == 0)
579                     location_updated = 1;
580
581                 /* Even if the update fails, there might still be another replica */
582
583                 reqp->flags |= CM_REQ_VOLUME_UPDATED;
584                 osi_Log3(afsd_logp, "cm_Analyze called cm_ForceUpdateVolume cell %u vol %u code 0x%x",
585                         fidp->cell, fidp->volume, code);
586             }
587
588             if (statep) {
589                 cm_UpdateVolumeStatus(volp, statep->ID);
590                 osi_Log3(afsd_logp, "cm_Analyze NewVolState cell %u vol %u state %u",
591                          fidp->cell, fidp->volume, statep->state);
592             }
593
594             if (volp) {
595                 lock_ObtainRead(&cm_volumeLock);
596                 cm_PutVolume(volp);
597                 lock_ReleaseRead(&cm_volumeLock);
598                 volp = NULL;
599             }
600
601             /*
602              * Mark server offline for this volume or delete the volume
603              * from the server list if it was moved or is not present.
604              */
605             if (!serversp || location_updated) {
606                 code = cm_GetServerList(fidp, userp, reqp, &serverspp);
607                 if (code == 0) {
608                     serversp = *serverspp;
609                     free_svr_list = 1;
610                 }
611             }
612         }
613
614         lock_ObtainWrite(&cm_serverLock);
615         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
616             if (tsrp->status == srv_deleted)
617                 continue;
618
619             sprintf(addr, "%d.%d.%d.%d",
620                      ((tsrp->server->addr.sin_addr.s_addr & 0xff)),
621                      ((tsrp->server->addr.sin_addr.s_addr & 0xff00)>> 8),
622                      ((tsrp->server->addr.sin_addr.s_addr & 0xff0000)>> 16),
623                      ((tsrp->server->addr.sin_addr.s_addr & 0xff000000)>> 24));
624
625             if (cm_ServerEqual(tsrp->server, serverp)) {
626                 /* REDIRECT */
627                 if (errorCode == VMOVED || errorCode == VNOVOL) {
628                     osi_Log2(afsd_logp, "volume %d not present on server %s",
629                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
630                     tsrp->status = srv_deleted;
631                     if (fidp)
632                         cm_RemoveVolumeFromServer(serverp, fidp->volume);
633                 } else {
634                     osi_Log2(afsd_logp, "volume %d instance on server %s marked offline",
635                              fidp->volume, osi_LogSaveString(afsd_logp,addr));
636                     tsrp->status = srv_offline;
637                 }
638                 /* break; */
639             } else {
640                 osi_Log3(afsd_logp, "volume %d exists on server %s with status %u",
641                          fidp->volume, osi_LogSaveString(afsd_logp,addr), tsrp->status);
642             }
643         }
644         lock_ReleaseWrite(&cm_serverLock);
645
646         /* Free the server list before cm_ForceUpdateVolume is called */
647         if (free_svr_list) {
648             cm_FreeServerList(serverspp, 0);
649             serversp = NULL;
650             free_svr_list = 0;
651         }
652
653         if ( timeLeft > 2 )
654             retry = 1;
655     } else if ( errorCode == VNOVNODE ) {
656         if ( fidp ) {
657             cm_scache_t * scp;
658             osi_Log4(afsd_logp, "cm_Analyze passed VNOVNODE cell %u vol %u vn %u uniq %u.",
659                       fidp->cell, fidp->volume, fidp->vnode, fidp->unique);
660
661             scp = cm_FindSCache(fidp);
662             if (scp) {
663                 cm_scache_t *pscp = NULL;
664
665                 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
666                     pscp = cm_FindSCacheParent(scp);
667
668                 lock_ObtainWrite(&scp->rw);
669                 lock_ObtainWrite(&cm_scacheLock);
670                 cm_RemoveSCacheFromHashTable(scp);
671                 lock_ReleaseWrite(&cm_scacheLock);
672                 cm_LockMarkSCacheLost(scp);
673                 scp->flags |= CM_SCACHEFLAG_DELETED;
674                 lock_ReleaseWrite(&scp->rw);
675                 cm_ReleaseSCache(scp);
676
677                 if (pscp) {
678                     if (cm_HaveCallback(pscp)) {
679                         lock_ObtainWrite(&pscp->rw);
680                         cm_DiscardSCache(pscp);
681                         lock_ReleaseWrite(&pscp->rw);
682                     }
683                     cm_ReleaseSCache(pscp);
684                 }
685             }
686         } else {
687             osi_Log0(afsd_logp, "cm_Analyze passed VNOVNODE unknown fid.");
688         }
689     }
690
691     /* RX codes */
692     else if (errorCode == RX_CALL_TIMEOUT) {
693         /* RPC took longer than hardDeadTime or the server
694          * reported idle for longer than idleDeadTime
695          * don't mark server as down but don't retry
696          * this is to prevent the SMB session from timing out
697          * In addition, we log an event to the event log 
698          */
699
700         if (serverp) {
701             sprintf(addr, "%d.%d.%d.%d", 
702                     ((serverp->addr.sin_addr.s_addr & 0xff)),
703                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
704                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
705                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
706
707             LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_HARD_DEAD_TIME_EXCEEDED, addr);
708             osi_Log1(afsd_logp, "cm_Analyze: hardDeadTime or idleDeadtime exceeded addr[%s]",
709                      osi_LogSaveString(afsd_logp,addr));
710             reqp->tokenIdleErrorServp = serverp;
711             reqp->idleError++;
712         }
713
714         if (timeLeft > 2) {
715             if (!fidp) { /* vldb */
716                 retry = 1;
717             } else { /* file */
718                 cm_volume_t *volp = cm_GetVolumeByFID(fidp);
719                 if (volp) {
720                     if (fidp->volume == cm_GetROVolumeID(volp))
721                         retry = 1;
722                     cm_PutVolume(volp);
723                 }
724             }
725         }
726     }
727     else if (errorCode == RX_MSGSIZE) {
728         /*
729          * RPC failed because a transmitted rx packet
730          * may have grown larger than the path mtu.
731          * Force a retry and the Rx library will try
732          * with a smaller mtu size.
733          */
734
735         if (serverp)
736             sprintf(addr, "%d.%d.%d.%d",
737                     ((serverp->addr.sin_addr.s_addr & 0xff)),
738                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
739                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
740                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
741
742         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_MSGSIZE_EXCEEDED, addr);
743         osi_Log1(afsd_logp, "cm_Analyze: Path MTU may have been exceeded addr[%s]",
744                  osi_LogSaveString(afsd_logp,addr));
745
746         retry = 1;
747     }
748     else if (errorCode == CM_RX_RETRY_BUSY_CALL) {
749         /*
750          * RPC failed because the selected call channel
751          * is currently busy on the server.  Unconditionally
752          * retry the request so an alternate call channel can be used.
753          */
754         if (serverp)
755             sprintf(addr, "%d.%d.%d.%d",
756                     ((serverp->addr.sin_addr.s_addr & 0xff)),
757                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
758                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
759                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
760
761         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_BUSY_CALL_CHANNEL, addr);
762         osi_Log1(afsd_logp, "cm_Analyze: Retry RPC due to busy call channel addr[%s]",
763                  osi_LogSaveString(afsd_logp,addr));
764         retry = 1;
765     }
766     else if (errorCode >= -64 && errorCode < 0) {
767         /* mark server as down */
768         if (serverp)
769             sprintf(addr, "%d.%d.%d.%d",
770                     ((serverp->addr.sin_addr.s_addr & 0xff)),
771                     ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
772                     ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
773                     ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24));
774
775         if (errorCode == RX_CALL_DEAD)
776             osi_Log2(afsd_logp, "cm_Analyze: Rx Call Dead addr[%s] forcedNew[%s]",
777                      osi_LogSaveString(afsd_logp,addr), 
778                      (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
779         else
780             osi_Log3(afsd_logp, "cm_Analyze: Rx Misc Error[%d] addr[%s] forcedNew[%s]",
781                      errorCode,
782                      osi_LogSaveString(afsd_logp,addr), 
783                      (reqp->flags & CM_REQ_NEW_CONN_FORCED ? "yes" : "no"));
784
785         if (serverp) {
786             lock_ObtainMutex(&serverp->mx);
787             if (errorCode == RX_CALL_DEAD &&
788                 (reqp->flags & CM_REQ_NEW_CONN_FORCED)) {
789                 if (!(serverp->flags & CM_SERVERFLAG_DOWN)) {
790                     serverp->flags |= CM_SERVERFLAG_DOWN;
791                     serverp->downTime = time(NULL);
792                 }
793             } else {
794                 if (reqp->flags & CM_REQ_NEW_CONN_FORCED) {
795                     reqp->tokenIdleErrorServp = serverp;
796                     reqp->tokenError = errorCode;
797                 } else {
798                     reqp->flags |= CM_REQ_NEW_CONN_FORCED;
799                     forcing_new = 1;
800                 }
801             }
802             lock_ReleaseMutex(&serverp->mx);
803             cm_ForceNewConnections(serverp);
804         }
805         if ( timeLeft > 2 )
806             retry = 1;
807     }
808     else if (errorCode == RXKADEXPIRED) {
809         osi_Log1(afsd_logp, "cm_Analyze: rxkad error code 0x%x (RXKADEXPIRED)",
810                  errorCode);
811         if (!dead_session) {
812             lock_ObtainMutex(&userp->mx);
813             ucellp = cm_GetUCell(userp, serverp->cellp);
814             if (ucellp->ticketp) {
815                 free(ucellp->ticketp);
816                 ucellp->ticketp = NULL;
817             }
818             ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
819             ucellp->gen++;
820             lock_ReleaseMutex(&userp->mx);
821             if ( timeLeft > 2 )
822                 retry = 1;
823         }
824     } else if (errorCode >= ERROR_TABLE_BASE_RXK && errorCode < ERROR_TABLE_BASE_RXK + 256) {
825         char * s = "unknown error";
826         switch ( errorCode ) {
827         case RXKADINCONSISTENCY: s = "RXKADINCONSISTENCY"; break;
828         case RXKADPACKETSHORT  : s = "RXKADPACKETSHORT";   break;
829         case RXKADLEVELFAIL    : s = "RXKADLEVELFAIL";     break;
830         case RXKADTICKETLEN    : s = "RXKADTICKETLEN";     break;
831         case RXKADOUTOFSEQUENCE: s = "RXKADOUTOFSEQUENCE"; break;
832         case RXKADNOAUTH       : s = "RXKADNOAUTH";        break;
833         case RXKADBADKEY       : s = "RXKADBADKEY";        break;
834         case RXKADBADTICKET    : s = "RXKADBADTICKET";     break;
835         case RXKADUNKNOWNKEY   : s = "RXKADUNKNOWNKEY";    break;
836         case RXKADEXPIRED      : s = "RXKADEXPIRED";       break;
837         case RXKADSEALEDINCON  : s = "RXKADSEALEDINCON";   break;
838         case RXKADDATALEN      : s = "RXKADDATALEN";       break;
839         case RXKADILLEGALLEVEL : s = "RXKADILLEGALLEVEL";  break;
840         }
841         osi_Log2(afsd_logp, "cm_Analyze: rxkad error code 0x%x (%s)",
842                   errorCode, s);
843
844         if (serverp) {
845             reqp->tokenIdleErrorServp = serverp;
846             reqp->tokenError = errorCode;
847             retry = 1;
848         }
849     } else if (errorCode >= ERROR_TABLE_BASE_U && errorCode < ERROR_TABLE_BASE_U + 256) {
850         /*
851          * We received a ubik error.  its possible that the server we are
852          * communicating with has a corrupted database or is partitioned
853          * from the rest of the servers and another server might be able
854          * to answer our query.  Therefore, we will retry the request
855          * and force the use of another server.
856          */
857         if (serverp) {
858             reqp->tokenIdleErrorServp = serverp;
859             reqp->tokenError = errorCode;
860             retry = 1;
861         }
862     } else if (errorCode == VICECONNBAD || errorCode == VICETOKENDEAD) {
863         cm_ForceNewConnections(serverp);
864         if ( timeLeft > 2 )
865             retry = 1;
866     } else {
867         if (errorCode) {
868             char * s = "unknown error";
869             switch ( errorCode ) {
870             case VSALVAGE          : s = "VSALVAGE";           break;
871             case VNOVNODE          : s = "VNOVNODE";           break;
872             case VNOVOL            : s = "VNOVOL";             break;
873             case VVOLEXISTS        : s = "VVOLEXISTS";         break;
874             case VNOSERVICE        : s = "VNOSERVICE";         break;
875             case VOFFLINE          : s = "VOFFLINE";           break;
876             case VONLINE           : s = "VONLINE";            break;
877             case VDISKFULL         : s = "VDISKFULL";          break;
878             case VOVERQUOTA        : s = "VOVERQUOTA";         break;
879             case VBUSY             : s = "VBUSY";              break;
880             case VMOVED            : s = "VMOVED";             break;
881             case VIO               : s = "VIO";                break;
882             case VRESTRICTED       : s = "VRESTRICTED";        break;
883             case VRESTARTING       : s = "VRESTARTING";        break;
884             case VREADONLY         : s = "VREADONLY";          break;
885             case EAGAIN            : s = "EAGAIN";             break;
886             case UAEAGAIN          : s = "UAEAGAIN";           break;
887             case EINVAL            : s = "EINVAL";             break;
888             case UAEINVAL          : s = "UAEINVAL";           break;
889             case EACCES            : s = "EACCES";             break;
890             case UAEACCES          : s = "UAEACCES";           break;
891             case ENOENT            : s = "ENOENT";             break;
892             case UAENOENT          : s = "UAENOENT";           break;
893             case EEXIST            : s = "EEXIST";             break;
894             case UAEEXIST          : s = "UAEEXIST";           break;
895             case VICECONNBAD       : s = "VICECONNBAD";        break;
896             case VICETOKENDEAD     : s = "VICETOKENDEAD";      break;
897             case WSAEWOULDBLOCK    : s = "WSAEWOULDBLOCK";     break;
898             case UAEWOULDBLOCK     : s = "UAEWOULDBLOCK";      break;
899             case VL_IDEXIST        : s = "VL_IDEXIST";         break;
900             case VL_IO             : s = "VL_IO";              break;
901             case VL_NAMEEXIST      : s = "VL_NAMEEXIST";       break;
902             case VL_CREATEFAIL     : s = "VL_CREATEFAIL";      break;
903             case VL_NOENT          : s = "VL_NOENT";           break;
904             case VL_EMPTY          : s = "VL_EMPTY";           break;
905             case VL_ENTDELETED     : s = "VL_ENTDELETED";      break;
906             case VL_BADNAME        : s = "VL_BADNAME";         break;
907             case VL_BADINDEX       : s = "VL_BADINDEX";        break;
908             case VL_BADVOLTYPE     : s = "VL_BADVOLTYPE";      break;
909             case VL_BADSERVER      : s = "VL_BADSERVER";       break;
910             case VL_BADPARTITION   : s = "VL_BADPARTITION";    break;
911             case VL_REPSFULL       : s = "VL_REPSFULL";        break;
912             case VL_NOREPSERVER    : s = "VL_NOREPSERVER";     break;
913             case VL_DUPREPSERVER   : s = "VL_DUPREPSERVER";    break;
914             case VL_RWNOTFOUND     : s = "VL_RWNOTFOUND";      break;
915             case VL_BADREFCOUNT    : s = "VL_BADREFCOUNT";     break;
916             case VL_SIZEEXCEEDED   : s = "VL_SIZEEXCEEDED";    break;
917             case VL_BADENTRY       : s = "VL_BADENTRY";        break;
918             case VL_BADVOLIDBUMP   : s = "VL_BADVOLIDBUMP";    break;
919             case VL_IDALREADYHASHED: s = "VL_IDALREADYHASHED"; break;
920             case VL_ENTRYLOCKED    : s = "VL_ENTRYLOCKED";     break;
921             case VL_BADVOLOPER     : s = "VL_BADVOLOPER";      break;
922             case VL_BADRELLOCKTYPE : s = "VL_BADRELLOCKTYPE";  break;
923             case VL_RERELEASE      : s = "VL_RERELEASE";       break;
924             case VL_BADSERVERFLAG  : s = "VL_BADSERVERFLAG";   break;
925             case VL_PERM           : s = "VL_PERM";            break;
926             case VL_NOMEM          : s = "VL_NOMEM";           break;
927             case VL_BADVERSION     : s = "VL_BADVERSION";      break;
928             case VL_INDEXERANGE    : s = "VL_INDEXERANGE";     break;
929             case VL_MULTIPADDR     : s = "VL_MULTIPADDR";      break;
930             case VL_BADMASK        : s = "VL_BADMASK";         break;
931             case CM_ERROR_NOSUCHCELL        : s = "CM_ERROR_NOSUCHCELL";         break;                         
932             case CM_ERROR_NOSUCHVOLUME      : s = "CM_ERROR_NOSUCHVOLUME";       break;                         
933             case CM_ERROR_TIMEDOUT          : s = "CM_ERROR_TIMEDOUT";           break;                 
934             case CM_ERROR_RETRY             : s = "CM_ERROR_RETRY";              break; 
935             case CM_ERROR_NOACCESS          : s = "CM_ERROR_NOACCESS";           break; 
936             case CM_ERROR_NOSUCHFILE        : s = "CM_ERROR_NOSUCHFILE";         break;                         
937             case CM_ERROR_STOPNOW           : s = "CM_ERROR_STOPNOW";            break;                         
938             case CM_ERROR_TOOBIG            : s = "CM_ERROR_TOOBIG";             break;                                 
939             case CM_ERROR_INVAL             : s = "CM_ERROR_INVAL";              break;                                 
940             case CM_ERROR_BADFD             : s = "CM_ERROR_BADFD";              break;                                 
941             case CM_ERROR_BADFDOP           : s = "CM_ERROR_BADFDOP";            break;                         
942             case CM_ERROR_EXISTS            : s = "CM_ERROR_EXISTS";             break;                                 
943             case CM_ERROR_CROSSDEVLINK      : s = "CM_ERROR_CROSSDEVLINK";       break;                         
944             case CM_ERROR_BADOP             : s = "CM_ERROR_BADOP";              break;                                 
945             case CM_ERROR_BADPASSWORD       : s = "CM_ERROR_BADPASSWORD";        break;         
946             case CM_ERROR_NOTDIR            : s = "CM_ERROR_NOTDIR";             break;                                 
947             case CM_ERROR_ISDIR             : s = "CM_ERROR_ISDIR";              break;                                 
948             case CM_ERROR_READONLY          : s = "CM_ERROR_READONLY";           break;                         
949             case CM_ERROR_WOULDBLOCK        : s = "CM_ERROR_WOULDBLOCK";         break;                         
950             case CM_ERROR_QUOTA             : s = "CM_ERROR_QUOTA";              break;                                 
951             case CM_ERROR_SPACE             : s = "CM_ERROR_SPACE";              break;                                 
952             case CM_ERROR_BADSHARENAME      : s = "CM_ERROR_BADSHARENAME";       break;                         
953             case CM_ERROR_BADTID            : s = "CM_ERROR_BADTID";             break;                                 
954             case CM_ERROR_UNKNOWN           : s = "CM_ERROR_UNKNOWN";            break;                         
955             case CM_ERROR_NOMORETOKENS      : s = "CM_ERROR_NOMORETOKENS";       break;                         
956             case CM_ERROR_NOTEMPTY          : s = "CM_ERROR_NOTEMPTY";           break;                         
957             case CM_ERROR_USESTD            : s = "CM_ERROR_USESTD";             break;                                 
958             case CM_ERROR_REMOTECONN        : s = "CM_ERROR_REMOTECONN";         break;                         
959             case CM_ERROR_ATSYS             : s = "CM_ERROR_ATSYS";              break;                                 
960             case CM_ERROR_NOSUCHPATH        : s = "CM_ERROR_NOSUCHPATH";         break;                         
961             case CM_ERROR_CLOCKSKEW         : s = "CM_ERROR_CLOCKSKEW";          break;                         
962             case CM_ERROR_BADSMB            : s = "CM_ERROR_BADSMB";             break;                                 
963             case CM_ERROR_ALLBUSY           : s = "CM_ERROR_ALLBUSY";            break;                         
964             case CM_ERROR_NOFILES           : s = "CM_ERROR_NOFILES";            break;                         
965             case CM_ERROR_PARTIALWRITE      : s = "CM_ERROR_PARTIALWRITE";       break;                         
966             case CM_ERROR_NOIPC             : s = "CM_ERROR_NOIPC";              break;                                 
967             case CM_ERROR_BADNTFILENAME     : s = "CM_ERROR_BADNTFILENAME";      break;                         
968             case CM_ERROR_BUFFERTOOSMALL    : s = "CM_ERROR_BUFFERTOOSMALL";     break;                         
969             case CM_ERROR_RENAME_IDENTICAL  : s = "CM_ERROR_RENAME_IDENTICAL";   break;                 
970             case CM_ERROR_ALLOFFLINE        : s = "CM_ERROR_ALLOFFLINE";         break;          
971             case CM_ERROR_AMBIGUOUS_FILENAME: s = "CM_ERROR_AMBIGUOUS_FILENAME"; break;  
972             case CM_ERROR_BADLOGONTYPE      : s = "CM_ERROR_BADLOGONTYPE";       break;             
973             case CM_ERROR_GSSCONTINUE       : s = "CM_ERROR_GSSCONTINUE";        break;         
974             case CM_ERROR_TIDIPC            : s = "CM_ERROR_TIDIPC";             break;              
975             case CM_ERROR_TOO_MANY_SYMLINKS : s = "CM_ERROR_TOO_MANY_SYMLINKS";  break;   
976             case CM_ERROR_PATH_NOT_COVERED  : s = "CM_ERROR_PATH_NOT_COVERED";   break;    
977             case CM_ERROR_LOCK_CONFLICT     : s = "CM_ERROR_LOCK_CONFLICT";      break;       
978             case CM_ERROR_SHARING_VIOLATION : s = "CM_ERROR_SHARING_VIOLATION";  break;   
979             case CM_ERROR_ALLDOWN           : s = "CM_ERROR_ALLDOWN";            break;             
980             case CM_ERROR_TOOFEWBUFS        : s = "CM_ERROR_TOOFEWBUFS";         break;                         
981             case CM_ERROR_TOOMANYBUFS       : s = "CM_ERROR_TOOMANYBUFS";        break;                         
982             }
983             osi_Log2(afsd_logp, "cm_Analyze: ignoring error code 0x%x (%s)", 
984                      errorCode, s);
985             retry = 0;
986         }
987     }
988
989     /* If not allowed to retry, don't */
990     if (!forcing_new && (reqp->flags & CM_REQ_NORETRY) &&
991         (errorCode != RX_MSGSIZE && errorCode != CM_RX_RETRY_BUSY_CALL))
992         retry = 0;
993     else if (retry && dead_session)
994         retry = 0;
995
996     /* drop this on the way out */
997     if (connp)
998         cm_PutConn(connp);
999
1000     /* 
1001      * clear the volume updated flag if we succeed.
1002      * this way the flag will not prevent a subsequent volume 
1003      * from being updated if necessary.
1004      */
1005     if (errorCode == 0)
1006     {
1007         reqp->flags &= ~CM_REQ_VOLUME_UPDATED;
1008     }
1009
1010     /* retry until we fail to find a connection */
1011     return retry;
1012 }
1013
1014 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
1015         cm_req_t *reqp, cm_conn_t **connpp)
1016 {
1017     long code;
1018     cm_serverRef_t *tsrp;
1019     cm_server_t *tsp;
1020     long firstError = 0;
1021     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
1022 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1023     long timeUsed, timeLeft, hardTimeLeft;
1024 #endif
1025     *connpp = NULL;
1026
1027     if (serversp == NULL) {
1028         osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", CM_ERROR_ALLDOWN);
1029         return CM_ERROR_ALLDOWN;
1030     }
1031
1032 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1033     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
1034         
1035     /* leave 5 seconds margin of safety */
1036     timeLeft =  ConnDeadtimeout - timeUsed - 5;
1037     hardTimeLeft = HardDeadtimeout - timeUsed - 5;
1038 #endif
1039
1040     lock_ObtainRead(&cm_serverLock);
1041     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
1042         if (tsrp->status == srv_deleted)
1043             continue;
1044
1045         tsp = tsrp->server;
1046         if (reqp->tokenIdleErrorServp) {
1047             /* 
1048              * search the list until we find the server
1049              * that failed last time.  When we find it
1050              * clear the error, skip it and try the one
1051              * in the list.
1052              */
1053             if (tsp == reqp->tokenIdleErrorServp)
1054                 reqp->tokenIdleErrorServp = NULL;
1055             continue;
1056         }
1057         if (tsp) {
1058             cm_GetServerNoLock(tsp);
1059             lock_ReleaseRead(&cm_serverLock);
1060             if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1061                 allDown = 0;
1062                 if (tsrp->status == srv_busy) {
1063                     allOffline = 0;
1064                     someBusy = 1;
1065                 } else if (tsrp->status == srv_offline) {
1066                     allBusy = 0;
1067                     someOffline = 1;
1068                 } else {
1069                     allOffline = 0;
1070                     allBusy = 0;
1071                     code = cm_ConnByServer(tsp, usersp, connpp);
1072                     if (code == 0) {        /* cm_CBS only returns 0 */
1073                         cm_PutServer(tsp);
1074 #ifdef SET_RX_TIMEOUTS_TO_TIMELEFT
1075                         /* Set RPC timeout */
1076                         if (timeLeft > ConnDeadtimeout)
1077                             timeLeft = ConnDeadtimeout;
1078
1079                         if (hardTimeLeft > HardDeadtimeout) 
1080                             hardTimeLeft = HardDeadtimeout;
1081
1082                         lock_ObtainMutex(&(*connpp)->mx);
1083                         rx_SetConnDeadTime((*connpp)->rxconnp, timeLeft);
1084                         rx_SetConnHardDeadTime((*connpp)->rxconnp, (u_short) hardTimeLeft);
1085                         lock_ReleaseMutex(&(*connpp)->mx);
1086 #endif
1087                         return 0;
1088                     }
1089
1090                     /* therefore, this code is never executed */
1091                     if (firstError == 0)
1092                         firstError = code;
1093                 }
1094             }
1095             lock_ObtainRead(&cm_serverLock);
1096             cm_PutServerNoLock(tsp);
1097         }
1098     }   
1099     lock_ReleaseRead(&cm_serverLock);
1100
1101     if (firstError == 0) {
1102         if (allDown) {
1103             firstError = (reqp->tokenError ? reqp->tokenError : 
1104                           (reqp->idleError ? RX_CALL_TIMEOUT : CM_ERROR_ALLDOWN));
1105             /*
1106              * if we experienced either a token error or and idle dead time error
1107              * and now all of the servers are down, we have either tried them
1108              * all or lost connectivity.  Clear the error we are returning so
1109              * we will not return it indefinitely if the request is retried.
1110              */
1111             reqp->idleError = reqp->tokenError = 0;
1112         } else if (allBusy) {
1113             firstError = CM_ERROR_ALLBUSY;
1114         } else if (allOffline || (someBusy && someOffline)) {
1115             firstError = CM_ERROR_ALLOFFLINE;
1116         } else {
1117             osi_Log0(afsd_logp, "cm_ConnByMServers returning impossible error TIMEDOUT");
1118             firstError = CM_ERROR_TIMEDOUT;
1119         }
1120     }
1121
1122     osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", firstError);
1123     return firstError;
1124 }
1125
1126 /* called with a held server to GC all bad connections hanging off of the server */
1127 void cm_GCConnections(cm_server_t *serverp)
1128 {
1129     cm_conn_t *tcp;
1130     cm_conn_t **lcpp;
1131     cm_user_t *userp;
1132
1133     lock_ObtainWrite(&cm_connLock);
1134     lcpp = &serverp->connsp;
1135     for (tcp = *lcpp; tcp; tcp = *lcpp) {
1136         userp = tcp->userp;
1137         if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
1138             /* do the deletion of this guy */
1139             cm_PutServer(tcp->serverp);
1140             cm_ReleaseUser(userp);
1141             *lcpp = tcp->nextp;
1142             rx_SetConnSecondsUntilNatPing(tcp->rxconnp, 0);
1143             rx_DestroyConnection(tcp->rxconnp);
1144             lock_FinalizeMutex(&tcp->mx);
1145             free(tcp);
1146         }
1147         else {
1148             /* just advance to the next */
1149             lcpp = &tcp->nextp;
1150         }
1151     }
1152     lock_ReleaseWrite(&cm_connLock);
1153 }
1154
1155 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
1156                                cm_server_t *serverp)
1157 {
1158     unsigned short port;
1159     int serviceID;
1160     int secIndex;
1161     struct rx_securityClass *secObjp;
1162
1163     port = serverp->addr.sin_port;
1164     switch (serverp->type) {
1165     case CM_SERVER_VLDB:
1166         if (port == 0)
1167             port = htons(7003);
1168         serviceID = 52;
1169         break;
1170     case CM_SERVER_FILE:
1171         if (port == 0)
1172             port = htons(7000);
1173         serviceID = 1;
1174         break;
1175     default:
1176         osi_panic("unknown server type", __FILE__, __LINE__);
1177     }
1178
1179     if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
1180         secIndex = 2;
1181         switch (cryptall) {
1182         case 0:
1183             tcp->cryptlevel = rxkad_clear;
1184             break;
1185         case 2:
1186             tcp->cryptlevel = rxkad_auth;
1187             break;
1188         default:
1189             tcp->cryptlevel = rxkad_crypt;
1190         }
1191         secObjp = rxkad_NewClientSecurityObject(tcp->cryptlevel,
1192                                                 &ucellp->sessionKey, ucellp->kvno,
1193                                                 ucellp->ticketLen, ucellp->ticketp);    
1194     } else {
1195         /* normal auth */
1196         secIndex = 0;
1197         tcp->cryptlevel = rxkad_clear;
1198         secObjp = rxnull_NewClientSecurityObject();
1199     }
1200     osi_assertx(secObjp != NULL, "null rx_securityClass");
1201     tcp->rxconnp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
1202                                     port,
1203                                     serviceID,
1204                                     secObjp,
1205                                     secIndex);
1206     rx_SetConnDeadTime(tcp->rxconnp, ConnDeadtimeout);
1207     rx_SetConnHardDeadTime(tcp->rxconnp, HardDeadtimeout);
1208     rx_SetConnIdleDeadTime(tcp->rxconnp, IdleDeadtimeout);
1209
1210     /*
1211      * Register the error to be returned on an idle dead timeout
1212      */
1213     rx_SetServerConnIdleDeadErr(tcp->rxconnp, RX_CALL_DEAD);
1214
1215     /*
1216      * Let the Rx library know that we can auto-retry if an
1217      * RX_MSGSIZE error is returned.
1218      */
1219     if (rx_pmtu_discovery)
1220         rx_SetMsgsizeRetryErr(tcp->rxconnp, RX_MSGSIZE);
1221
1222     /*
1223      * Attempt to limit NAT pings to the anonymous file server connections.
1224      * Only file servers implement client callbacks and we only need one ping
1225      * to be sent to each server.
1226      */
1227     if (NatPingInterval && serverp->type == CM_SERVER_FILE && secIndex == 0)
1228         rx_SetConnSecondsUntilNatPing(tcp->rxconnp, NatPingInterval);
1229
1230     tcp->ucgen = ucellp->gen;
1231     if (secObjp)
1232         rxs_Release(secObjp);   /* Decrement the initial refCount */
1233 }
1234
1235 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
1236 {
1237     cm_conn_t *tcp;
1238     cm_ucell_t *ucellp;
1239
1240     *connpp = NULL;
1241
1242     if (cm_anonvldb && serverp->type == CM_SERVER_VLDB)
1243         userp = cm_rootUserp;
1244
1245     lock_ObtainMutex(&userp->mx);
1246     lock_ObtainRead(&cm_connLock);
1247     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1248         if (tcp->userp == userp) 
1249             break;
1250     }
1251     
1252     /* find ucell structure */
1253     ucellp = cm_GetUCell(userp, serverp->cellp);
1254     if (!tcp) {
1255         lock_ConvertRToW(&cm_connLock);
1256         for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1257             if (tcp->userp == userp) 
1258                 break;
1259         }
1260         if (tcp) {
1261             lock_ReleaseWrite(&cm_connLock);
1262             goto haveconn;
1263         }
1264         cm_GetServer(serverp);
1265         tcp = malloc(sizeof(*tcp));
1266         memset(tcp, 0, sizeof(*tcp));
1267         tcp->nextp = serverp->connsp;
1268         serverp->connsp = tcp;
1269         cm_HoldUser(userp);
1270         tcp->userp = userp;
1271         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex", LOCK_HIERARCHY_CONN);
1272         lock_ObtainMutex(&tcp->mx);
1273         tcp->serverp = serverp;
1274         tcp->cryptlevel = rxkad_clear;
1275         cm_NewRXConnection(tcp, ucellp, serverp);
1276         tcp->refCount = 1;
1277         lock_ReleaseMutex(&tcp->mx);
1278         lock_ReleaseWrite(&cm_connLock);
1279     } else {
1280         lock_ReleaseRead(&cm_connLock);
1281       haveconn:
1282         InterlockedIncrement(&tcp->refCount);
1283
1284         lock_ObtainMutex(&tcp->mx);
1285         if ((tcp->flags & CM_CONN_FLAG_FORCE_NEW) ||
1286             (tcp->ucgen < ucellp->gen) ||
1287             (tcp->cryptlevel != (ucellp->flags & CM_UCELLFLAG_RXKAD ? (cryptall == 1 ? rxkad_crypt : (cryptall == 2 ? rxkad_auth : rxkad_clear)) : rxkad_clear)))
1288         {
1289             if (tcp->ucgen < ucellp->gen)
1290                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to token update");
1291             else
1292                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to crypt change");
1293             tcp->flags &= ~CM_CONN_FLAG_FORCE_NEW;
1294             rx_SetConnSecondsUntilNatPing(tcp->rxconnp, 0);
1295             rx_DestroyConnection(tcp->rxconnp);
1296             cm_NewRXConnection(tcp, ucellp, serverp);
1297         }
1298         lock_ReleaseMutex(&tcp->mx);
1299     }
1300     lock_ReleaseMutex(&userp->mx);
1301
1302     /* return this pointer to our caller */
1303     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%p", tcp);
1304     *connpp = tcp;
1305
1306     return 0;
1307 }
1308
1309 long cm_ServerAvailable(struct cm_fid *fidp, struct cm_user *userp)
1310 {
1311     long code;
1312     cm_req_t req;
1313     cm_serverRef_t **serverspp;
1314     cm_serverRef_t *tsrp;
1315     cm_server_t *tsp;
1316     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
1317
1318     cm_InitReq(&req);
1319
1320     code = cm_GetServerList(fidp, userp, &req, &serverspp);
1321     if (code)
1322         return 0;
1323
1324     lock_ObtainRead(&cm_serverLock);
1325     for (tsrp = *serverspp; tsrp; tsrp=tsrp->next) {
1326         if (tsrp->status == srv_deleted)
1327             continue;
1328         tsp = tsrp->server;
1329         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
1330             allDown = 0;
1331             if (tsrp->status == srv_busy) {
1332                 allOffline = 0;
1333                 someBusy = 1;
1334             } else if (tsrp->status == srv_offline) {
1335                 allBusy = 0;
1336                 someOffline = 1;
1337             } else {
1338                 allOffline = 0;
1339                 allBusy = 0;
1340             }
1341         }
1342     }   
1343     lock_ReleaseRead(&cm_serverLock);
1344     cm_FreeServerList(serverspp, 0);
1345
1346     if (allDown)
1347         return 0;
1348     else if (allBusy) 
1349         return 0;
1350     else if (allOffline || (someBusy && someOffline))
1351         return 0;
1352     else
1353         return 1;
1354 }
1355
1356 /* 
1357  * The returned cm_conn_t ** object is released in the subsequent call
1358  * to cm_Analyze().  
1359  */
1360 long cm_ConnFromFID(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
1361                     cm_conn_t **connpp)
1362 {
1363     long code;
1364     cm_serverRef_t **serverspp;
1365
1366     *connpp = NULL;
1367
1368     code = cm_GetServerList(fidp, userp, reqp, &serverspp);
1369     if (code) {
1370         return code;
1371     }
1372
1373     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
1374     cm_FreeServerList(serverspp, 0);
1375     return code;
1376 }
1377
1378
1379 long cm_ConnFromVolume(struct cm_volume *volp, unsigned long volid, struct cm_user *userp, cm_req_t *reqp,
1380                        cm_conn_t **connpp)
1381 {
1382     long code;
1383     cm_serverRef_t **serverspp;
1384
1385     *connpp = NULL;
1386
1387     serverspp = cm_GetVolServers(volp, volid, userp, reqp);
1388
1389     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
1390     cm_FreeServerList(serverspp, 0);
1391     return code;
1392 }
1393
1394
1395 extern struct rx_connection *
1396 cm_GetRxConn(cm_conn_t *connp)
1397 {
1398     struct rx_connection * rxconnp;
1399     lock_ObtainMutex(&connp->mx);
1400     rxconnp = connp->rxconnp;
1401     rx_GetConnection(rxconnp);
1402     lock_ReleaseMutex(&connp->mx);
1403     return rxconnp;
1404 }
1405
1406 void cm_ForceNewConnections(cm_server_t *serverp)
1407 {
1408     cm_conn_t *tcp;
1409
1410     lock_ObtainWrite(&cm_connLock);
1411     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
1412         lock_ObtainMutex(&tcp->mx);
1413         tcp->flags |= CM_CONN_FLAG_FORCE_NEW;
1414         lock_ReleaseMutex(&tcp->mx);
1415     }
1416     lock_ReleaseWrite(&cm_connLock);
1417 }