windows-updatecell-20070619
[openafs.git] / src / WINNT / afsd / cm_conn.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afs/param.h>
11 #include <afs/stds.h>
12
13 #include <windows.h>
14 #include <string.h>
15 #include <malloc.h>
16 #include <osi.h>
17 #include "afsd.h"
18 #include <rx/rx.h>
19 #include <rx/rxkad.h>
20 #include <afs/unified_afs.h>
21 #include <WINNT/afsreg.h>
22
23 osi_rwlock_t cm_connLock;
24
25 DWORD RDRtimeout = CM_CONN_DEFAULTRDRTIMEOUT;
26 unsigned short ConnDeadtimeout = CM_CONN_CONNDEADTIME;
27 unsigned short HardDeadtimeout = CM_CONN_HARDDEADTIME;
28
29 #define LANMAN_WKS_PARAM_KEY "SYSTEM\\CurrentControlSet\\Services\\lanmanworkstation\\parameters"
30 #define LANMAN_WKS_SESSION_TIMEOUT "SessTimeout"
31
32 afs_int32 cryptall = 0;
33
34 void cm_PutConn(cm_conn_t *connp)
35 {
36         lock_ObtainWrite(&cm_connLock);
37         osi_assert(connp->refCount-- > 0);
38         lock_ReleaseWrite(&cm_connLock);
39 }
40
41 void cm_InitConn(void)
42 {
43     static osi_once_t once;
44     long code;
45     DWORD dwValue;
46     DWORD dummyLen;
47     HKEY parmKey;
48         
49     if (osi_Once(&once)) {
50         lock_InitializeRWLock(&cm_connLock, "connection global lock");
51
52         /* keisa - read timeout value for lanmanworkstation  service.
53          * jaltman - as per 
54          *   http://support.microsoft.com:80/support/kb/articles/Q102/0/67.asp&NoWebContent=1
55          * the SessTimeout is a minimum timeout not a maximum timeout.  Therefore, 
56          * I believe that the default should not be short.  Instead, we should wait until
57          * RX times out before reporting a timeout to the SMB client.
58          */
59         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, LANMAN_WKS_PARAM_KEY,
60                             0, KEY_QUERY_VALUE, &parmKey);
61         if (code == ERROR_SUCCESS)
62         {
63             dummyLen = sizeof(DWORD);
64             code = RegQueryValueEx(parmKey, LANMAN_WKS_SESSION_TIMEOUT, NULL, NULL, 
65                                    (BYTE *) &dwValue, &dummyLen);
66             if (code == ERROR_SUCCESS)
67                 RDRtimeout = dwValue;
68             RegCloseKey(parmKey);
69         }
70
71         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
72                              0, KEY_QUERY_VALUE, &parmKey);
73         if (code == ERROR_SUCCESS) {
74             dummyLen = sizeof(DWORD);
75             code = RegQueryValueEx(parmKey, "ConnDeadTimeout", NULL, NULL,
76                                     (BYTE *) &dwValue, &dummyLen);
77             if (code == ERROR_SUCCESS)
78                 ConnDeadtimeout = (unsigned short)dwValue;
79
80             dummyLen = sizeof(DWORD);
81             code = RegQueryValueEx(parmKey, "HardDeadTimeout", NULL, NULL,
82                                     (BYTE *) &dwValue, &dummyLen);
83             if (code == ERROR_SUCCESS)
84                 HardDeadtimeout = (unsigned short)dwValue;
85             afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
86             RegCloseKey(parmKey);
87         }
88
89         afsi_log("lanmanworkstation : SessTimeout %u", RDRtimeout);
90         if (ConnDeadtimeout == 0)
91             ConnDeadtimeout = (unsigned short) (RDRtimeout / 2);
92         afsi_log("ConnDeadTimeout is %d", ConnDeadtimeout);
93         if (HardDeadtimeout == 0)
94             HardDeadtimeout = (unsigned short) RDRtimeout;
95         afsi_log("HardDeadTimeout is %d", HardDeadtimeout);
96
97         osi_EndOnce(&once);
98     }
99 }
100
101 void cm_InitReq(cm_req_t *reqp)
102 {
103         memset((char *)reqp, 0, sizeof(cm_req_t));
104         reqp->startTime = GetTickCount();
105 }
106
107 static long cm_GetServerList(struct cm_fid *fidp, struct cm_user *userp,
108         struct cm_req *reqp, cm_serverRef_t ***serversppp)
109 {
110     long code;
111     cm_volume_t *volp = NULL;
112     cm_cell_t *cellp = NULL;
113
114     if (!fidp) {
115         *serversppp = NULL;
116         return 0;
117     }
118
119     cellp = cm_FindCellByID(fidp->cell);
120     if (!cellp) 
121         return CM_ERROR_NOSUCHCELL;
122
123     code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, CM_GETVOL_FLAG_CREATE, &volp);
124     if (code) 
125         return code;
126     
127     *serversppp = cm_GetVolServers(volp, fidp->volume);
128
129     cm_PutVolume(volp);
130     return 0;
131 }
132
133 /*
134  * Analyze the error return from an RPC.  Determine whether or not to retry,
135  * and if we're going to retry, determine whether failover is appropriate,
136  * and whether timed backoff is appropriate.
137  *
138  * If the error code is from cm_ConnFromFID() or friends, it will be a CM_ERROR code.
139  * Otherwise it will be an RPC code.  This may be a UNIX code (e.g. EDQUOT), or
140  * it may be an RX code, or it may be a special code (e.g. VNOVOL), or it may
141  * be a security code (e.g. RXKADEXPIRED).
142  *
143  * If the error code is from cm_ConnFromFID() or friends, connp will be NULL.
144  *
145  * For VLDB calls, fidp will be NULL.
146  *
147  * volSyncp and/or cbrp may also be NULL.
148  */
149 int
150 cm_Analyze(cm_conn_t *connp, cm_user_t *userp, cm_req_t *reqp,
151            struct cm_fid *fidp, 
152            AFSVolSync *volSyncp, 
153            cm_serverRef_t * serversp,
154            cm_callbackRequest_t *cbrp, long errorCode)
155 {
156     cm_server_t *serverp = NULL;
157     cm_serverRef_t **serverspp = NULL;
158     cm_serverRef_t *tsrp;
159     cm_cell_t  *cellp = NULL;
160     cm_ucell_t *ucellp;
161     cm_volume_t * volp = NULL;
162     cm_vol_state_t *statep = NULL;
163     int retry = 0;
164     int free_svr_list = 0;
165     int dead_session;
166     long timeUsed, timeLeft;
167     long code;
168     char addr[16];
169     int forcing_new = 0;
170
171     osi_Log2(afsd_logp, "cm_Analyze connp 0x%p, code 0x%x",
172              connp, errorCode);
173
174     /* no locking required, since connp->serverp never changes after
175      * creation */
176     dead_session = (userp->cellInfop == NULL);
177     if (connp)
178         serverp = connp->serverp;
179
180     /* Update callback pointer */
181     if (cbrp && serverp && errorCode == 0) {
182         if (cbrp->serverp) {
183             if ( cbrp->serverp != serverp ) {
184                 lock_ObtainWrite(&cm_serverLock);
185                 cm_PutServerNoLock(cbrp->serverp);
186                 cm_GetServerNoLock(serverp);
187                 lock_ReleaseWrite(&cm_serverLock);
188             }
189         } else {
190             cm_GetServer(serverp);
191         }
192         lock_ObtainWrite(&cm_callbackLock);
193         cbrp->serverp = serverp;
194         lock_ReleaseWrite(&cm_callbackLock);
195     }
196
197     /* if timeout - check that it did not exceed the HardDead timeout
198      * and retry */
199     
200     /* timeleft - get if from reqp the same way as cmXonnByMServers does */
201     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
202             
203     /* leave 5 seconds margin for sleep */
204     timeLeft = HardDeadtimeout - timeUsed;
205
206     /* get a pointer to the cell */
207     if (errorCode) {
208         if (cellp == NULL && serverp)
209             cellp = serverp->cellp;
210         if (cellp == NULL && serversp) {
211             struct cm_serverRef * refp;
212             for ( refp=serversp ; cellp == NULL && refp != NULL; refp=refp->next) {
213                 if ( refp->server )
214                     cellp = refp->server->cellp;
215             }
216         } 
217         if (cellp == NULL && fidp) {
218             cellp = cm_FindCellByID(fidp->cell);
219         }
220     }
221
222     if (errorCode == CM_ERROR_TIMEDOUT) {
223         if (timeLeft > 5 ) {
224             thrd_Sleep(3000);
225             cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS, cellp);
226             retry = 1;
227         }
228     } 
229
230     /* if there is nosuchvolume, then we have a situation in which a 
231      * previously known volume no longer has a set of servers 
232      * associated with it.  Either the volume has moved or
233      * the volume has been deleted.  Try to find a new server list
234      * until the timeout period expires.
235      */
236     else if (errorCode == CM_ERROR_NOSUCHVOLUME) {
237         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_NOSUCHVOLUME.");
238         if (timeLeft > 7) {
239             thrd_Sleep(5000);
240             
241             retry = 1;
242
243             if (fidp != NULL)   /* Not a VLDB call */
244                 cm_ForceUpdateVolume(fidp, userp, reqp);
245         }
246     }
247
248     else if (errorCode == CM_ERROR_ALLDOWN) {
249         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLDOWN.");
250         /* Servers marked DOWN will be restored by the background daemon
251          * thread as they become available.
252          */
253     }
254
255     else if (errorCode == CM_ERROR_ALLOFFLINE) {
256         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLOFFLINE.");
257         /* Volume instances marked offline will be restored by the 
258          * background daemon thread as they become available 
259          */
260         if (timeLeft > 7 && fidp) {
261             cm_volume_t *volp;
262             cm_vol_state_t *statep;
263
264             thrd_Sleep(5000);
265
266             code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, 
267                                     CM_GETVOL_FLAG_NO_LRU_UPDATE, 
268                                     &volp);
269             if (code == 0) {
270                 if (fidp->volume == volp->rw.ID)
271                     statep = &volp->rw;
272                 else if (fidp->volume == volp->ro.ID)
273                     statep = &volp->ro;
274                 else if (fidp->volume == volp->bk.ID)
275                     statep = &volp->bk;
276
277                 if (statep->state != vl_offline) {
278                     retry = 1;
279                 } else {
280                     if (cm_CheckOfflineVolume(volp, statep->ID))
281                         retry = 1;
282                 }
283             
284                 cm_PutVolume(volp);
285             }
286         }
287     }
288     else if (errorCode == CM_ERROR_ALLBUSY) {
289         /* Volumes that are busy cannot be determined to be non-busy 
290          * without actually attempting to access them.
291          */
292         osi_Log0(afsd_logp, "cm_Analyze passed CM_ERROR_ALLBUSY.");
293         if (timeLeft > 7) {
294
295             thrd_Sleep(5000);
296
297             if (fidp) { /* File Server query */
298                 code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, 
299                                         CM_GETVOL_FLAG_NO_LRU_UPDATE, 
300                                         &volp);
301                 if (code == 0) {
302                     if (fidp->volume == volp->rw.ID)
303                         statep = &volp->rw;
304                     else if (fidp->volume == volp->ro.ID)
305                         statep = &volp->ro;
306                     else if (fidp->volume == volp->bk.ID)
307                         statep = &volp->bk;
308
309                     if (statep->state != vl_offline && statep->state != vl_busy) {
310                         retry = 1;
311                     } else {
312                         if (!serversp) {
313                             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
314                             if (code == 0) {
315                                 serversp = *serverspp;
316                                 free_svr_list = 1;
317                             }
318                         }
319                         lock_ObtainWrite(&cm_serverLock);
320                         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
321                             if (tsrp->status == srv_busy) {
322                                 tsrp->status = srv_not_busy;
323                             }
324                         }
325                         lock_ReleaseWrite(&cm_serverLock);
326                         if (free_svr_list) {
327                             cm_FreeServerList(&serversp, 0);
328                             *serverspp = serversp;
329                         }
330
331                         cm_UpdateVolumeStatus(volp, statep->ID);
332                         retry = 1;
333                     }
334             
335                     cm_PutVolume(volp);
336                 }
337             } else {    /* VL Server query */
338                 if (serversp) {
339                     lock_ObtainWrite(&cm_serverLock);
340                     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
341                         if (tsrp->status == srv_busy) {
342                             tsrp->status = srv_not_busy;
343                         }
344                     }
345                     lock_ReleaseWrite(&cm_serverLock);
346                     retry = 1;
347                 }
348             }
349         }
350     }
351
352     /* special codes:  VBUSY and VRESTARTING */
353     else if (errorCode == VBUSY || errorCode == VRESTARTING) {
354         if (!serversp) {
355             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
356             if (code == 0) {
357                 serversp = *serverspp;
358                 free_svr_list = 1;
359             }
360         }
361         lock_ObtainWrite(&cm_serverLock);
362         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
363             if (tsrp->server == serverp && tsrp->status == srv_not_busy) {
364                 tsrp->status = srv_busy;
365                 if (fidp) { /* File Server query */
366                     code = cm_GetVolumeByID(cellp, fidp->volume, userp, reqp, 
367                                              CM_GETVOL_FLAG_NO_LRU_UPDATE, 
368                                              &volp);
369                     if (code == 0) {
370                         if (fidp->volume == volp->rw.ID)
371                             statep = &volp->rw;
372                         else if (fidp->volume == volp->ro.ID)
373                             statep = &volp->ro;
374                         else if (fidp->volume == volp->bk.ID)
375                             statep = &volp->bk;
376                     }
377             
378                     cm_PutVolume(volp);
379                 }
380                 break;
381             }
382         }
383         lock_ReleaseWrite(&cm_serverLock);
384         
385         if (statep)
386             cm_UpdateVolumeStatus(volp, statep->ID);
387         
388         if (free_svr_list) {
389             cm_FreeServerList(&serversp, 0);
390             *serverspp = serversp;
391         }
392         retry = 1;
393     }
394
395     /* special codes:  missing volumes */
396     else if (errorCode == VNOVOL || errorCode == VMOVED || errorCode == VOFFLINE ||
397              errorCode == VSALVAGE || errorCode == VNOSERVICE || errorCode == VIO) 
398     {       
399         char addr[16];
400         char *format;
401         DWORD msgID;
402         switch ( errorCode ) {
403         case VNOVOL:
404             msgID = MSG_SERVER_REPORTS_VNOVOL;
405             format = "Server %s reported volume %d as not attached.";
406             break;
407         case VMOVED:
408             msgID = MSG_SERVER_REPORTS_VMOVED;
409             format = "Server %s reported volume %d as moved.";
410             break;
411         case VOFFLINE:
412             msgID = MSG_SERVER_REPORTS_VOFFLINE;
413             format = "Server %s reported volume %d as offline.";
414             break;
415         case VSALVAGE:
416             msgID = MSG_SERVER_REPORTS_VSALVAGE;
417             format = "Server %s reported volume %d as needs salvage.";
418             break;
419         case VNOSERVICE:
420             msgID = MSG_SERVER_REPORTS_VNOSERVICE;
421             format = "Server %s reported volume %d as not in service.";
422             break;
423         case VIO:
424             msgID = MSG_SERVER_REPORTS_VIO;
425             format = "Server %s reported volume %d as temporarily unaccessible.";
426             break;
427         }
428
429         /* Log server being offline for this volume */
430         sprintf(addr, "%d.%d.%d.%d", 
431                  ((serverp->addr.sin_addr.s_addr & 0xff)),
432                  ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
433                  ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
434                  ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
435
436         osi_Log2(afsd_logp, format, osi_LogSaveString(afsd_logp,addr), fidp->volume);
437         LogEvent(EVENTLOG_WARNING_TYPE, msgID, addr, fidp->volume);
438
439         /* Mark server offline for this volume */
440         if (!serversp) {
441             code = cm_GetServerList(fidp, userp, reqp, &serverspp);
442             if (code == 0) {
443                 serversp = *serverspp;
444                 free_svr_list = 1;
445             }
446         }
447         for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
448             if (tsrp->server == serverp) {
449                 /* REDIRECT */
450                 if (errorCode == VNOVOL || errorCode == VMOVED) {
451                     tsrp->status = srv_deleted;
452                     if (fidp) {
453                         cm_ForceUpdateVolume(fidp, userp, reqp);
454                     }
455                 } else 
456                     tsrp->status = srv_offline;
457             }
458         }   
459         if (free_svr_list) {
460             cm_FreeServerList(&serversp, 0);
461             *serverspp = serversp;
462         }
463         if ( timeLeft > 2 )
464             retry = 1;
465     } else if ( errorCode == VNOVNODE ) {
466         if ( fidp ) {
467             cm_scache_t * scp;
468             osi_Log4(afsd_logp, "cm_Analyze passed VNOVNODE cell %u vol %u vn %u uniq %u.",
469                       fidp->cell, fidp->volume, fidp->vnode, fidp->unique);
470
471             scp = cm_FindSCache(fidp);
472             if (scp) {
473                 cm_scache_t *pscp = NULL;
474
475                 if (scp->fileType != CM_SCACHETYPE_DIRECTORY)
476                     pscp = cm_FindSCacheParent(scp);
477
478
479                 lock_ObtainMutex(&scp->mx);
480                 lock_ObtainWrite(&cm_scacheLock);
481                 cm_RemoveSCacheFromHashTable(scp);
482                 lock_ReleaseWrite(&cm_scacheLock);
483                 scp->flags |= CM_SCACHEFLAG_DELETED;
484                 lock_ReleaseMutex(&scp->mx);
485                 cm_ReleaseSCache(scp);
486
487                 if (pscp) {
488                     if (cm_HaveCallback(pscp)) {
489                         lock_ObtainMutex(&pscp->mx);
490                         cm_DiscardSCache(pscp);
491                         lock_ReleaseMutex(&pscp->mx);
492                     }
493                     cm_ReleaseSCache(pscp);
494                 }
495             }
496         } else {
497             osi_Log0(afsd_logp, "cm_Analyze passed VNOVNODE unknown fid.");
498         }
499     }
500
501     /* RX codes */
502     else if (errorCode == RX_CALL_TIMEOUT) {
503         /* server took longer than hardDeadTime 
504          * don't mark server as down but don't retry
505          * this is to prevent the SMB session from timing out
506          * In addition, we log an event to the event log 
507          */
508
509         /* Log server being offline for this volume */
510         sprintf(addr, "%d.%d.%d.%d", 
511                  ((serverp->addr.sin_addr.s_addr & 0xff)),
512                  ((serverp->addr.sin_addr.s_addr & 0xff00)>> 8),
513                  ((serverp->addr.sin_addr.s_addr & 0xff0000)>> 16),
514                  ((serverp->addr.sin_addr.s_addr & 0xff000000)>> 24)); 
515
516         LogEvent(EVENTLOG_WARNING_TYPE, MSG_RX_HARD_DEAD_TIME_EXCEEDED, addr);
517           
518         retry = 0;
519         osi_Log1(afsd_logp, "cm_Analyze: hardDeadTime exceeded addr[%s]",
520                  osi_LogSaveString(afsd_logp,addr));
521     }
522     else if (errorCode >= -64 && errorCode < 0) {
523         /* mark server as down */
524         lock_ObtainMutex(&serverp->mx);
525         if (reqp->flags & CM_REQ_NEW_CONN_FORCED)
526             serverp->flags |= CM_SERVERFLAG_DOWN;
527         else {
528             reqp->flags |= CM_REQ_NEW_CONN_FORCED;
529             forcing_new = 1;
530         }
531         lock_ReleaseMutex(&serverp->mx);
532         cm_ForceNewConnections(serverp);
533         if ( timeLeft > 2 )
534             retry = 1;
535     }
536     else if (errorCode == RXKADEXPIRED || errorCode == RXKADBADTICKET) {
537         if (!dead_session) {
538             lock_ObtainMutex(&userp->mx);
539             ucellp = cm_GetUCell(userp, serverp->cellp);
540             if (ucellp->ticketp) {
541                 free(ucellp->ticketp);
542                 ucellp->ticketp = NULL;
543             }
544             ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
545             ucellp->gen++;
546             lock_ReleaseMutex(&userp->mx);
547             if ( timeLeft > 2 )
548                 retry = 1;
549         }
550     } else if (errorCode == VICECONNBAD || errorCode == VICETOKENDEAD) {
551         cm_ForceNewConnections(serverp);
552         if ( timeLeft > 2 )
553             retry = 1;
554     } else {
555         if (errorCode) {
556             char * s = "unknown error";
557             switch ( errorCode ) {
558             case RXKADINCONSISTENCY: s = "RXKADINCONSISTENCY"; break;
559             case RXKADPACKETSHORT  : s = "RXKADPACKETSHORT";   break;
560             case RXKADLEVELFAIL    : s = "RXKADLEVELFAIL";     break;
561             case RXKADTICKETLEN    : s = "RXKADTICKETLEN";     break;
562             case RXKADOUTOFSEQUENCE: s = "RXKADOUTOFSEQUENCE"; break;
563             case RXKADNOAUTH       : s = "RXKADNOAUTH";        break;
564             case RXKADBADKEY       : s = "RXKADBADKEY";        break;
565             case RXKADBADTICKET    : s = "RXKADBADTICKET";     break;
566             case RXKADUNKNOWNKEY   : s = "RXKADUNKNOWNKEY";    break;
567             case RXKADEXPIRED      : s = "RXKADEXPIRED";       break;
568             case RXKADSEALEDINCON  : s = "RXKADSEALEDINCON";   break;
569             case RXKADDATALEN      : s = "RXKADDATALEN";       break;
570             case RXKADILLEGALLEVEL : s = "RXKADILLEGALLEVEL";  break;
571             case VSALVAGE          : s = "VSALVAGE";           break;
572             case VNOVNODE          : s = "VNOVNODE";           break;
573             case VNOVOL            : s = "VNOVOL";             break;
574             case VVOLEXISTS        : s = "VVOLEXISTS";         break;
575             case VNOSERVICE        : s = "VNOSERVICE";         break;
576             case VOFFLINE          : s = "VOFFLINE";           break;
577             case VONLINE           : s = "VONLINE";            break;
578             case VDISKFULL         : s = "VDISKFULL";          break;
579             case VOVERQUOTA        : s = "VOVERQUOTA";         break;
580             case VBUSY             : s = "VBUSY";              break;
581             case VMOVED            : s = "VMOVED";             break;
582             case VIO               : s = "VIO";                break;
583             case VRESTRICTED       : s = "VRESTRICTED";        break;
584             case VRESTARTING       : s = "VRESTARTING";        break;
585             case VREADONLY         : s = "VREADONLY";          break;
586             case EAGAIN            : s = "EAGAIN";             break;
587             case UAEAGAIN          : s = "UAEAGAIN";           break;
588             case EINVAL            : s = "EINVAL";             break;
589             case UAEINVAL          : s = "UAEINVAL";           break;
590             case EACCES            : s = "EACCES";             break;
591             case UAEACCES          : s = "UAEACCES";           break;
592             case ENOENT            : s = "ENOENT";             break;
593             case UAENOENT          : s = "UAENOENT";           break;
594             case VICECONNBAD       : s = "VICECONNBAD";        break;
595             case VICETOKENDEAD     : s = "VICETOKENDEAD";      break;
596             case CM_ERROR_NOSUCHCELL        : s = "CM_ERROR_NOSUCHCELL";         break;                         
597             case CM_ERROR_NOSUCHVOLUME      : s = "CM_ERROR_NOSUCHVOLUME";       break;                         
598             case CM_ERROR_TIMEDOUT          : s = "CM_ERROR_TIMEDOUT";           break;                 
599             case CM_ERROR_RETRY             : s = "CM_ERROR_RETRY";              break; 
600             case CM_ERROR_NOACCESS          : s = "CM_ERROR_NOACCESS";           break; 
601             case CM_ERROR_NOSUCHFILE        : s = "CM_ERROR_NOSUCHFILE";         break;                         
602             case CM_ERROR_STOPNOW           : s = "CM_ERROR_STOPNOW";            break;                         
603             case CM_ERROR_TOOBIG            : s = "CM_ERROR_TOOBIG";             break;                                 
604             case CM_ERROR_INVAL             : s = "CM_ERROR_INVAL";              break;                                 
605             case CM_ERROR_BADFD             : s = "CM_ERROR_BADFD";              break;                                 
606             case CM_ERROR_BADFDOP           : s = "CM_ERROR_BADFDOP";            break;                         
607             case CM_ERROR_EXISTS            : s = "CM_ERROR_EXISTS";             break;                                 
608             case CM_ERROR_CROSSDEVLINK      : s = "CM_ERROR_CROSSDEVLINK";       break;                         
609             case CM_ERROR_BADOP             : s = "CM_ERROR_BADOP";              break;                                 
610             case CM_ERROR_BADPASSWORD       : s = "CM_ERROR_BADPASSWORD";        break;         
611             case CM_ERROR_NOTDIR            : s = "CM_ERROR_NOTDIR";             break;                                 
612             case CM_ERROR_ISDIR             : s = "CM_ERROR_ISDIR";              break;                                 
613             case CM_ERROR_READONLY          : s = "CM_ERROR_READONLY";           break;                         
614             case CM_ERROR_WOULDBLOCK        : s = "CM_ERROR_WOULDBLOCK";         break;                         
615             case CM_ERROR_QUOTA             : s = "CM_ERROR_QUOTA";              break;                                 
616             case CM_ERROR_SPACE             : s = "CM_ERROR_SPACE";              break;                                 
617             case CM_ERROR_BADSHARENAME      : s = "CM_ERROR_BADSHARENAME";       break;                         
618             case CM_ERROR_BADTID            : s = "CM_ERROR_BADTID";             break;                                 
619             case CM_ERROR_UNKNOWN           : s = "CM_ERROR_UNKNOWN";            break;                         
620             case CM_ERROR_NOMORETOKENS      : s = "CM_ERROR_NOMORETOKENS";       break;                         
621             case CM_ERROR_NOTEMPTY          : s = "CM_ERROR_NOTEMPTY";           break;                         
622             case CM_ERROR_USESTD            : s = "CM_ERROR_USESTD";             break;                                 
623             case CM_ERROR_REMOTECONN        : s = "CM_ERROR_REMOTECONN";         break;                         
624             case CM_ERROR_ATSYS             : s = "CM_ERROR_ATSYS";              break;                                 
625             case CM_ERROR_NOSUCHPATH        : s = "CM_ERROR_NOSUCHPATH";         break;                         
626             case CM_ERROR_CLOCKSKEW         : s = "CM_ERROR_CLOCKSKEW";          break;                         
627             case CM_ERROR_BADSMB            : s = "CM_ERROR_BADSMB";             break;                                 
628             case CM_ERROR_ALLBUSY           : s = "CM_ERROR_ALLBUSY";            break;                         
629             case CM_ERROR_NOFILES           : s = "CM_ERROR_NOFILES";            break;                         
630             case CM_ERROR_PARTIALWRITE      : s = "CM_ERROR_PARTIALWRITE";       break;                         
631             case CM_ERROR_NOIPC             : s = "CM_ERROR_NOIPC";              break;                                 
632             case CM_ERROR_BADNTFILENAME     : s = "CM_ERROR_BADNTFILENAME";      break;                         
633             case CM_ERROR_BUFFERTOOSMALL    : s = "CM_ERROR_BUFFERTOOSMALL";     break;                         
634             case CM_ERROR_RENAME_IDENTICAL  : s = "CM_ERROR_RENAME_IDENTICAL";   break;                 
635             case CM_ERROR_ALLOFFLINE        : s = "CM_ERROR_ALLOFFLINE";         break;          
636             case CM_ERROR_AMBIGUOUS_FILENAME: s = "CM_ERROR_AMBIGUOUS_FILENAME"; break;  
637             case CM_ERROR_BADLOGONTYPE      : s = "CM_ERROR_BADLOGONTYPE";       break;             
638             case CM_ERROR_GSSCONTINUE       : s = "CM_ERROR_GSSCONTINUE";        break;         
639             case CM_ERROR_TIDIPC            : s = "CM_ERROR_TIDIPC";             break;              
640             case CM_ERROR_TOO_MANY_SYMLINKS : s = "CM_ERROR_TOO_MANY_SYMLINKS";  break;   
641             case CM_ERROR_PATH_NOT_COVERED  : s = "CM_ERROR_PATH_NOT_COVERED";   break;    
642             case CM_ERROR_LOCK_CONFLICT     : s = "CM_ERROR_LOCK_CONFLICT";      break;       
643             case CM_ERROR_SHARING_VIOLATION : s = "CM_ERROR_SHARING_VIOLATION";  break;   
644             case CM_ERROR_ALLDOWN           : s = "CM_ERROR_ALLDOWN";            break;             
645             case CM_ERROR_TOOFEWBUFS        : s = "CM_ERROR_TOOFEWBUFS";         break;                         
646             case CM_ERROR_TOOMANYBUFS       : s = "CM_ERROR_TOOMANYBUFS";        break;                         
647             }
648             osi_Log2(afsd_logp, "cm_Analyze: ignoring error code 0x%x (%s)", 
649                      errorCode, s);
650             retry = 0;
651         }
652     }
653
654     /* If not allowed to retry, don't */
655     if (!forcing_new && (reqp->flags & CM_REQ_NORETRY))
656         retry = 0;
657     else if (retry && dead_session)
658         retry = 0;
659
660   out:
661     /* drop this on the way out */
662     if (connp)
663         cm_PutConn(connp);
664
665     /* retry until we fail to find a connection */
666     return retry;
667 }
668
669 long cm_ConnByMServers(cm_serverRef_t *serversp, cm_user_t *usersp,
670         cm_req_t *reqp, cm_conn_t **connpp)
671 {
672     long code;
673     cm_serverRef_t *tsrp;
674     cm_server_t *tsp;
675     long firstError = 0;
676     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
677     long timeUsed, timeLeft, hardTimeLeft;
678
679     if (serversp == NULL) {
680         osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", CM_ERROR_ALLDOWN);
681         return CM_ERROR_ALLDOWN;
682     }
683
684     *connpp = NULL;
685
686     timeUsed = (GetTickCount() - reqp->startTime) / 1000;
687         
688     /* leave 5 seconds margin of safety */
689     timeLeft =  ConnDeadtimeout - timeUsed - 5;
690     hardTimeLeft = HardDeadtimeout - timeUsed - 5;
691
692     lock_ObtainWrite(&cm_serverLock);
693     for (tsrp = serversp; tsrp; tsrp=tsrp->next) {
694         tsp = tsrp->server;
695         cm_GetServerNoLock(tsp);
696         lock_ReleaseWrite(&cm_serverLock);
697         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
698             allDown = 0;
699             if (tsrp->status == srv_deleted) {
700                 /* skip this entry.  no longer valid. */;
701             } else if (tsrp->status == srv_busy) {
702                 allOffline = 0;
703                 someBusy = 1;
704             } else if (tsrp->status == srv_offline) {
705                 allBusy = 0;
706                 someOffline = 1;
707             } else {
708                 allOffline = 0;
709                 allBusy = 0;
710                 code = cm_ConnByServer(tsp, usersp, connpp);
711                 if (code == 0) {        /* cm_CBS only returns 0 */
712                     cm_PutServer(tsp);
713                     /* Set RPC timeout */
714                     if (timeLeft > ConnDeadtimeout)
715                         timeLeft = ConnDeadtimeout;
716
717                     if (hardTimeLeft > HardDeadtimeout) 
718                         hardTimeLeft = HardDeadtimeout;
719
720                     lock_ObtainMutex(&(*connpp)->mx);
721                     rx_SetConnDeadTime((*connpp)->callp, timeLeft);
722                     rx_SetConnHardDeadTime((*connpp)->callp, (u_short) hardTimeLeft);
723                     lock_ReleaseMutex(&(*connpp)->mx);
724                     return 0;
725                 }
726                 
727                 /* therefore, this code is never executed */
728                 if (firstError == 0)
729                     firstError = code;
730             }
731         }
732         lock_ObtainWrite(&cm_serverLock);
733         cm_PutServerNoLock(tsp);
734     }   
735     lock_ReleaseWrite(&cm_serverLock);
736
737     if (firstError == 0) {
738         if (allDown) 
739             firstError = CM_ERROR_ALLDOWN;
740         else if (allBusy) 
741             firstError = CM_ERROR_ALLBUSY;
742         else if (allOffline || (someBusy && someOffline))
743             firstError = CM_ERROR_ALLOFFLINE;
744         else {
745             osi_Log0(afsd_logp, "cm_ConnByMServers returning impossible error TIMEDOUT");
746             firstError = CM_ERROR_TIMEDOUT;
747         }
748     }
749
750     osi_Log1(afsd_logp, "cm_ConnByMServers returning 0x%x", firstError);
751     return firstError;
752 }
753
754 /* called with a held server to GC all bad connections hanging off of the server */
755 void cm_GCConnections(cm_server_t *serverp)
756 {
757     cm_conn_t *tcp;
758     cm_conn_t **lcpp;
759     cm_user_t *userp;
760
761     lock_ObtainWrite(&cm_connLock);
762     lcpp = &serverp->connsp;
763     for (tcp = *lcpp; tcp; tcp = *lcpp) {
764         userp = tcp->userp;
765         if (userp && tcp->refCount == 0 && (userp->vcRefs == 0)) {
766             /* do the deletion of this guy */
767             cm_PutServer(tcp->serverp);
768             cm_ReleaseUser(userp);
769             *lcpp = tcp->nextp;
770             rx_DestroyConnection(tcp->callp);
771             lock_FinalizeMutex(&tcp->mx);
772             free(tcp);
773         }
774         else {
775             /* just advance to the next */
776             lcpp = &tcp->nextp;
777         }
778     }
779     lock_ReleaseWrite(&cm_connLock);
780 }
781
782 static void cm_NewRXConnection(cm_conn_t *tcp, cm_ucell_t *ucellp,
783                                cm_server_t *serverp)
784 {
785     unsigned short port;
786     int serviceID;
787     int secIndex;
788     struct rx_securityClass *secObjp;
789
790     if (serverp->type == CM_SERVER_VLDB) {
791         port = htons(7003);
792         serviceID = 52;
793     }
794     else {
795         osi_assert(serverp->type == CM_SERVER_FILE);
796         port = htons(7000);
797         serviceID = 1;
798     }
799     if (ucellp->flags & CM_UCELLFLAG_RXKAD) {
800         secIndex = 2;
801         if (cryptall) {
802             tcp->cryptlevel = rxkad_crypt;
803         } else {
804             tcp->cryptlevel = rxkad_clear;
805         }
806         secObjp = rxkad_NewClientSecurityObject(tcp->cryptlevel,
807                                                 &ucellp->sessionKey, ucellp->kvno,
808                                                 ucellp->ticketLen, ucellp->ticketp);    
809     } else {
810         /* normal auth */
811         secIndex = 0;
812         tcp->cryptlevel = rxkad_clear;
813         secObjp = rxnull_NewClientSecurityObject();
814     }
815     osi_assert(secObjp != NULL);
816     tcp->callp = rx_NewConnection(serverp->addr.sin_addr.s_addr,
817                                   port,
818                                   serviceID,
819                                   secObjp,
820                                   secIndex);
821     rx_SetConnDeadTime(tcp->callp, ConnDeadtimeout);
822     rx_SetConnHardDeadTime(tcp->callp, HardDeadtimeout);
823     tcp->ucgen = ucellp->gen;
824     if (secObjp)
825         rxs_Release(secObjp);   /* Decrement the initial refCount */
826 }
827
828 long cm_ConnByServer(cm_server_t *serverp, cm_user_t *userp, cm_conn_t **connpp)
829 {
830     cm_conn_t *tcp;
831     cm_ucell_t *ucellp;
832
833     lock_ObtainMutex(&userp->mx);
834     lock_ObtainWrite(&cm_connLock);
835     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
836         if (tcp->userp == userp) 
837             break;
838     }
839     
840     /* find ucell structure */
841     ucellp = cm_GetUCell(userp, serverp->cellp);
842     if (!tcp) {
843         cm_GetServer(serverp);
844         tcp = malloc(sizeof(*tcp));
845         memset(tcp, 0, sizeof(*tcp));
846         tcp->nextp = serverp->connsp;
847         serverp->connsp = tcp;
848         cm_HoldUser(userp);
849         tcp->userp = userp;
850         lock_InitializeMutex(&tcp->mx, "cm_conn_t mutex");
851         lock_ObtainMutex(&tcp->mx);
852         tcp->serverp = serverp;
853         tcp->cryptlevel = rxkad_clear;
854         cm_NewRXConnection(tcp, ucellp, serverp);
855         tcp->refCount = 1;
856         lock_ReleaseMutex(&tcp->mx);
857     } else {
858         if ((tcp->flags & CM_CONN_FLAG_FORCE_NEW) ||
859             (tcp->ucgen < ucellp->gen) ||
860             (tcp->cryptlevel != (cryptall ? (ucellp->flags & CM_UCELLFLAG_RXKAD ? rxkad_crypt : rxkad_clear) : rxkad_clear)))
861         {
862             if (tcp->ucgen < ucellp->gen)
863                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to token update");
864             else
865                 osi_Log0(afsd_logp, "cm_ConnByServer replace connection due to crypt change");
866             lock_ObtainMutex(&tcp->mx);
867             tcp->flags &= ~CM_CONN_FLAG_FORCE_NEW;
868             rx_DestroyConnection(tcp->callp);
869             cm_NewRXConnection(tcp, ucellp, serverp);
870             lock_ReleaseMutex(&tcp->mx);
871         }
872         tcp->refCount++;
873     }
874     lock_ReleaseWrite(&cm_connLock);
875     lock_ReleaseMutex(&userp->mx);
876
877     /* return this pointer to our caller */
878     osi_Log1(afsd_logp, "cm_ConnByServer returning conn 0x%p", tcp);
879     *connpp = tcp;
880
881     return 0;
882 }
883
884 long cm_ServerAvailable(struct cm_fid *fidp, struct cm_user *userp)
885 {
886     long code;
887     cm_req_t req;
888     cm_serverRef_t **serverspp;
889     cm_serverRef_t *tsrp;
890     cm_server_t *tsp;
891     int someBusy = 0, someOffline = 0, allOffline = 1, allBusy = 1, allDown = 1;
892
893     cm_InitReq(&req);
894
895     code = cm_GetServerList(fidp, userp, &req, &serverspp);
896     if (code)
897         return 0;
898
899     lock_ObtainWrite(&cm_serverLock);
900     for (tsrp = *serverspp; tsrp; tsrp=tsrp->next) {
901         tsp = tsrp->server;
902         cm_GetServerNoLock(tsp);
903         if (!(tsp->flags & CM_SERVERFLAG_DOWN)) {
904             allDown = 0;
905             if (tsrp->status == srv_busy) {
906                 allOffline = 0;
907                 someBusy = 1;
908             } else if (tsrp->status == srv_offline) {
909                 allBusy = 0;
910                 someOffline = 1;
911             } else {
912                 allOffline = 0;
913                 allBusy = 0;
914             }
915         }
916         cm_PutServerNoLock(tsp);
917     }   
918     lock_ReleaseWrite(&cm_serverLock);
919     cm_FreeServerList(serverspp, 0);
920
921     if (allDown)
922         return 0;
923     else if (allBusy) 
924         return 0;
925     else if (allOffline || (someBusy && someOffline))
926         return 0;
927     else
928         return 1;
929 }
930
931 /* 
932  * The returned cm_conn_t ** object is released in the subsequent call
933  * to cm_Analyze().  
934  */
935 long cm_ConnFromFID(struct cm_fid *fidp, struct cm_user *userp, cm_req_t *reqp,
936                     cm_conn_t **connpp)
937 {
938     long code;
939     cm_serverRef_t **serverspp;
940
941     code = cm_GetServerList(fidp, userp, reqp, &serverspp);
942     if (code) {
943         *connpp = NULL;
944         return code;
945     }
946
947     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
948     cm_FreeServerList(serverspp, 0);
949     return code;
950 }
951
952
953 long cm_ConnFromVolume(struct cm_volume *volp, unsigned long volid, struct cm_user *userp, cm_req_t *reqp,
954                        cm_conn_t **connpp)
955 {
956     long code;
957     cm_serverRef_t **serverspp;
958
959     serverspp = cm_GetVolServers(volp, volid);
960
961     code = cm_ConnByMServers(*serverspp, userp, reqp, connpp);
962     cm_FreeServerList(serverspp, 0);
963     return code;
964 }
965
966
967 extern struct rx_connection *
968 cm_GetRxConn(cm_conn_t *connp)
969 {
970     struct rx_connection * rxconn;
971     lock_ObtainMutex(&connp->mx);
972     rxconn = connp->callp;
973     rx_GetConnection(rxconn);
974     lock_ReleaseMutex(&connp->mx);
975     return rxconn;
976 }
977
978 void cm_ForceNewConnections(cm_server_t *serverp)
979 {
980     cm_conn_t *tcp;
981
982     lock_ObtainWrite(&cm_connLock);
983     for (tcp = serverp->connsp; tcp; tcp=tcp->nextp) {
984         lock_ObtainMutex(&tcp->mx);
985         tcp->flags |= CM_CONN_FLAG_FORCE_NEW;
986         lock_ReleaseMutex(&tcp->mx);
987     }
988     lock_ReleaseWrite(&cm_connLock);
989 }