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