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