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