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