da10a258e95039fcfeb61a119c73f5354399e4f3
[openafs.git] / src / viced / afsfileprocs.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 /*  afs_fileprocs.c - Complete File Server request routines              */
11 /*                                                                       */
12 /*  Information Technology Center                                        */
13 /*  Carnegie Mellon University                                           */
14 /*                                                                       */
15 /*  Date: 8/10/88                                                        */
16 /*                                                                       */
17 /*  Function    - A set of routines to handle the various file Server    */
18 /*                  requests; these routines are invoked by rxgen.       */
19 /*                                                                       */
20 /* ********************************************************************** */
21
22 /* 
23  * in Check_PermissionRights, certain privileges are afforded to the owner 
24  * of the volume, or the owner of a file.  Are these considered "use of 
25  * privilege"? 
26  */
27
28 #include <afsconfig.h>
29 #include <afs/param.h>
30
31 RCSID("$Header$");
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <errno.h>
36 #ifdef  AFS_SGI_ENV
37 #undef SHARED           /* XXX */
38 #endif
39 #ifdef AFS_NT40_ENV
40 #include <fcntl.h>
41 #else
42 #include <sys/param.h>
43 #include <sys/file.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48
49 #ifdef HAVE_STRING_H
50 #include <string.h>
51 #else
52 #ifdef HAVE_STRINGS_H
53 #include <strings.h>
54 #endif
55 #endif
56
57 #ifndef AFS_LINUX20_ENV
58 #include <net/if.h>
59 #include <netinet/if_ether.h>
60 #endif
61 #endif
62 #ifdef AFS_HPUX_ENV
63 /* included early because of name conflict on IOPEN */
64 #include <sys/inode.h>
65 #ifdef IOPEN
66 #undef IOPEN
67 #endif
68 #endif /* AFS_HPUX_ENV */
69 #include <afs/stds.h>
70 #include <rx/xdr.h>
71 #include <afs/nfs.h>
72 #include <afs/assert.h>
73 #include <lwp.h>
74 #include <lock.h>
75 #include <afs/afsint.h>
76 #include <afs/vldbint.h>
77 #include <afs/errors.h>
78 #include <afs/ihandle.h>
79 #include <afs/vnode.h>
80 #include <afs/volume.h>
81 #include <afs/acl.h>
82 #include <afs/ptclient.h>
83 #include <afs/prs_fs.h>
84 #include <rx/rx.h>
85 #include <rx/rx_globals.h>
86 #include <sys/stat.h>
87 #if ! defined(AFS_SGI_ENV) && ! defined(AFS_AIX32_ENV) && ! defined(AFS_NT40_ENV) && ! defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
88 #include <sys/map.h>
89 #endif
90 #if !defined(AFS_NT40_ENV)
91 #include <unistd.h>
92 #endif
93 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
94 #ifdef  AFS_AIX_ENV
95 #include <sys/statfs.h>
96 #include <sys/lockf.h>
97 #else
98 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
99 #include <sys/dk.h>
100 #endif
101 #endif
102 #endif
103 #include <afs/cellconfig.h>
104 #include <afs/keys.h>
105
106 #include <afs/auth.h>
107 #include <signal.h>
108 #include <afs/partition.h>
109 #include "viced_prototypes.h"
110 #include "viced.h"
111 #include "host.h"
112 #include <afs/unified_afs.h>
113 #include <afs/audit.h>
114 #include <afs/afsutil.h>
115
116 #ifdef AFS_PTHREAD_ENV
117 pthread_mutex_t fileproc_glock_mutex;
118 #endif /* AFS_PTHREAD_ENV */
119
120
121 /* Useful local defines used by this module */
122
123 #define DONTCHECK       0
124 #define MustNOTBeDIR    1
125 #define MustBeDIR       2
126
127 #define TVS_SDATA       1
128 #define TVS_SSTATUS     2
129 #define TVS_CFILE       4
130 #define TVS_SLINK       8
131 #define TVS_MKDIR       0x10
132
133 #define CHK_FETCH       0x10
134 #define CHK_FETCHDATA   0x10
135 #define CHK_FETCHACL    0x11
136 #define CHK_FETCHSTATUS 0x12
137 #define CHK_STOREDATA   0x00
138 #define CHK_STOREACL    0x01
139 #define CHK_STORESTATUS 0x02
140
141 #define OWNERREAD       0400
142 #define OWNERWRITE      0200
143 #define OWNEREXEC       0100
144 #ifdef USE_GROUP_PERMS
145 #define GROUPREAD       0040
146 #define GROUPWRITE      0020
147 #define GROUPREXEC      0010
148 #endif
149
150 /* The following errors were not defined in NT. They are given unique
151  * names here to avoid any potential collision.
152  */
153 #define FSERR_ELOOP              90
154 #define FSERR_EOPNOTSUPP        122
155 #define FSERR_ECONNREFUSED      130
156
157 #define NOTACTIVECALL   0
158 #define ACTIVECALL      1
159
160 #define CREATE_SGUID_ADMIN_ONLY 1
161
162 extern struct afsconf_dir *confDir;
163 extern afs_int32 dataVersionHigh;
164
165 extern  int         SystemId;
166 static struct AFSCallStatistics AFSCallStats;
167 #if FS_STATS_DETAILED
168 struct fs_stats_FullPerfStats afs_FullPerfStats;
169 extern int AnonymousID;
170 #endif /* FS_STATS_DETAILED */
171 #if OPENAFS_VOL_STATS
172 static const char nullString[] = "";
173 #endif /* OPENAFS_VOL_STATS */
174
175 struct afs_FSStats {
176     afs_int32 NothingYet;
177 };
178
179 struct afs_FSStats afs_fsstats;
180
181 void    ResetDebug(), SetDebug(), Terminate();
182
183 int     LogLevel = 0;
184 int     supported = 1;
185 int     Console = 0;
186 afs_int32 BlocksSpare = 1024;   /* allow 1 MB overruns */
187 afs_int32 PctSpare;
188 extern afs_int32 implicitAdminRights;
189 extern afs_int32 readonlyServer;
190
191 /*
192  * Externals used by the xstat code.
193  */
194 extern int VolumeCacheSize, VolumeGets, VolumeReplacements;
195 extern int CEs, CEBlocks;
196
197 extern int HTs, HTBlocks;
198
199 afs_int32
200 FetchData_RXStyle(Volume *volptr, 
201                   Vnode *targetptr, 
202                   register struct rx_call *Call,
203                   afs_int32 Pos,
204                   afs_int32 Len,
205                   afs_int32 Int64Mode,
206 #if FS_STATS_DETAILED
207                   afs_int32 *a_bytesToFetchP,
208                   afs_int32 *a_bytesFetchedP
209 #endif /* FS_STATS_DETAILED */
210                   );
211
212 afs_int32
213 StoreData_RXStyle(Volume *volptr,
214                   Vnode *targetptr,
215                   struct AFSFid *Fid,
216                   struct client *client,
217                   register struct rx_call *Call,
218                   afs_uint32 Pos,
219                   afs_uint32 Length,
220                   afs_uint32 FileLength,
221                   int sync,
222 #if FS_STATS_DETAILED
223                   afs_int32 *a_bytesToStoreP,
224                   afs_int32 *a_bytesStoredP
225 #endif /* FS_STATS_DETAILED */
226                   );
227
228 #ifdef AFS_SGI_XFS_IOPS_ENV
229 #include <afs/xfsattrs.h>
230 static int GetLinkCount(Volume *avp, struct stat *astat)
231 {
232     if (!strcmp("xfs", astat->st_fstype)) {
233         return (astat->st_mode & AFS_XFS_MODE_LINK_MASK);
234     }
235     else
236         return astat->st_nlink;
237 }
238 #else
239 #define GetLinkCount(V, S) (S)->st_nlink
240 #endif
241
242 afs_int32 SpareComp(Volume *avolp)
243 {
244     register afs_int32 temp;
245
246     FS_LOCK
247     if (PctSpare) {
248         temp = V_maxquota(avolp);
249         if (temp == 0) {
250             /* no matter; doesn't check in this case */
251             FS_UNLOCK
252             return 0;
253         }
254         temp = (temp * PctSpare) / 100;
255         FS_UNLOCK
256         return temp;
257     }
258     else {
259         FS_UNLOCK
260         return BlocksSpare;
261     }
262
263 } /*SpareComp*/
264
265 /*
266  * Set the volume synchronization parameter for this volume.  If it changes,
267  * the Cache Manager knows that the volume must be purged from the stat cache.
268  */
269 static void SetVolumeSync(register struct AFSVolSync *async, 
270                           register Volume *avol)
271 {
272     FS_LOCK
273     /* date volume instance was created */
274     if (async) {
275         if (avol)
276             async->spare1 = avol->header->diskstuff.creationDate;
277         else
278             async->spare1 = 0;
279         async->spare2 = 0;
280         async->spare3 = 0;
281         async->spare4 = 0;
282         async->spare5 = 0;
283         async->spare6 = 0;
284     }
285     FS_UNLOCK
286 } /*SetVolumeSync*/
287
288 /*
289  * Note that this function always returns a held host, so
290  * that CallPostamble can block without the host's disappearing.
291  * Call returns rx connection in passed in *tconn
292  */
293 static int CallPreamble(register struct rx_call *acall, int activecall,
294                         struct rx_connection **tconn)
295 {
296     struct host *thost;
297     struct client *tclient;
298     int retry_flag=1;
299     int code = 0;
300     char hoststr[16];
301     if (!tconn) {
302         ViceLog (0, ("CallPreamble: unexpected null tconn!\n"));
303         return -1;
304     }
305     *tconn = rx_ConnectionOf(acall);
306
307     H_LOCK
308 retry:
309     tclient = h_FindClient_r(*tconn);
310     if (tclient->prfail == 1) { /* couldn't get the CPS */
311        if (!retry_flag) {
312           h_ReleaseClient_r(tclient);
313           ViceLog(0, ("CallPreamble: Couldn't get CPS. Fail\n"));
314           H_UNLOCK
315           return -1001;
316        }
317        retry_flag=0;    /* Retry once */
318
319        /* Take down the old connection and re-read the key file */
320        ViceLog(0, ("CallPreamble: Couldn't get CPS. Reconnect to ptserver\n"));
321        H_UNLOCK
322        code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
323        H_LOCK
324        if (code) {
325           h_ReleaseClient_r(tclient);
326           H_UNLOCK
327           ViceLog(0,("CallPreamble: couldn't reconnect to ptserver\n"));
328           return -1001;
329        }
330
331        tclient->prfail = 2;      /* Means re-eval client's cps */
332        h_ReleaseClient_r(tclient);
333        goto retry;
334     }
335
336     thost = tclient->host;
337     tclient->LastCall = thost->LastCall = FT_ApproxTime();
338     if (activecall) /* For all but "GetTime" calls */
339         thost->ActiveCall = thost->LastCall;
340
341     h_Lock_r(thost);
342     if (thost->hostFlags & HOSTDELETED) {
343       ViceLog(3,("Discarded a packet for deleted host %s\n",afs_inet_ntoa_r(thost->host,hoststr)));
344       code = VBUSY; /* raced, so retry */
345     }
346     else if ((thost->hostFlags & VENUSDOWN) || (thost->hostFlags & HFE_LATER)){
347       if (BreakDelayedCallBacks_r(thost)) {
348         ViceLog(0,("BreakDelayedCallbacks FAILED for host %s which IS UP.  Possible network or routing failure.\n",
349                 afs_inet_ntoa_r(thost->host, hoststr)));
350         if ( MultiProbeAlternateAddress_r (thost) ) {
351             ViceLog(0, ("MultiProbe failed to find new address for host %s:%d\n",
352                         afs_inet_ntoa_r(thost->host, hoststr), 
353                         ntohs(thost->port)));
354             code = -1;
355         } else {
356             ViceLog(0, ("MultiProbe found new address for host %s:%d\n",
357                         afs_inet_ntoa_r(thost->host, hoststr), 
358                         ntohs(thost->port)));
359             if (BreakDelayedCallBacks_r(thost)) {
360                 ViceLog(0,("BreakDelayedCallbacks FAILED AGAIN for host %s which IS UP.  Possible network or routing failure.\n",
361                         afs_inet_ntoa_r(thost->host, hoststr)));
362                 code = -1;
363             }
364         }
365       }
366     } else {
367        code =  0;
368     }
369
370     h_ReleaseClient_r(tclient);
371     h_Unlock_r(thost);
372     H_UNLOCK
373     return code;      
374
375 } /*CallPreamble*/
376
377
378 static afs_int32 CallPostamble(register struct rx_connection *aconn,
379                                afs_int32 ret)
380 {
381     struct host *thost;
382     struct client *tclient;
383     int translate = 0;
384
385     H_LOCK
386     tclient = h_FindClient_r(aconn);
387     thost = tclient->host;
388     if (thost->hostFlags & HERRORTRANS) translate = 1;
389     h_ReleaseClient_r(tclient);
390     h_Release_r(thost);
391     H_UNLOCK
392
393     return (translate ? sys_error_to_et(ret) : ret);
394 } /*CallPostamble*/
395
396 /*
397  * Returns the volume and vnode pointers associated with file Fid; the lock
398  * type on the vnode is set to lock. Note that both volume/vnode's ref counts
399  * are incremented and they must be eventualy released.
400  */
401 static afs_int32
402 CheckVnode(AFSFid *fid, Volume **volptr, Vnode **vptr, int lock)
403 {
404     int fileCode = 0;
405     int errorCode = -1;
406     static struct timeval restartedat = {0,0};
407
408     if (fid->Volume == 0 || fid->Vnode == 0) /* not: || fid->Unique == 0) */
409         return(EINVAL);
410     if ((*volptr) == 0) {
411       extern int VInit;
412
413       while(1) {
414         errorCode = 0;
415         *volptr = VGetVolume(&errorCode, (afs_int32)fid->Volume);
416         if (!errorCode) {
417           assert (*volptr);
418           break;
419         }
420         if ((errorCode == VOFFLINE) && (VInit < 2)) {
421             /* The volume we want may not be attached yet because
422              * the volume initialization is not yet complete.
423              * We can do several things: 
424              *     1.  return -1, which will cause users to see
425              *         "connection timed out".  This is more or
426              *         less the same as always, except that the servers
427              *         may appear to bounce up and down while they
428              *         are actually restarting.
429              *     2.  return VBUSY which will cause clients to 
430              *         sleep and retry for 6.5 - 15 minutes, depending
431              *         on what version of the CM they are running.  If
432              *         the file server takes longer than that interval 
433              *         to attach the desired volume, then the application
434              *         will see an ENODEV or EIO.  This approach has 
435              *         the advantage that volumes which have been attached
436              *         are immediately available, it keeps the server's
437              *         immediate backlog low, and the call is interruptible
438              *         by the user.  Users see "waiting for busy volume."
439              *     3.  sleep here and retry.  Some people like this approach
440              *         because there is no danger of seeing errors.  However, 
441              *         this approach only works with a bounded number of 
442              *         clients, since the pending queues will grow without
443              *         stopping.  It might be better to find a way to take
444              *         this call and stick it back on a queue in order to
445              *         recycle this thread for a different request.    
446              *     4.  Return a new error code, which new cache managers will
447              *         know enough to interpret as "sleep and retry", without
448              *         the upper bound of 6-15 minutes that is imposed by the
449              *         VBUSY handling.  Users will see "waiting for
450              *         busy volume," so they know that something is
451              *         happening.  Old cache managers must be able to do  
452              *         something reasonable with this, for instance, mark the
453              *         server down.  Fortunately, any error code < 0
454              *         will elicit that behavior. See #1.
455              *     5.  Some combination of the above.  I like doing #2 for 10
456              *         minutes, followed by #4.  3.1b and 3.2 cache managers
457              *         will be fine as long as the restart period is
458              *         not longer than 6.5 minutes, otherwise they may
459              *         return ENODEV to users.  3.3 cache managers will be
460              *         fine for 10 minutes, then will return
461              *         ETIMEDOUT.  3.4 cache managers will just wait
462              *         until the call works or fails definitively.
463              *  NB. The problem with 2,3,4,5 is that old clients won't
464              *  fail over to an alternate read-only replica while this
465              *  server is restarting.  3.4 clients will fail over right away.
466              */
467           if (restartedat.tv_sec == 0) {
468             /* I'm not really worried about when we restarted, I'm   */
469             /* just worried about when the first VBUSY was returned. */
470             TM_GetTimeOfDay(&restartedat, 0);
471             return(busyonrst?VBUSY:VRESTARTING);
472           }
473           else {
474             struct timeval now;
475             TM_GetTimeOfDay(&now, 0);
476             if ((now.tv_sec - restartedat.tv_sec) < (11*60)) {
477               return(busyonrst?VBUSY:VRESTARTING);
478             }
479             else {
480               return (VRESTARTING);
481             }
482           }
483         }
484           /* allow read operations on busy volume */
485         else if(errorCode==VBUSY && lock==READ_LOCK) {
486           errorCode=0;
487           break;
488         }
489         else if (errorCode)
490           return(errorCode);
491       }
492     }
493     assert (*volptr);
494
495     /* get the vnode  */
496     *vptr = VGetVnode(&errorCode, *volptr, fid->Vnode, lock);
497     if (errorCode)
498         return(errorCode);
499     if ((*vptr)->disk.uniquifier != fid->Unique) {
500         VPutVnode(&fileCode, *vptr);
501         assert(fileCode == 0);
502         *vptr = 0;
503         return(VNOVNODE);   /* return the right error code, at least */
504     }
505     return(0);
506 } /*CheckVnode*/
507
508 /*
509  * This routine returns the ACL associated with the targetptr. If the
510  * targetptr isn't a directory, we access its parent dir and get the ACL
511  * thru the parent; in such case the parent's vnode is returned in
512  * READ_LOCK mode.
513  */
514 static afs_int32
515 SetAccessList(Vnode **targetptr,
516               Volume **volume,
517               struct acl_accessList **ACL,
518               int * ACLSize,
519               Vnode **parent,
520               AFSFid *Fid,
521               int Lock)
522 {
523     if ((*targetptr)->disk.type == vDirectory) {
524         *parent = 0;
525         *ACL = VVnodeACL(*targetptr);
526         *ACLSize = VAclSize(*targetptr);
527         return(0);
528     }
529     else {
530         assert(Fid != 0);
531         while(1) {
532             VnodeId parentvnode;
533             int errorCode = 0;
534             
535             parentvnode = (*targetptr)->disk.parent;
536             VPutVnode(&errorCode,*targetptr);
537             *targetptr = 0;
538             if (errorCode) return(errorCode);
539             *parent = VGetVnode(&errorCode, *volume, parentvnode, READ_LOCK);
540             if (errorCode) return(errorCode);
541             *ACL = VVnodeACL(*parent);
542             *ACLSize = VAclSize(*parent);
543             if ((errorCode = CheckVnode(Fid, volume, targetptr, Lock)) != 0)
544                 return(errorCode);
545             if ((*targetptr)->disk.parent != parentvnode) {
546                 VPutVnode(&errorCode, *parent);
547                 *parent = 0;
548                 if (errorCode) return(errorCode);
549             } else
550                 return(0);
551         }
552     }
553
554 } /*SetAccessList*/
555
556 /*
557  * Compare the directory's ACL with the user's access rights in the client
558  * connection and return the user's and everybody else's access permissions
559  * in rights and anyrights, respectively
560  */
561 static afs_int32
562 GetRights (struct client *client,
563            struct acl_accessList *ACL,
564            afs_int32 *rights,
565            afs_int32 *anyrights)
566 {
567     extern prlist SystemAnyUserCPS;
568     afs_int32 hrights = 0;
569     int code;
570
571     if (acl_CheckRights(ACL, &SystemAnyUserCPS, anyrights) != 0) {
572
573         ViceLog(0,("CheckRights failed\n"));
574         *anyrights = 0;
575     }
576     *rights = 0;
577     acl_CheckRights(ACL, &client->CPS, rights);
578
579         /* wait if somebody else is already doing the getCPS call */
580     H_LOCK
581     while ( client->host->hostFlags & HCPS_INPROGRESS )
582     {
583         client->host->hostFlags |= HCPS_WAITING;  /* I am waiting */
584 #ifdef AFS_PTHREAD_ENV
585         pthread_cond_wait(&client->host->cond, &host_glock_mutex);
586 #else /* AFS_PTHREAD_ENV */
587         if ((code=LWP_WaitProcess( &(client->host->hostFlags))) !=LWP_SUCCESS)
588                 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
589 #endif /* AFS_PTHREAD_ENV */
590     }
591
592     if (client->host->hcps.prlist_len && !client->host->hcps.prlist_val) {
593         ViceLog(0,("CheckRights: len=%d, for host=0x%x\n", client->host->hcps.prlist_len, client->host->host));
594     } else
595         acl_CheckRights(ACL, &client->host->hcps, &hrights);
596     H_UNLOCK
597     /* Allow system:admin the rights given with the -implicit option */
598     if (acl_IsAMember(SystemId, &client->CPS))
599         *rights |= implicitAdminRights;
600     *rights |= hrights;
601     *anyrights |= hrights;
602
603     return(0);
604
605 } /*GetRights*/
606
607 /*
608  * VanillaUser returns 1 (true) if the user is a vanilla user (i.e., not
609  * a System:Administrator)
610  */
611 static afs_int32
612 VanillaUser(struct client *client)
613 {
614     if (acl_IsAMember(SystemId, &client->CPS))
615         return(0);  /* not a system administrator, then you're "vanilla" */
616     return(1);
617
618 } /*VanillaUser*/
619
620
621 /*
622  * This unusual afs_int32-parameter routine encapsulates all volume package related
623  * operations together in a single function; it's called by almost all AFS
624  * interface calls.
625  */
626 static afs_int32
627 GetVolumePackage(struct rx_connection *tcon,
628                  AFSFid *Fid,
629                  Volume **volptr,
630                  Vnode **targetptr,
631                  int chkforDir,
632                  Vnode **parent,
633                  struct client **client,
634                  int locktype,
635                  afs_int32 *rights, 
636                  afs_int32 *anyrights)
637 {
638     struct acl_accessList * aCL;    /* Internal access List */
639     int aCLSize;            /* size of the access list */
640     int errorCode = 0;      /* return code to caller */
641
642     if ((errorCode = CheckVnode(Fid, volptr, targetptr, locktype)))
643         return(errorCode);
644     if (chkforDir) {
645         if (chkforDir == MustNOTBeDIR && ((*targetptr)->disk.type == vDirectory))
646             return(EISDIR);
647         else if (chkforDir == MustBeDIR && ((*targetptr)->disk.type != vDirectory))
648             return(ENOTDIR);
649     }
650     if ((errorCode = SetAccessList(targetptr, volptr, &aCL, &aCLSize, parent, (chkforDir == MustBeDIR ? (AFSFid *)0 : Fid), (chkforDir == MustBeDIR ? 0 : locktype))) != 0)
651         return(errorCode);
652     if (chkforDir == MustBeDIR) assert((*parent) == 0);
653     if ((errorCode = GetClient(tcon, client)) != 0)
654         return(errorCode);
655     if (!(*client))
656         return(EINVAL);
657     assert(GetRights(*client, aCL, rights, anyrights) == 0);
658     /* ok, if this is not a dir, set the PRSFS_ADMINISTER bit iff we're the owner */
659     if ((*targetptr)->disk.type != vDirectory) {
660         /* anyuser can't be owner, so only have to worry about rights, not anyrights */
661         if ((*targetptr)->disk.owner == (*client)->ViceId)
662             (*rights) |= PRSFS_ADMINISTER;
663         else
664             (*rights) &= ~PRSFS_ADMINISTER;
665     }
666 #ifdef ADMIN_IMPLICIT_LOOKUP
667     /* admins get automatic lookup on everything */
668     if (!VanillaUser(*client)) (*rights) |= PRSFS_LOOKUP;
669 #endif /* ADMIN_IMPLICIT_LOOKUP */
670     return errorCode;
671
672 } /*GetVolumePackage*/
673
674
675 /*
676  * This is the opposite of GetVolumePackage(), and is always used at the end of
677  * AFS calls to put back all used vnodes and the volume in the proper order!
678  */
679 static afs_int32
680 PutVolumePackage(Vnode *parentwhentargetnotdir, 
681                  Vnode *targetptr,
682                  Vnode *parentptr,
683                  Volume *volptr)
684 {
685     int fileCode = 0;   /* Error code returned by the volume package */
686
687     if (parentwhentargetnotdir) {
688         VPutVnode(&fileCode, parentwhentargetnotdir);
689         assert(!fileCode || (fileCode == VSALVAGE));
690     }
691     if (targetptr) {
692         VPutVnode(&fileCode, targetptr);
693         assert(!fileCode || (fileCode == VSALVAGE));
694     }
695     if (parentptr) {
696         VPutVnode(&fileCode, parentptr);
697         assert(!fileCode || (fileCode == VSALVAGE));
698     }
699     if (volptr) {
700         VPutVolume(volptr);
701     }
702 } /*PutVolumePackage*/
703
704 static int VolumeOwner (register struct client *client, 
705                         register Vnode *targetptr)
706 {
707     afs_int32 owner = V_owner(targetptr->volumePtr);    /* get volume owner */
708
709     if (owner >= 0)
710         return (client->ViceId == owner);
711     else {
712         /* 
713          * We don't have to check for host's cps since only regular
714          * viceid are volume owners.
715          */
716         return (acl_IsAMember(owner, &client->CPS));
717     }
718
719 } /*VolumeOwner*/
720
721 static int VolumeRootVnode (Vnode *targetptr)
722 {
723     return ((targetptr->vnodeNumber == ROOTVNODE) &&
724             (targetptr->disk.uniquifier == 1));
725
726 } /*VolumeRootVnode*/
727
728 /*
729  * Check if target file has the proper access permissions for the Fetch
730  * (FetchData, FetchACL, FetchStatus) and Store (StoreData, StoreACL,
731  * StoreStatus) related calls
732  */
733 /* this code should probably just set a "priv" flag where all the audit events
734  * are now, and only generate the audit event once at the end of the routine, 
735  * thus only generating the event if all the checks succeed, but only because
736  * of the privilege       XXX
737  */
738 static afs_int32
739 Check_PermissionRights(Vnode *targetptr,
740                        struct client *client,
741                        afs_int32 rights,
742                        int CallingRoutine,
743                        AFSStoreStatus *InStatus)
744 {
745     int errorCode = 0;
746 #define OWNSp(client, target) ((client)->ViceId == (target)->disk.owner)
747 #define CHOWN(i,t) (((i)->Mask & AFS_SETOWNER) &&((i)->Owner != (t)->disk.owner))
748 #define CHGRP(i,t) (((i)->Mask & AFS_SETGROUP) &&((i)->Group != (t)->disk.group))
749
750     if (CallingRoutine & CHK_FETCH) {
751         if (CallingRoutine == CHK_FETCHDATA || VanillaUser(client)) 
752           {
753             if (targetptr->disk.type == vDirectory || targetptr->disk.type == vSymlink) {
754                 if (   !(rights & PRSFS_LOOKUP)
755 #ifdef ADMIN_IMPLICIT_LOOKUP  
756                     /* grant admins fetch on all directories */
757                     && VanillaUser(client)
758 #endif /* ADMIN_IMPLICIT_LOOKUP */
759                     && !VolumeOwner(client, targetptr))
760                     return(EACCES);
761             } else {    /* file */
762                 /* must have read access, or be owner and have insert access */
763                 if (!(rights & PRSFS_READ) &&
764                     !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)))
765                     return(EACCES);
766             }
767             if (CallingRoutine == CHK_FETCHDATA && targetptr->disk.type == vFile)
768 #ifdef USE_GROUP_PERMS
769                 if (!OWNSp(client, targetptr) &&
770                     !acl_IsAMember(targetptr->disk.owner, &client->CPS)) {
771                     errorCode = (((GROUPREAD|GROUPEXEC) & targetptr->disk.modeBits)
772                                  ? 0: EACCES);
773                 } else {
774                     errorCode =(((OWNERREAD|OWNEREXEC) & targetptr->disk.modeBits)
775                                 ? 0: EACCES);
776                 }
777 #else
778                 /*
779                  * The check with the ownership below is a kludge to allow
780                  * reading of files created with no read permission. The owner
781                  * of the file is always allowed to read it.
782                  */
783                 if ((client->ViceId != targetptr->disk.owner) && VanillaUser(client))
784                     errorCode =(((OWNERREAD|OWNEREXEC) & targetptr->disk.modeBits) ? 0: EACCES);
785 #endif
786         }
787         else /*  !VanillaUser(client) && !FetchData */ {
788           osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0), 
789                                         AUD_INT, CallingRoutine, AUD_END);
790         }
791     }
792     else { /* a store operation */
793       if ( (rights & PRSFS_INSERT) && OWNSp(client, targetptr)
794           && (CallingRoutine != CHK_STOREACL)
795           && (targetptr->disk.type == vFile))
796         {
797           /* bypass protection checks on first store after a create
798            * for the creator; also prevent chowns during this time
799            * unless you are a system administrator */
800           /******  InStatus->Owner && UnixModeBits better be SET!! */
801           if ( CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
802             if (readonlyServer) 
803               return(VREADONLY);
804             else if (VanillaUser (client)) 
805               return(EPERM);      /* Was EACCES */
806             else
807               osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0), 
808                                             AUD_INT, CallingRoutine, AUD_END);
809           }
810         } else {
811           if (CallingRoutine != CHK_STOREDATA && !VanillaUser(client)) {
812             osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0),
813                                           AUD_INT, CallingRoutine, AUD_END);
814           }
815           else {
816             if (readonlyServer) {
817                 return(VREADONLY);
818             }
819             if (CallingRoutine == CHK_STOREACL) {
820               if (!(rights & PRSFS_ADMINISTER) &&
821                   !VolumeOwner(client, targetptr)) return(EACCES);
822             }
823             else {      /* store data or status */
824               /* watch for chowns and chgrps */
825               if (CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
826                 if (readonlyServer) 
827                   return(VREADONLY);
828                 else if (VanillaUser (client)) 
829                   return(EPERM);        /* Was EACCES */
830                 else
831                   osi_audit(PrivilegeEvent, 0,
832                             AUD_INT, (client ? client->ViceId : 0), 
833                             AUD_INT, CallingRoutine, AUD_END);
834               }
835               /* must be sysadmin to set suid/sgid bits */
836               if ((InStatus->Mask & AFS_SETMODE) &&
837 #ifdef AFS_NT40_ENV
838                   (InStatus->UnixModeBits & 0xc00) != 0) {
839 #else
840                   (InStatus->UnixModeBits & (S_ISUID|S_ISGID)) != 0) {
841 #endif
842                 if (readonlyServer)
843                   return(VREADONLY);
844                 if (VanillaUser(client))
845                   return(EACCES);
846                 else osi_audit( PrivSetID, 0, AUD_INT, (client ? client->ViceId : 0),
847                                               AUD_INT, CallingRoutine, AUD_END);
848               }
849               if (CallingRoutine == CHK_STOREDATA) {
850                 if (readonlyServer)
851                   return(VREADONLY);
852                 if (!(rights & PRSFS_WRITE))
853                   return(EACCES);
854                 /* Next thing is tricky.  We want to prevent people
855                  * from writing files sans 0200 bit, but we want
856                  * creating new files with 0444 mode to work.  We
857                  * don't check the 0200 bit in the "you are the owner"
858                  * path above, but here we check the bit.  However, if
859                  * you're a system administrator, we ignore the 0200
860                  * bit anyway, since you may have fchowned the file,
861                  * too */
862 #ifdef USE_GROUP_PERMS
863                         if ((targetptr->disk.type == vFile)
864                             && VanillaUser(client)) {
865                             if (!OWNSp(client, targetptr) &&
866                                 !acl_IsAMember(targetptr->disk.owner,
867                                                &client->CPS)) {
868                                 errorCode = ((GROUPWRITE & targetptr->disk.modeBits)
869                                              ? 0: EACCES);
870                             } else {
871                                 errorCode = ((OWNERWRITE & targetptr->disk.modeBits)
872                                              ? 0 : EACCES);
873                             }
874                         } else
875 #endif
876                 if ((targetptr->disk.type != vDirectory)
877                     && (!(targetptr->disk.modeBits & OWNERWRITE))) {
878                   if (readonlyServer)
879                     return(VREADONLY);
880                   if (VanillaUser(client))
881                     return(EACCES);
882                   else osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0),
883                                                      AUD_INT, CallingRoutine, AUD_END);
884                 }
885               }
886               else {  /* a status store */
887                 if (readonlyServer)
888                   return(VREADONLY);
889                 if (targetptr->disk.type == vDirectory) {
890                   if (!(rights & PRSFS_DELETE) && !(rights & PRSFS_INSERT))
891                     return(EACCES);
892                 }
893                 else {  /* a file  or symlink */
894                   if (!(rights & PRSFS_WRITE)) return(EACCES);
895                 }
896               }
897             }
898           }
899         }
900     }
901     return(errorCode);
902
903 } /*Check_PermissionRights*/
904
905
906 /*
907  * The Access List information is converted from its internal form in the
908  * target's vnode buffer (or its parent vnode buffer if not a dir), to an
909  * external form and returned back to the caller, via the AccessList
910  * structure
911  */
912 static afs_int32
913 RXFetch_AccessList(Vnode *targetptr,
914                    Vnode *parentwhentargetnotdir,
915                    struct AFSOpaque *AccessList)
916 {
917     char * eACL;        /* External access list placeholder */
918
919     if (acl_Externalize((targetptr->disk.type == vDirectory ?
920                          VVnodeACL(targetptr) :
921                          VVnodeACL(parentwhentargetnotdir)), &eACL) != 0) {
922         return EIO;
923     }
924     if ((strlen(eACL)+1) > AFSOPAQUEMAX) {
925         acl_FreeExternalACL(&eACL);
926         return(E2BIG);
927     } else {
928         strcpy((char *)(AccessList->AFSOpaque_val), (char *)eACL);
929         AccessList->AFSOpaque_len = strlen(eACL) +1;
930     }
931     acl_FreeExternalACL(&eACL);
932     return(0);
933
934 } /*RXFetch_AccessList*/
935
936
937 /*
938  * The Access List information is converted from its external form in the
939  * input AccessList structure to the internal representation and copied into
940  * the target dir's vnode storage.
941  */
942 static afs_int32
943 RXStore_AccessList(Vnode *targetptr, struct AFSOpaque *AccessList)
944 {
945     struct acl_accessList * newACL;     /* PlaceHolder for new access list */
946
947     if (acl_Internalize(AccessList->AFSOpaque_val, &newACL) != 0)
948         return(EINVAL);
949     if ((newACL->size + 4) > VAclSize(targetptr))
950         return(E2BIG);
951     memcpy((char *) VVnodeACL(targetptr), (char *) newACL, (int)(newACL->size));
952     acl_FreeACL(&newACL);
953     return(0);
954
955 } /*RXStore_AccessList*/
956
957
958 static afs_int32
959 Fetch_AccessList(Vnode *targetptr, Vnode *parentwhentargetnotdir,
960                  struct AFSAccessList *AccessList)
961 {
962     char * eACL;        /* External access list placeholder */
963
964     assert(acl_Externalize((targetptr->disk.type == vDirectory ?
965                             VVnodeACL(targetptr) :
966                             VVnodeACL(parentwhentargetnotdir)), &eACL) == 0);
967     if ((strlen(eACL)+1) > AccessList->MaxSeqLen) {
968         acl_FreeExternalACL(&eACL);
969         return(E2BIG);
970     } else {
971         strcpy((char *)(AccessList->SeqBody), (char *)eACL);
972         AccessList->SeqLen = strlen(eACL) +1;
973     }
974     acl_FreeExternalACL(&eACL);
975     return(0);
976
977 } /*Fetch_AccessList*/
978
979 /*
980  * The Access List information is converted from its external form in the
981  * input AccessList structure to the internal representation and copied into
982  * the target dir's vnode storage.
983  */
984 static afs_int32
985 Store_AccessList(Vnode *targetptr, struct AFSAccessList *AccessList)
986 {
987     struct acl_accessList * newACL;     /* PlaceHolder for new access list */
988
989     if (acl_Internalize(AccessList->SeqBody, &newACL) != 0)
990         return(EINVAL);
991     if ((newACL->size + 4) > VAclSize(targetptr))
992         return(E2BIG);
993     memcpy((char *) VVnodeACL(targetptr), (char *) newACL, (int)(newACL->size));
994     acl_FreeACL(&newACL);
995     return(0);
996
997 } /*Store_AccessList*/
998
999
1000 /* In our current implementation, each successive data store (new file
1001  * data version) creates a new inode. This function creates the new
1002  * inode, copies the old inode's contents to the new one, remove the old
1003  * inode (i.e. decrement inode count -- if it's currently used the delete
1004  * will be delayed), and modify some fields (i.e. vnode's
1005  * disk.inodeNumber and cloned)
1006  */
1007 #define COPYBUFFSIZE    8192
1008 static int CopyOnWrite(Vnode *targetptr, Volume *volptr)
1009 {
1010     Inode       ino, nearInode;
1011     int         rdlen;
1012     int         wrlen;
1013     register int size, length;
1014     int ifd, ofd;
1015     char        *buff;
1016     int         rc;             /* return code */
1017     IHandle_t   *newH;  /* Use until finished copying, then cp to vnode.*/
1018     FdHandle_t  *targFdP;  /* Source Inode file handle */
1019     FdHandle_t  *newFdP; /* Dest Inode file handle */
1020
1021     if (targetptr->disk.type == vDirectory) DFlush();   /* just in case? */
1022
1023     VN_GET_LEN(size, targetptr);
1024     buff = (char *)malloc(COPYBUFFSIZE);
1025     if (buff == NULL) {
1026         return EIO;
1027     }
1028
1029     ino = VN_GET_INO(targetptr);
1030     assert(VALID_INO(ino));
1031     targFdP = IH_OPEN(targetptr->handle);
1032     if (targFdP == NULL) {
1033         rc = errno;
1034         ViceLog(0, ("CopyOnWrite failed: Failed to open target vnode %u in volume %u (errno = %d)\n", targetptr->vnodeNumber, V_id(volptr), rc));
1035         free(buff);
1036         VTakeOffline (volptr);
1037         return rc;
1038     }
1039
1040     nearInode = VN_GET_INO(targetptr);
1041     ino = IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1042                     VPartitionPath(V_partition(volptr)),nearInode, V_id(volptr),
1043                     targetptr->vnodeNumber, targetptr->disk.uniquifier,
1044                     (int)targetptr->disk.dataVersion);
1045     if (!VALID_INO(ino))
1046     {
1047         ViceLog(0,("CopyOnWrite failed: Partition %s that contains volume %u may be out of free inodes(errno = %d)\n", volptr->partition->name, V_id(volptr), errno));
1048         FDH_CLOSE(targFdP);
1049         free(buff);
1050         return ENOSPC;
1051     }
1052     IH_INIT(newH, V_device(volptr), V_id(volptr), ino);
1053     newFdP = IH_OPEN(newH);
1054     assert(newFdP != NULL);
1055
1056     while(size > 0) {
1057         if (size > COPYBUFFSIZE) { /* more than a buffer */
1058             length = COPYBUFFSIZE;
1059             size -= COPYBUFFSIZE;
1060         } else {
1061             length = size;
1062             size = 0;
1063         }
1064         rdlen = FDH_READ(targFdP, buff, length); 
1065         if (rdlen == length)
1066             wrlen = FDH_WRITE(newFdP, buff, length);
1067         else
1068             wrlen = 0;
1069         /*  Callers of this function are not prepared to recover
1070          *  from error that put the filesystem in an inconsistent
1071          *  state. Make sure that we force the volume off-line if
1072          *  we some error other than ENOSPC - 4.29.99)
1073          *
1074          *  In case we are unable to write the required bytes, and the
1075          *  error code indicates that the disk is full, we roll-back to
1076          *  the initial state.
1077          */
1078         if((rdlen != length) || (wrlen != length))
1079                 if ( (wrlen < 0) && (errno == ENOSPC) ) /* disk full */
1080                 {
1081                         ViceLog(0,("CopyOnWrite failed: Partition %s containing volume %u is full\n",
1082                                         volptr->partition->name, V_id(volptr)));
1083                         /* remove destination inode which was partially copied till now*/
1084                         FDH_REALLYCLOSE(newFdP);
1085                         IH_RELEASE(newH);
1086                         FDH_REALLYCLOSE(targFdP);
1087                         rc = IH_DEC(V_linkHandle(volptr), ino,
1088                                   V_parentId(volptr));
1089                         if (!rc ) {
1090                             ViceLog(0,("CopyOnWrite failed: error %u after i_dec on disk full, volume %u in partition %s needs salvage\n",
1091                                        rc, V_id(volptr), 
1092                                        volptr->partition->name));
1093                             VTakeOffline (volptr);
1094                         }
1095                         free(buff);
1096                         return ENOSPC;
1097                 }
1098                 else {
1099                     ViceLog(0,("CopyOnWrite failed: volume %u in partition %s  (tried reading %u, read %u, wrote %u, errno %u) volume needs salvage\n",
1100                                V_id(volptr), volptr->partition->name, length,
1101                                rdlen, wrlen, errno));
1102 #ifdef FAST_RESTART /* if running in no-salvage, don't core the server */
1103                     ViceLog(0,("CopyOnWrite failed: taking volume offline\n"));
1104 #else /* Avoid further corruption and try to get a core. */
1105                     assert(0); 
1106 #endif
1107                     /* Decrement this inode so salvager doesn't find it. */
1108                     FDH_REALLYCLOSE(newFdP);
1109                     IH_RELEASE(newH);
1110                     FDH_REALLYCLOSE(targFdP);
1111                     rc = IH_DEC(V_linkHandle(volptr), ino,
1112                                 V_parentId(volptr));
1113                     free(buff);
1114                     VTakeOffline (volptr);
1115                     return EIO;
1116                 }
1117 #ifndef AFS_PTHREAD_ENV
1118         IOMGR_Poll();
1119 #endif /* !AFS_PTHREAD_ENV */
1120     }
1121     FDH_REALLYCLOSE(targFdP);
1122     rc = IH_DEC(V_linkHandle(volptr), VN_GET_INO(targetptr),
1123               V_parentId(volptr)) ;
1124     assert(!rc);
1125     IH_RELEASE(targetptr->handle);
1126
1127     rc = FDH_SYNC(newFdP);
1128     assert(rc == 0);
1129     FDH_CLOSE(newFdP);
1130     targetptr->handle = newH;
1131     VN_SET_INO(targetptr, ino);
1132     targetptr->disk.cloned = 0;
1133     /* Internal change to vnode, no user level change to volume - def 5445 */
1134     targetptr->changed_oldTime = 1;
1135     free(buff);
1136     return 0;                           /* success */
1137 } /*CopyOnWrite*/
1138
1139
1140 /*
1141  * Common code to handle with removing the Name (file when it's called from
1142  * SAFS_RemoveFile() or an empty dir when called from SAFS_rmdir()) from a
1143  * given directory, parentptr.
1144  */
1145 int DT1=0, DT0=0;
1146 static afs_int32
1147 DeleteTarget(Vnode *parentptr,
1148              Volume *volptr,
1149              Vnode **targetptr,
1150              DirHandle *dir,
1151              AFSFid *fileFid,
1152              char *Name,
1153              int ChkForDir)
1154 {
1155     DirHandle childdir;     /* Handle for dir package I/O */
1156     int errorCode = 0;
1157     int code;
1158
1159     /* watch for invalid names */
1160     if (!strcmp(Name, ".") || !strcmp(Name, ".."))
1161         return (EINVAL);
1162     if (parentptr->disk.cloned) 
1163     {
1164         ViceLog(25, ("DeleteTarget : CopyOnWrite called\n"));
1165         if ((errorCode = CopyOnWrite(parentptr, volptr)))
1166         {
1167                 ViceLog(20, ("DeleteTarget %s: CopyOnWrite failed %d\n",Name,errorCode));
1168                 return errorCode;
1169         }
1170     }
1171
1172     /* check that the file is in the directory */
1173     SetDirHandle(dir, parentptr);
1174     if (Lookup(dir, Name, fileFid))
1175         return(ENOENT);
1176     fileFid->Volume = V_id(volptr);
1177
1178     /* just-in-case check for something causing deadlock */
1179     if (fileFid->Vnode == parentptr->vnodeNumber)
1180         return(EINVAL);
1181
1182     *targetptr = VGetVnode(&errorCode, volptr, fileFid->Vnode, WRITE_LOCK);
1183     if (errorCode) {
1184         return (errorCode);
1185     }
1186     if (ChkForDir == MustBeDIR) {
1187         if ((*targetptr)->disk.type != vDirectory)
1188             return(ENOTDIR);
1189     } else if ((*targetptr)->disk.type == vDirectory)
1190         return(EISDIR);
1191     
1192     /*assert((*targetptr)->disk.uniquifier == fileFid->Unique);*/
1193     /**
1194       * If the uniquifiers dont match then instead of asserting
1195       * take the volume offline and return VSALVAGE
1196       */
1197     if ( (*targetptr)->disk.uniquifier != fileFid->Unique ) {
1198         VTakeOffline(volptr);
1199         errorCode = VSALVAGE;
1200         return errorCode;
1201     }
1202         
1203     if (ChkForDir == MustBeDIR) {
1204         SetDirHandle(&childdir, *targetptr);
1205         if (IsEmpty(&childdir) != 0)
1206             return(EEXIST);
1207         DZap(&childdir);
1208         (*targetptr)->delete = 1;
1209     } else if ((--(*targetptr)->disk.linkCount) == 0) 
1210         (*targetptr)->delete = 1;
1211     if ((*targetptr)->delete) {
1212         if (VN_GET_INO(*targetptr)) {
1213             DT0++;
1214             IH_REALLYCLOSE((*targetptr)->handle);
1215             errorCode = IH_DEC(V_linkHandle(volptr),
1216                              VN_GET_INO(*targetptr),
1217                              V_parentId(volptr));
1218             IH_RELEASE((*targetptr)->handle);
1219             if (errorCode == -1) {
1220                 ViceLog(0, ("DT: inode=%s, name=%s, errno=%d\n",
1221                             PrintInode(NULL, VN_GET_INO(*targetptr)),
1222                             Name, errno));
1223 #ifdef  AFS_DEC_ENV
1224                 if ((errno != ENOENT) && (errno != EIO) && (errno != ENXIO))
1225 #else
1226                 if (errno != ENOENT) 
1227 #endif
1228                     {
1229                     ViceLog(0, ("Volume %u now offline, must be salvaged.\n", 
1230                                 volptr->hashid));
1231                     VTakeOffline(volptr);
1232                     return (EIO);
1233                     }
1234                 DT1++;
1235                 errorCode = 0;
1236             }
1237         }
1238         VN_SET_INO(*targetptr, (Inode)0);
1239         {
1240             afs_fsize_t adjLength;
1241             VN_GET_LEN(adjLength, *targetptr);
1242             VAdjustDiskUsage(&errorCode, volptr,
1243                              -(int)nBlocks(adjLength), 0);
1244         }
1245     }
1246     
1247     (*targetptr)->changed_newTime = 1; /* Status change of deleted file/dir */
1248
1249     code = Delete(dir,(char *) Name);
1250     if (code) {
1251        ViceLog(0, ("Error %d deleting %s\n", code,
1252                    (((*targetptr)->disk.type== Directory)?"directory":"file")));
1253        ViceLog(0, ("Volume %u now offline, must be salvaged.\n", 
1254                   volptr->hashid));
1255        VTakeOffline(volptr);
1256        if (!errorCode) errorCode = code;
1257     }
1258
1259     DFlush();
1260     return(errorCode);
1261
1262 } /*DeleteTarget*/
1263
1264
1265 /*
1266  * This routine updates the parent directory's status block after the
1267  * specified operation (i.e. RemoveFile(), CreateFile(), Rename(),
1268  * SymLink(), Link(), MakeDir(), RemoveDir()) on one of its children has
1269  * been performed.
1270  */
1271 static void
1272 Update_ParentVnodeStatus(Vnode *parentptr,
1273                          Volume *volptr,
1274                          DirHandle *dir,
1275                          int author,
1276                          int linkcount,
1277 #if FS_STATS_DETAILED
1278                          char a_inSameNetwork
1279 #endif /* FS_STATS_DETAILED */
1280                          )
1281 {
1282     afs_fsize_t newlength;      /* Holds new directory length */
1283     afs_fsize_t parentLength;
1284     int errorCode;
1285 #if FS_STATS_DETAILED
1286     Date currDate;              /*Current date*/
1287     int writeIdx;               /*Write index to bump*/
1288     int timeIdx;                /*Authorship time index to bump*/
1289 #endif /* FS_STATS_DETAILED */
1290
1291     parentptr->disk.dataVersion++;
1292     newlength = Length(dir);
1293     /* 
1294      * This is a called on both dir removals (i.e. remove, removedir, rename) but also in dir additions
1295      * (create, symlink, link, makedir) so we need to check if we have enough space
1296      * XXX But we still don't check the error since we're dealing with dirs here and really the increase
1297      * of a new entry would be too tiny to worry about failures (since we have all the existing cushion)
1298      */
1299     VN_GET_LEN(parentLength, parentptr);
1300     if (nBlocks(newlength) != nBlocks(parentLength)) {
1301         VAdjustDiskUsage(&errorCode, volptr, 
1302                          (nBlocks(newlength) - nBlocks(parentLength)),
1303                          (nBlocks(newlength) - nBlocks(parentLength)));
1304     }
1305     VN_SET_LEN(parentptr, newlength);
1306
1307 #if FS_STATS_DETAILED
1308     /*
1309      * Update directory write stats for this volume.  Note that the auth
1310      * counter is located immediately after its associated ``distance''
1311      * counter.
1312      */
1313     if (a_inSameNetwork)
1314         writeIdx = VOL_STATS_SAME_NET;
1315     else
1316         writeIdx = VOL_STATS_DIFF_NET;
1317     V_stat_writes(volptr, writeIdx)++;
1318     if (author != AnonymousID) {
1319         V_stat_writes(volptr, writeIdx+1)++;
1320     }
1321
1322     /*
1323      * Update the volume's authorship information in response to this
1324      * directory operation.  Get the current time, decide to which time
1325      * slot this operation belongs, and bump the appropriate slot.
1326      */
1327     currDate = (FT_ApproxTime() - parentptr->disk.unixModifyTime);
1328     timeIdx = (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 :
1329                currDate < VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 :
1330                currDate < VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 :
1331                currDate < VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 :
1332                currDate < VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1333                VOL_STATS_TIME_IDX_5);
1334     if (parentptr->disk.author == author) {
1335         V_stat_dirSameAuthor(volptr, timeIdx)++;
1336     }
1337     else {
1338         V_stat_dirDiffAuthor(volptr, timeIdx)++;
1339     }
1340 #endif /* FS_STATS_DETAILED */
1341
1342     parentptr->disk.author = author;
1343     parentptr->disk.linkCount = linkcount;
1344     parentptr->disk.unixModifyTime = FT_ApproxTime();   /* This should be set from CLIENT!! */
1345     parentptr->disk.serverModifyTime = FT_ApproxTime();
1346     parentptr->changed_newTime = 1; /* vnode changed, write it back. */
1347 }
1348
1349
1350 /*
1351  * Update the target file's (or dir's) status block after the specified
1352  * operation is complete. Note that some other fields maybe updated by
1353  * the individual module.
1354  */
1355
1356 /* XXX INCOMPLETE - More attention is needed here! */
1357 static void
1358 Update_TargetVnodeStatus(Vnode *targetptr,
1359                          afs_uint32 Caller,
1360                          struct client *client,
1361                          AFSStoreStatus *InStatus,
1362                          Vnode *parentptr,
1363                          Volume *volptr,
1364                          afs_fsize_t length)
1365 {
1366 #if FS_STATS_DETAILED
1367     Date currDate;              /*Current date*/
1368     int writeIdx;               /*Write index to bump*/
1369     int timeIdx;                /*Authorship time index to bump*/
1370 #endif /* FS_STATS_DETAILED */
1371
1372     if (Caller & (TVS_CFILE|TVS_SLINK|TVS_MKDIR))       {   /* initialize new file */
1373         targetptr->disk.parent = parentptr->vnodeNumber;
1374         VN_SET_LEN(targetptr, length);
1375         /* targetptr->disk.group =      0;  save some cycles */
1376         targetptr->disk.modeBits = 0777;
1377         targetptr->disk.owner = client->ViceId;
1378         targetptr->disk.dataVersion =  0 ; /* consistent with the client */
1379         targetptr->disk.linkCount = (Caller & TVS_MKDIR ? 2 : 1);
1380         /* the inode was created in Alloc_NewVnode() */
1381     }
1382
1383 #if FS_STATS_DETAILED
1384     /*
1385      * Update file write stats for this volume.  Note that the auth
1386      * counter is located immediately after its associated ``distance''
1387      * counter.
1388      */
1389     if (client->InSameNetwork)
1390         writeIdx = VOL_STATS_SAME_NET;
1391     else
1392         writeIdx = VOL_STATS_DIFF_NET;
1393     V_stat_writes(volptr, writeIdx)++;
1394     if (client->ViceId != AnonymousID) {
1395         V_stat_writes(volptr, writeIdx+1)++;
1396     }
1397
1398     /*
1399      * We only count operations that DON'T involve creating new objects
1400      * (files, symlinks, directories) or simply setting status as
1401      * authorship-change operations.
1402      */
1403     if (!(Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR | TVS_SSTATUS))) {
1404         /*
1405          * Update the volume's authorship information in response to this
1406          * file operation.  Get the current time, decide to which time
1407          * slot this operation belongs, and bump the appropriate slot.
1408          */
1409         currDate = (FT_ApproxTime() - targetptr->disk.unixModifyTime);
1410         timeIdx = (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 :
1411                    currDate < VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 :
1412                    currDate < VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 :
1413                    currDate < VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 :
1414                    currDate < VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1415                    VOL_STATS_TIME_IDX_5);
1416         if (targetptr->disk.author == client->ViceId) {
1417             V_stat_fileSameAuthor(volptr, timeIdx)++;
1418         } else {
1419             V_stat_fileDiffAuthor(volptr, timeIdx)++;
1420         }
1421       }
1422 #endif /* FS_STATS_DETAILED */
1423
1424     if (!(Caller & TVS_SSTATUS))
1425       targetptr->disk.author = client->ViceId;
1426     if (Caller & TVS_SDATA) {
1427       targetptr->disk.dataVersion++;
1428       if (VanillaUser(client))
1429         {
1430           targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1431 #ifdef CREATE_SGUID_ADMIN_ONLY
1432           targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1433 #endif
1434         }
1435     }
1436     if (Caller & TVS_SSTATUS) { /* update time on non-status change */
1437         /* store status, must explicitly request to change the date */
1438         if (InStatus->Mask & AFS_SETMODTIME)
1439             targetptr->disk.unixModifyTime = InStatus->ClientModTime;
1440     }
1441     else {/* other: date always changes, but perhaps to what is specified by caller */
1442         targetptr->disk.unixModifyTime = (InStatus->Mask & AFS_SETMODTIME ? InStatus->ClientModTime : FT_ApproxTime());
1443     }
1444     if (InStatus->Mask & AFS_SETOWNER) {
1445         /* admin is allowed to do chmod, chown as well as chown, chmod. */
1446         if (VanillaUser(client))
1447           {
1448             targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1449 #ifdef CREATE_SGUID_ADMIN_ONLY
1450             targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1451 #endif
1452           }
1453         targetptr->disk.owner = InStatus->Owner;
1454         if (VolumeRootVnode (targetptr)) {
1455             Error errorCode = 0;        /* what should be done with this? */
1456
1457             V_owner(targetptr->volumePtr) = InStatus->Owner;
1458             VUpdateVolume(&errorCode, targetptr->volumePtr);
1459         }
1460     }
1461     if (InStatus->Mask & AFS_SETMODE) {
1462         int modebits = InStatus->UnixModeBits;
1463 #define CREATE_SGUID_ADMIN_ONLY 1
1464 #ifdef CREATE_SGUID_ADMIN_ONLY
1465         if (VanillaUser(client)) 
1466             modebits = modebits & 0777;
1467 #endif
1468         if (VanillaUser(client)) {
1469           targetptr->disk.modeBits = modebits;
1470         }
1471         else {
1472           targetptr->disk.modeBits = modebits;
1473           switch ( Caller ) {
1474           case TVS_SDATA: osi_audit( PrivSetID, 0, AUD_INT, client->ViceId,
1475                                     AUD_INT, CHK_STOREDATA, AUD_END); break;
1476           case TVS_CFILE:
1477           case TVS_SSTATUS: osi_audit( PrivSetID, 0, AUD_INT, client->ViceId,
1478                                     AUD_INT, CHK_STORESTATUS, AUD_END); break;
1479           default: break;
1480           }
1481         }
1482       }
1483     targetptr->disk.serverModifyTime = FT_ApproxTime();
1484     if (InStatus->Mask & AFS_SETGROUP)
1485         targetptr->disk.group = InStatus->Group;
1486     /* vnode changed : to be written back by VPutVnode */
1487     targetptr->changed_newTime = 1;
1488
1489 } /*Update_TargetVnodeStatus*/
1490
1491
1492 /*
1493  * Fills the CallBack structure with the expiration time and type of callback
1494  * structure. Warning: this function is currently incomplete.
1495  */
1496 static void
1497 SetCallBackStruct(afs_uint32 CallBackTime, struct AFSCallBack *CallBack)
1498 {
1499     /* CallBackTime could not be 0 */
1500     if (CallBackTime == 0) {
1501         ViceLog(0, ("WARNING: CallBackTime == 0!\n"));
1502         CallBack->ExpirationTime = 0;
1503     } else
1504         CallBack->ExpirationTime = CallBackTime - FT_ApproxTime();      
1505     CallBack->CallBackVersion = CALLBACK_VERSION;
1506     CallBack->CallBackType = CB_SHARED;             /* The default for now */
1507
1508 } /*SetCallBackStruct*/
1509
1510
1511 /*
1512  * Adjusts (Subtract) "length" number of blocks from the volume's disk
1513  * allocation; if some error occured (exceeded volume quota or partition
1514  * was full, or whatever), it frees the space back and returns the code.
1515  * We usually pre-adjust the volume space to make sure that there's
1516  * enough space before consuming some.
1517  */
1518 static afs_int32
1519 AdjustDiskUsage(Volume *volptr, afs_int32 length, afs_int32 checkLength)
1520 {
1521     int rc;
1522     int nc;
1523
1524     VAdjustDiskUsage(&rc, volptr, length, checkLength);
1525     if (rc) {
1526         VAdjustDiskUsage(&nc, volptr, -length, 0);
1527         if (rc == VOVERQUOTA) {
1528             ViceLog(2,("Volume %u (%s) is full\n",
1529                     V_id(volptr), V_name(volptr)));
1530             return(rc);
1531         }
1532         if (rc == VDISKFULL) {
1533             ViceLog(0,("Partition %s that contains volume %u is full\n",
1534                     volptr->partition->name, V_id(volptr)));
1535             return(rc);
1536         }
1537         ViceLog(0,("Got error return %d from VAdjustDiskUsage\n",rc));
1538         return(rc);
1539     }
1540     return(0);
1541
1542 } /*AdjustDiskUsage*/
1543
1544 /*
1545  * Common code that handles the creation of a new file (SAFS_CreateFile and
1546  * SAFS_Symlink) or a new dir (SAFS_MakeDir)
1547  */
1548 static afs_int32
1549 Alloc_NewVnode(Vnode *parentptr,
1550                DirHandle *dir,
1551                Volume *volptr,
1552                Vnode **targetptr,
1553                char *Name,
1554                struct AFSFid *OutFid,
1555                int FileType,
1556                int BlocksPreallocatedForVnode)
1557 {
1558     int errorCode = 0;          /* Error code returned back */
1559     int temp;
1560     Inode inode=0;
1561     Inode nearInode;            /* hint for inode allocation in solaris */
1562
1563     if ((errorCode = AdjustDiskUsage(volptr, BlocksPreallocatedForVnode,
1564                                     BlocksPreallocatedForVnode))) {
1565         ViceLog(25, ("Insufficient space to allocate %d blocks\n", 
1566                      BlocksPreallocatedForVnode));
1567         return(errorCode);
1568     }
1569
1570     *targetptr = VAllocVnode(&errorCode, volptr, FileType);
1571     if (errorCode != 0) {
1572         VAdjustDiskUsage(&temp, volptr, - BlocksPreallocatedForVnode, 0);
1573         return(errorCode);
1574     }
1575     OutFid->Volume = V_id(volptr);
1576     OutFid->Vnode = (*targetptr)->vnodeNumber;
1577     OutFid->Unique = (*targetptr)->disk.uniquifier;
1578
1579     nearInode = VN_GET_INO(parentptr);   /* parent is also in same vol */
1580
1581     /* create the inode now itself */
1582     inode = IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1583                       VPartitionPath(V_partition(volptr)), nearInode,
1584                       V_id(volptr), (*targetptr)->vnodeNumber,
1585                       (*targetptr)->disk.uniquifier, 1);
1586
1587     /* error in creating inode */
1588     if (!VALID_INO(inode)) 
1589     {
1590                ViceLog(0, ("Volume : %d vnode = %d Failed to create inode: errno = %d\n", 
1591                          (*targetptr)->volumePtr->header->diskstuff.id,
1592                          (*targetptr)->vnodeNumber, 
1593                          errno));
1594                 VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode,0);
1595                 (*targetptr)->delete = 1; /* delete vnode */
1596                 return ENOSPC;
1597     }
1598     VN_SET_INO(*targetptr, inode);
1599     IH_INIT(((*targetptr)->handle), V_device(volptr), V_id(volptr), inode);
1600
1601     /* copy group from parent dir */
1602     (*targetptr)->disk.group = parentptr->disk.group;
1603
1604     if (parentptr->disk.cloned) 
1605     {
1606         ViceLog(25, ("Alloc_NewVnode : CopyOnWrite called\n"));
1607         if ((errorCode = CopyOnWrite(parentptr, volptr)))  /* disk full */
1608         {
1609                 ViceLog(25, ("Alloc_NewVnode : CopyOnWrite failed\n"));
1610                 /* delete the vnode previously allocated */
1611                 (*targetptr)->delete = 1;
1612                 VAdjustDiskUsage(&temp, volptr,
1613                                  -BlocksPreallocatedForVnode, 0);
1614                 IH_REALLYCLOSE((*targetptr)->handle);
1615                 if ( IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)) )
1616                     ViceLog(0,("Alloc_NewVnode: partition %s idec %s failed\n",
1617                                 volptr->partition->name,
1618                                PrintInode(NULL, inode)));
1619                 IH_RELEASE((*targetptr)->handle);
1620                         
1621                 return errorCode;
1622         }
1623     }
1624     
1625     /* add the name to the directory */
1626     SetDirHandle(dir, parentptr);
1627     if ((errorCode = Create(dir,(char *)Name, OutFid))) {
1628         (*targetptr)->delete = 1;
1629         VAdjustDiskUsage(&temp, volptr, - BlocksPreallocatedForVnode, 0);
1630         IH_REALLYCLOSE((*targetptr)->handle);
1631         if ( IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1632             ViceLog(0,("Alloc_NewVnode: partition %s idec %s failed\n",
1633                        volptr->partition->name,
1634                        PrintInode(NULL, inode)));
1635         IH_RELEASE((*targetptr)->handle);
1636         return(errorCode);
1637     }
1638     DFlush();
1639     return(0);
1640
1641 } /*Alloc_NewVnode*/
1642
1643
1644 /*
1645  * Handle all the lock-related code (SAFS_SetLock, SAFS_ExtendLock and
1646  * SAFS_ReleaseLock)
1647  */
1648 static afs_int32
1649 HandleLocking(Vnode *targetptr, afs_int32 rights, ViceLockType LockingType)
1650 {
1651     int Time;           /* Used for time */
1652     int writeVnode = targetptr->changed_oldTime; /* save original status */
1653
1654     /* Does the caller has Lock priviledges; root extends locks, however */
1655     if (LockingType != LockExtend && !(rights & PRSFS_LOCK))
1656         return(EACCES);
1657     targetptr->changed_oldTime = 1; /* locking doesn't affect any time stamp */
1658     Time = FT_ApproxTime();
1659     switch (LockingType) {
1660         case LockRead:
1661         case LockWrite:
1662             if (Time > targetptr->disk.lock.lockTime)
1663                 targetptr->disk.lock.lockTime = targetptr->disk.lock.lockCount = 0;
1664             Time += AFS_LOCKWAIT;
1665             if (LockingType == LockRead) {
1666                 if (targetptr->disk.lock.lockCount >= 0) {
1667                     ++(targetptr->disk.lock.lockCount);
1668                     targetptr->disk.lock.lockTime = Time;
1669                 } else return(EAGAIN);
1670             } else {
1671                 if (targetptr->disk.lock.lockCount == 0) {
1672                     targetptr->disk.lock.lockCount = -1;
1673                     targetptr->disk.lock.lockTime = Time;
1674                 } else return(EAGAIN);
1675             }
1676             break;
1677         case LockExtend:
1678             Time += AFS_LOCKWAIT;
1679             if (targetptr->disk.lock.lockCount != 0)
1680                 targetptr->disk.lock.lockTime = Time;
1681             else return(EINVAL);            
1682             break;
1683         case LockRelease:
1684             if ((--targetptr->disk.lock.lockCount) <= 0)
1685                 targetptr->disk.lock.lockCount = targetptr->disk.lock.lockTime = 0;
1686             break;
1687         default:
1688             targetptr->changed_oldTime = writeVnode; /* restore old status */
1689             ViceLog(0, ("Illegal Locking type %d\n", LockingType));
1690     }
1691     return(0);
1692 } /*HandleLocking*/
1693
1694 /* Checks if caller has the proper AFS and Unix (WRITE) access permission to the target directory; Prfs_Mode refers to the AFS Mode operation while rights contains the caller's access permissions to the directory. */
1695
1696 static afs_int32
1697 CheckWriteMode(Vnode *targetptr, afs_int32 rights, int Prfs_Mode)
1698 {
1699     if (readonlyServer)
1700         return(VREADONLY);
1701     if (!(rights & Prfs_Mode))
1702         return(EACCES);
1703     if ((targetptr->disk.type != vDirectory) && (!(targetptr->disk.modeBits & OWNERWRITE)))
1704         return(EACCES);
1705     return(0);
1706 }
1707
1708 /*
1709  * If some flags (i.e. min or max quota) are set, the volume's in disk
1710  * label is updated; Name, OfflineMsg, and Motd are also reflected in the
1711  * update, if applicable.
1712  */
1713 static afs_int32
1714 RXUpdate_VolumeStatus(Volume *volptr, AFSStoreVolumeStatus* StoreVolStatus,
1715                       char *Name, char *OfflineMsg, char *Motd)
1716 {
1717     Error errorCode = 0;
1718
1719     if (StoreVolStatus->Mask & AFS_SETMINQUOTA)
1720         V_minquota(volptr) = StoreVolStatus->MinQuota;
1721     if (StoreVolStatus->Mask & AFS_SETMAXQUOTA)
1722         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
1723     if (strlen(OfflineMsg) > 0) {
1724         strcpy(V_offlineMessage(volptr), OfflineMsg);
1725     }
1726     if (strlen(Name) > 0) {
1727         strcpy(V_name(volptr), Name);
1728     }
1729 #if OPENAFS_VOL_STATS
1730     /*
1731      * We don't overwrite the motd field, since it's now being used
1732      * for stats
1733      */
1734 #else
1735     if (strlen(Motd) > 0) {
1736         strcpy(V_motd(volptr), Motd);
1737     }
1738 #endif /* FS_STATS_DETAILED */
1739     VUpdateVolume(&errorCode, volptr);
1740     return(errorCode);
1741
1742 } /*RXUpdate_VolumeStatus*/
1743
1744
1745 /* old interface */
1746 static afs_int32
1747 Update_VolumeStatus(Volume *volptr, VolumeStatus *StoreVolStatus,
1748                     struct BBS *Name, struct BBS *OfflineMsg,
1749                     struct BBS *Motd)
1750 {
1751     Error errorCode = 0;
1752
1753     if (StoreVolStatus->MinQuota > -1)
1754         V_minquota(volptr) = StoreVolStatus->MinQuota;
1755     if (StoreVolStatus->MaxQuota > -1)
1756         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
1757     if (OfflineMsg->SeqLen > 1)
1758         strcpy(V_offlineMessage(volptr), OfflineMsg->SeqBody);
1759     if (Name->SeqLen > 1)
1760         strcpy(V_name(volptr), Name->SeqBody);
1761 #if OPENAFS_VOL_STATS
1762     /*
1763      * We don't overwrite the motd field, since it's now being used
1764      * for stats
1765      */
1766 #else
1767     if (Motd->SeqLen > 1)
1768         strcpy(V_motd(volptr), Motd->SeqBody);
1769 #endif /* FS_STATS_DETAILED */
1770     VUpdateVolume(&errorCode, volptr);
1771     return(errorCode);
1772
1773 } /*Update_VolumeStatus*/
1774
1775
1776 /*
1777  * Get internal volume-related statistics from the Volume disk label
1778  * structure and put it into the VolumeStatus structure, status; it's
1779  * used by both SAFS_GetVolumeStatus and SAFS_SetVolumeStatus to return
1780  * the volume status to the caller.
1781  */
1782 static afs_int32
1783 GetVolumeStatus(VolumeStatus *status, struct BBS *name, struct BBS *offMsg,
1784                 struct BBS *motd, Volume *volptr)
1785 {
1786     status->Vid = V_id(volptr);
1787     status->ParentId = V_parentId(volptr);
1788     status->Online = V_inUse(volptr);
1789     status->InService = V_inService(volptr);
1790     status->Blessed = V_blessed(volptr);
1791     status->NeedsSalvage = V_needsSalvaged(volptr);
1792     if (VolumeWriteable(volptr))
1793         status->Type = ReadWrite;
1794     else
1795         status->Type = ReadOnly;
1796     status->MinQuota = V_minquota(volptr);
1797     status->MaxQuota = V_maxquota(volptr);
1798     status->BlocksInUse = V_diskused(volptr);
1799     status->PartBlocksAvail = volptr->partition->free;
1800     status->PartMaxBlocks = volptr->partition->totalUsable;
1801     strncpy(name->SeqBody, V_name(volptr), (int)name->MaxSeqLen);
1802     name->SeqLen = strlen(V_name(volptr)) + 1;
1803     if (name->SeqLen > name->MaxSeqLen) name->SeqLen = name -> MaxSeqLen;
1804     strncpy(offMsg->SeqBody, V_offlineMessage(volptr), (int)name->MaxSeqLen);
1805     offMsg->SeqLen = strlen(V_offlineMessage(volptr)) + 1;
1806     if (offMsg->SeqLen > offMsg->MaxSeqLen)
1807         offMsg->SeqLen = offMsg -> MaxSeqLen;
1808 #ifdef notdef
1809     /*Don't do anything with the motd field*/
1810     strncpy(motd->SeqBody, nullString, (int)offMsg->MaxSeqLen);
1811     motd->SeqLen = strlen(nullString) + 1;
1812 #endif
1813     if (motd->SeqLen > motd->MaxSeqLen)
1814         motd->SeqLen = motd -> MaxSeqLen;
1815
1816 } /*GetVolumeStatus*/
1817
1818 static afs_int32
1819 RXGetVolumeStatus(AFSFetchVolumeStatus *status, char **name, char **offMsg,
1820                   char **motd, Volume *volptr)
1821 {
1822     int temp;
1823
1824     status->Vid = V_id(volptr);
1825     status->ParentId = V_parentId(volptr);
1826     status->Online = V_inUse(volptr);
1827     status->InService = V_inService(volptr);
1828     status->Blessed = V_blessed(volptr);
1829     status->NeedsSalvage = V_needsSalvaged(volptr);
1830     if (VolumeWriteable(volptr))
1831         status->Type = ReadWrite;
1832     else
1833         status->Type = ReadOnly;
1834     status->MinQuota = V_minquota(volptr);
1835     status->MaxQuota = V_maxquota(volptr);
1836     status->BlocksInUse = V_diskused(volptr);
1837     status->PartBlocksAvail = volptr->partition->free;
1838     status->PartMaxBlocks = volptr->partition->totalUsable;
1839
1840     /* now allocate and copy these things; they're freed by the RXGEN stub */
1841     temp = strlen(V_name(volptr)) + 1;
1842     *name = malloc(temp);
1843     if (!*name) {
1844         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1845         assert(0);
1846     }
1847     strcpy(*name, V_name(volptr));
1848     temp = strlen(V_offlineMessage(volptr)) + 1;
1849     *offMsg = malloc(temp);
1850     if (!*offMsg) {
1851         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1852         assert(0);
1853     }
1854     strcpy(*offMsg, V_offlineMessage(volptr));
1855 #if OPENAFS_VOL_STATS
1856     *motd = malloc(1);
1857     if (!*motd) {
1858         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1859         assert(0);
1860     }
1861     strcpy(*motd, nullString);
1862 #else
1863     temp = strlen(V_motd(volptr)) + 1;
1864     *motd = malloc(temp);
1865     if (!*motd) {
1866         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1867         assert(0);
1868     }
1869     strcpy(*motd, V_motd(volptr));
1870 #endif /* FS_STATS_DETAILED */
1871
1872 } /*RXGetVolumeStatus*/
1873
1874
1875 static afs_int32
1876 FileNameOK(register char *aname)
1877 {
1878     register afs_int32 i, tc;
1879     i = strlen(aname);
1880     if (i >= 4) {
1881         /* watch for @sys on the right */
1882         if (strcmp(aname+i-4, "@sys") == 0) return 0;
1883     }
1884     while ((tc = *aname++)) {
1885         if (tc == '/') return 0;    /* very bad character to encounter */
1886     }
1887     return 1;   /* file name is ok */
1888
1889 } /*FileNameOK*/
1890
1891
1892 /* Debugging tool to print Volume Statu's contents */
1893 static void
1894 PrintVolumeStatus(VolumeStatus *status)
1895 {
1896     ViceLog(5,("Volume header contains:\n"));
1897     ViceLog(5,("Vid = %u, Parent = %u, Online = %d, InService = %d, Blessed = %d, NeedsSalvage = %d\n",
1898             status->Vid, status->ParentId, status->Online, status->InService,
1899             status->Blessed, status->NeedsSalvage));
1900     ViceLog(5,("MinQuota = %d, MaxQuota = %d\n", status->MinQuota, status->MaxQuota));
1901     ViceLog(5,("Type = %d, BlocksInUse = %d, PartBlocksAvail = %d, PartMaxBlocks = %d\n",
1902             status->Type, status->BlocksInUse, status->PartBlocksAvail, status->PartMaxBlocks));
1903
1904 } /*PrintVolumeStatus*/
1905
1906
1907 /*
1908  * This variant of symlink is expressly to support the AFS/DFS translator
1909  * and is not supported by the AFS fileserver. We just return EINVAL.
1910  * The cache manager should not generate this call to an AFS cache manager.
1911  */
1912 afs_int32 SRXAFS_DFSSymlink (struct rx_call *acall,
1913                              struct AFSFid *DirFid,
1914                              char *Name,
1915                              char *LinkContents,
1916                              struct AFSStoreStatus *InStatus,
1917                              struct AFSFid *OutFid,
1918                              struct AFSFetchStatus *OutFidStatus,
1919                              struct AFSFetchStatus *OutDirStatus,
1920                              struct AFSCallBack *CallBack,
1921                              struct AFSVolSync *Sync)
1922 {
1923     return EINVAL;
1924 }
1925
1926 afs_int32 SRXAFS_ResidencyCmd (struct rx_call *acall, struct AFSFid *Fid,
1927                                struct ResidencyCmdInputs *Inputs,
1928                                struct ResidencyCmdOutputs *Outputs)
1929 {
1930     return EINVAL;
1931 }
1932
1933 static struct afs_buffer {
1934     struct afs_buffer *next;
1935 } *freeBufferList = 0;
1936 static int afs_buffersAlloced = 0;
1937
1938 static FreeSendBuffer(register struct afs_buffer *adata)
1939 {
1940     FS_LOCK
1941     afs_buffersAlloced--;
1942     adata->next = freeBufferList;
1943     freeBufferList = adata;
1944     FS_UNLOCK
1945     return 0;
1946
1947 } /*FreeSendBuffer*/
1948
1949 /* allocate space for sender */
1950 static char *AllocSendBuffer()
1951 {
1952     register struct afs_buffer *tp;
1953
1954     FS_LOCK
1955     afs_buffersAlloced++;
1956     if (!freeBufferList) {
1957         char *tmp;
1958         FS_UNLOCK
1959
1960         tmp = malloc(sendBufSize);
1961         if (!tmp) {
1962             ViceLog(0, ("Failed malloc in AllocSendBuffer\n"));
1963             assert(0);
1964         }
1965         return tmp;
1966     }
1967     tp = freeBufferList;
1968     freeBufferList = tp->next;
1969     FS_UNLOCK
1970     return (char *) tp;
1971
1972 } /*AllocSendBuffer*/
1973
1974 /*
1975  * This routine returns the status info associated with the targetptr vnode
1976  * in the AFSFetchStatus structure.  Some of the newer fields, such as
1977  * SegSize and Group are not yet implemented
1978  */
1979 static 
1980 void GetStatus(Vnode *targetptr,
1981                AFSFetchStatus *status,
1982                afs_int32 rights,
1983                afs_int32 anyrights,
1984                Vnode *parentptr)
1985 {
1986     /* initialize return status from a vnode  */
1987     status->InterfaceVersion = 1;
1988     status->SyncCounter = status->dataVersionHigh = status->lockCount =
1989     status->errorCode = 0;
1990     status->ResidencyMask = 1; /* means for MR-AFS: file in /vicepr-partition */
1991     if (targetptr->disk.type == vFile)
1992         status->FileType = File;
1993     else if (targetptr->disk.type == vDirectory)
1994         status->FileType = Directory;
1995     else if (targetptr->disk.type == vSymlink)
1996         status->FileType = SymbolicLink;
1997     else
1998         status->FileType = Invalid;                     /*invalid type field */
1999     status->LinkCount = targetptr->disk.linkCount;
2000     {
2001         afs_fsize_t targetLen;
2002         VN_GET_LEN(targetLen, targetptr);
2003         SplitOffsetOrSize(targetLen, status->Length_hi, status->Length);
2004     }
2005     status->DataVersion = targetptr->disk.dataVersion;
2006     status->Author = targetptr->disk.author;
2007     status->Owner = targetptr->disk.owner;
2008     status->CallerAccess = rights;
2009     status->AnonymousAccess = anyrights;
2010     status->UnixModeBits = targetptr->disk.modeBits;
2011     status->ClientModTime = targetptr->disk.unixModifyTime;     /* This might need rework */
2012     status->ParentVnode = (status->FileType == Directory ? targetptr->vnodeNumber : parentptr->vnodeNumber);
2013     status->ParentUnique = (status->FileType == Directory ? targetptr->disk.uniquifier : parentptr->disk.uniquifier);
2014     status->ServerModTime = targetptr->disk.serverModifyTime;                   
2015     status->Group = targetptr->disk.group;
2016     status->lockCount = targetptr->disk.lock.lockCount;
2017     status->errorCode = 0;
2018
2019 } /*GetStatus*/
2020
2021 static
2022 afs_int32 common_FetchData64 (struct rx_call *acall, 
2023                               struct AFSFid *Fid,    
2024                               afs_int32 Pos,         
2025                               afs_int32 Len,         
2026                               struct AFSFetchStatus *OutStatus,
2027                               struct AFSCallBack *CallBack,
2028                               struct AFSVolSync *Sync,
2029                               int type)              
2030
2031     Vnode * targetptr = 0;                  /* pointer to vnode to fetch */
2032     Vnode * parentwhentargetnotdir = 0;     /* parent vnode if vptr is a file */
2033     Vnode   tparentwhentargetnotdir;        /* parent vnode for GetStatus */
2034     int     errorCode = 0;                  /* return code to caller */
2035     int     fileCode =  0;                  /* return code from vol package */
2036     Volume * volptr = 0;                    /* pointer to the volume */
2037     struct client *client;                  /* pointer to the client data */
2038     struct rx_connection *tcon;             /* the connection we're part of */
2039     afs_int32 rights, anyrights;                    /* rights for this and any user */
2040     struct client *t_client;                /* tmp ptr to client data */
2041     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
2042 #if FS_STATS_DETAILED
2043     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2044     struct fs_stats_xferData *xferP;        /* Ptr to this op's byte size struct */
2045     struct timeval opStartTime,
2046                    opStopTime;              /* Start/stop times for RPC op*/
2047     struct timeval xferStartTime,
2048                    xferStopTime;            /* Start/stop times for xfer portion*/
2049     struct timeval elapsedTime;             /* Transfer time */
2050     afs_int32 bytesToXfer;                          /* # bytes to xfer*/
2051     afs_int32 bytesXferred;                         /* # bytes actually xferred*/
2052     int readIdx;                            /* Index of read stats array to bump*/
2053     static afs_int32 tot_bytesXferred; /* shared access protected by FS_LOCK */
2054
2055     /*
2056      * Set our stats pointers, remember when the RPC operation started, and
2057      * tally the operation.
2058      */
2059     opP   = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHDATA]);
2060     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_FETCHDATA]);
2061     FS_LOCK
2062     (opP->numOps)++;
2063     FS_UNLOCK
2064     TM_GetTimeOfDay(&opStartTime, 0);
2065 #endif /* FS_STATS_DETAILED */
2066
2067     ViceLog(1,("SRXAFS_FetchData, Fid = %u.%d.%d\n",
2068             Fid->Volume, Fid->Vnode, Fid->Unique));     
2069     FS_LOCK
2070     AFSCallStats.FetchData++, AFSCallStats.TotalCalls++;
2071     FS_UNLOCK
2072
2073     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon))
2074         goto Bad_FetchData;
2075
2076     /* Get ptr to client data for user Id for logging */
2077     t_client = (struct client *)  rx_GetSpecific(tcon, rxcon_client_key);
2078     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2079     ViceLog(5,("SRXAFS_FetchData, Fid = %u.%d.%d, Host %s, Id %d\n",
2080             Fid->Volume, Fid->Vnode, Fid->Unique,
2081             inet_ntoa(logHostAddr), t_client->ViceId)); 
2082     /*
2083      * Get volume/vnode for the fetched file; caller's access rights to
2084      * it are also returned
2085      */
2086     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2087                                      DONTCHECK, &parentwhentargetnotdir,
2088                                      &client, READ_LOCK, &rights, &anyrights)))
2089         goto Bad_FetchData;
2090
2091     SetVolumeSync(Sync, volptr);
2092
2093 #if FS_STATS_DETAILED
2094     /*
2095      * Remember that another read operation was performed.
2096      */
2097     FS_LOCK
2098     if (client->InSameNetwork)
2099         readIdx = VOL_STATS_SAME_NET;
2100     else
2101         readIdx = VOL_STATS_DIFF_NET;
2102     V_stat_reads(volptr, readIdx)++;
2103     if (client->ViceId != AnonymousID) {
2104         V_stat_reads(volptr, readIdx+1)++;
2105     }
2106     FS_UNLOCK
2107 #endif /* FS_STATS_DETAILED */
2108
2109     /* Check whether the caller has permission access to fetch the data */
2110     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2111                                            CHK_FETCHDATA, 0))) 
2112         goto Bad_FetchData;
2113
2114     /*
2115      * Drop the read lock on the parent directory after saving the parent
2116      * vnode information we need to pass to GetStatus
2117      */
2118     if (parentwhentargetnotdir != NULL) {
2119         tparentwhentargetnotdir = *parentwhentargetnotdir;
2120         VPutVnode(&fileCode, parentwhentargetnotdir);
2121         assert(!fileCode || (fileCode == VSALVAGE));
2122         parentwhentargetnotdir = NULL;
2123     }
2124
2125 #if FS_STATS_DETAILED
2126     /*
2127      * Remember when the data transfer started.
2128      */
2129     TM_GetTimeOfDay(&xferStartTime, 0);
2130 #endif /* FS_STATS_DETAILED */
2131
2132     /* actually do the data transfer */
2133 #if FS_STATS_DETAILED
2134     errorCode = FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type,
2135                                   &bytesToXfer, &bytesXferred);
2136 #else
2137     if ((errorCode = FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type)))
2138         goto Bad_FetchData;
2139 #endif /* FS_STATS_DETAILED */
2140
2141 #if FS_STATS_DETAILED
2142     /*
2143      * At this point, the data transfer is done, for good or ill.  Remember
2144      * when the transfer ended, bump the number of successes/failures, and
2145      * integrate the transfer size and elapsed time into the stats.  If the
2146      * operation failed, we jump to the appropriate point.
2147      */
2148     TM_GetTimeOfDay(&xferStopTime, 0);
2149     FS_LOCK
2150     (xferP->numXfers)++;
2151     if (!errorCode) {
2152         (xferP->numSuccesses)++;
2153
2154         /*
2155          * Bump the xfer sum by the number of bytes actually sent, NOT the
2156          * target number.
2157          */
2158         tot_bytesXferred += bytesXferred;
2159         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2160         tot_bytesXferred &= 0x3FF;
2161         if (bytesXferred < xferP->minBytes)
2162             xferP->minBytes = bytesXferred;
2163         if (bytesXferred > xferP->maxBytes)
2164             xferP->maxBytes = bytesXferred;
2165
2166         /*
2167          * Tally the size of the object.  Note: we tally the actual size,
2168          * NOT the number of bytes that made it out over the wire.
2169          */
2170         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2171             (xferP->count[0])++;
2172         else
2173             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2174                 (xferP->count[1])++;
2175         else
2176             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
2177                 (xferP->count[2])++;
2178         else
2179             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
2180                 (xferP->count[3])++;
2181         else
2182             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
2183                 (xferP->count[4])++;
2184         else
2185             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
2186                 (xferP->count[5])++;
2187         else
2188             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
2189                 (xferP->count[6])++;
2190         else
2191             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
2192                 (xferP->count[7])++;
2193         else
2194             (xferP->count[8])++;
2195
2196         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
2197         fs_stats_AddTo((xferP->sumTime), elapsedTime);
2198         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
2199         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
2200             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
2201         }
2202         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
2203             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
2204         }
2205       }
2206     FS_UNLOCK
2207     /*
2208      * Finally, go off to tell our caller the bad news in case the
2209      * fetch failed.
2210      */
2211     if (errorCode)
2212         goto Bad_FetchData;
2213 #endif /* FS_STATS_DETAILED */
2214
2215     /* write back  the OutStatus from the target vnode  */
2216     GetStatus(targetptr, OutStatus, rights, anyrights, &tparentwhentargetnotdir);
2217
2218     /* if a r/w volume, promise a callback to the caller */
2219     if (VolumeWriteable(volptr))
2220         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2221     else {
2222       struct AFSFid myFid;              
2223       memset(&myFid, 0, sizeof(struct AFSFid));
2224       myFid.Volume = Fid->Volume;
2225       SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2226       }
2227
2228 Bad_FetchData: 
2229     /* Update and store volume/vnode and parent vnodes back */
2230     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2231                             volptr);
2232     ViceLog(2, ("SRXAFS_FetchData returns %d\n", errorCode)); 
2233     errorCode = CallPostamble(tcon, errorCode);
2234
2235 #if FS_STATS_DETAILED
2236     TM_GetTimeOfDay(&opStopTime, 0);
2237     if (errorCode == 0) {
2238         FS_LOCK
2239         (opP->numSuccesses)++;
2240         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2241         fs_stats_AddTo((opP->sumTime), elapsedTime);
2242         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2243         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2244             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2245         }
2246         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2247             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2248         }
2249         FS_UNLOCK
2250       }
2251
2252 #endif /* FS_STATS_DETAILED */
2253
2254     osi_auditU (acall, FetchDataEvent, errorCode, AUD_FID, Fid, AUD_END);
2255     return(errorCode);
2256
2257 } /*SRXAFS_FetchData*/
2258
2259 afs_int32 SRXAFS_FetchData (struct rx_call *acall,   
2260                             struct AFSFid *Fid,      
2261                             afs_int32 Pos,           
2262                             afs_int32 Len,           
2263                             struct AFSFetchStatus *OutStatus,
2264                             struct AFSCallBack *CallBack, 
2265                             struct AFSVolSync *Sync) 
2266
2267 {
2268     int code;
2269
2270     code = common_FetchData64 (acall, Fid, Pos, Len, OutStatus,
2271                              CallBack, Sync, 0);
2272     return code;
2273 }
2274
2275 afs_int32 SRXAFS_FetchData64 (struct rx_call *acall, 
2276                               struct AFSFid *Fid,    
2277                               afs_int64 Pos,         
2278                               afs_int64 Len,         
2279                               struct AFSFetchStatus *OutStatus,
2280                               struct AFSCallBack *CallBack,
2281                               struct AFSVolSync *Sync)
2282 {
2283     int code;
2284     afs_int32 tPos, tLen;
2285
2286 #ifdef AFS_64BIT_ENV
2287     if (Pos + Len > 0x7fffffff)
2288         return E2BIG;
2289     tPos = Pos;
2290     tLen = Len;
2291 #else /* AFS_64BIT_ENV */
2292     if (Pos.high || Len.high)
2293         return E2BIG;
2294     tPos = Pos.low;
2295     tLen = Len.low;
2296 #endif /* AFS_64BIT_ENV */
2297
2298     code = common_FetchData64 (acall, Fid, tPos, tLen, OutStatus,
2299                              CallBack, Sync, 1);
2300     return code;
2301 }
2302
2303 afs_int32 SRXAFS_FetchACL (struct rx_call *acall,    
2304                            struct AFSFid *Fid,       
2305                            struct AFSOpaque *AccessList,     
2306                            struct AFSFetchStatus *OutStatus, 
2307                            struct AFSVolSync *Sync)
2308 {
2309     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2310     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2311     int     errorCode = 0;              /* return error code to caller */
2312     Volume * volptr = 0;                /* pointer to the volume */
2313     struct client *client;              /* pointer to the client data */
2314     afs_int32 rights, anyrights;                /* rights for this and any user */
2315     struct rx_connection *tcon = rx_ConnectionOf(acall);
2316     struct client *t_client;                /* tmp ptr to client data */
2317     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
2318 #if FS_STATS_DETAILED
2319     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2320     struct timeval opStartTime,
2321                    opStopTime;              /* Start/stop times for RPC op*/
2322     struct timeval elapsedTime;             /* Transfer time */
2323
2324     /*
2325      * Set our stats pointer, remember when the RPC operation started, and
2326      * tally the operation.
2327      */
2328     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHACL]);
2329     FS_LOCK
2330     (opP->numOps)++;
2331     FS_UNLOCK
2332     TM_GetTimeOfDay(&opStartTime, 0);
2333 #endif /* FS_STATS_DETAILED */
2334
2335     ViceLog(1, ("SAFS_FetchACL, Fid = %u.%d.%d\n",
2336             Fid->Volume, Fid->Vnode, Fid->Unique));
2337     FS_LOCK
2338     AFSCallStats.FetchACL++, AFSCallStats.TotalCalls++;
2339     FS_UNLOCK
2340     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
2341         goto Bad_FetchACL;
2342
2343     /* Get ptr to client data for user Id for logging */
2344     t_client = (struct client *)  rx_GetSpecific(tcon, rxcon_client_key);
2345     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2346     ViceLog(5, ("SAFS_FetchACL, Fid = %u.%d.%d, Host %s, Id %d\n",
2347             Fid->Volume, Fid->Vnode, Fid->Unique,
2348             inet_ntoa(logHostAddr), t_client->ViceId));
2349
2350     AccessList->AFSOpaque_len = 0;
2351     AccessList->AFSOpaque_val = malloc(AFSOPAQUEMAX);
2352     if (!AccessList->AFSOpaque_val) {
2353         ViceLog(0, ("Failed malloc in SRXAFS_FetchACL\n"));
2354         assert(0);
2355     }
2356
2357     /*
2358      * Get volume/vnode for the fetched file; caller's access rights to it
2359      * are also returned
2360      */
2361     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2362                                      DONTCHECK, &parentwhentargetnotdir,
2363                                      &client, READ_LOCK, &rights, &anyrights)))
2364         goto Bad_FetchACL;
2365
2366     SetVolumeSync(Sync, volptr);
2367
2368     /* Check whether we have permission to fetch the ACL */
2369     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2370                                            CHK_FETCHACL, 0)))
2371         goto Bad_FetchACL;
2372
2373     /* Get the Access List from the dir's vnode */
2374     if ((errorCode = RXFetch_AccessList(targetptr, parentwhentargetnotdir,
2375                                        AccessList)))
2376         goto Bad_FetchACL;
2377
2378     /* Get OutStatus back From the target Vnode  */
2379     GetStatus(targetptr, OutStatus, rights, anyrights, parentwhentargetnotdir);
2380
2381 Bad_FetchACL: 
2382     /* Update and store volume/vnode and parent vnodes back */
2383     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2384                             volptr);
2385     ViceLog(2, ("SAFS_FetchACL returns %d (ACL=%s)\n",
2386             errorCode, AccessList->AFSOpaque_val));
2387     errorCode = CallPostamble(tcon, errorCode);
2388
2389 #if FS_STATS_DETAILED
2390     TM_GetTimeOfDay(&opStopTime, 0);
2391     if (errorCode == 0) {
2392         FS_LOCK
2393         (opP->numSuccesses)++;
2394         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2395         fs_stats_AddTo((opP->sumTime), elapsedTime);
2396         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2397         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2398             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2399         }
2400         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2401             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2402         }
2403         FS_UNLOCK
2404       }
2405
2406 #endif /* FS_STATS_DETAILED */
2407
2408     osi_auditU (acall, FetchACLEvent, errorCode, AUD_FID, Fid, AUD_END);
2409     return errorCode;
2410 } /*SRXAFS_FetchACL*/
2411
2412
2413 /*
2414  * This routine is called exclusively by SRXAFS_FetchStatus(), and should be
2415  * merged into it when possible.
2416  */
2417 static 
2418 afs_int32 SAFSS_FetchStatus (struct rx_call *acall,
2419                              struct AFSFid *Fid,  
2420                              struct AFSFetchStatus *OutStatus,
2421                              struct AFSCallBack *CallBack,      
2422                              struct AFSVolSync *Sync)           
2423 {
2424     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2425     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2426     int     errorCode = 0;              /* return code to caller */
2427     Volume * volptr = 0;                /* pointer to the volume */
2428     struct client *client;              /* pointer to the client data */
2429     afs_int32 rights, anyrights;                /* rights for this and any user */
2430     struct client *t_client;            /* tmp ptr to client data */
2431     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
2432     struct rx_connection *tcon = rx_ConnectionOf(acall);
2433
2434     /* Get ptr to client data for user Id for logging */
2435     t_client = (struct client *)  rx_GetSpecific(tcon, rxcon_client_key);
2436     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2437     ViceLog(1, ("SAFS_FetchStatus,  Fid = %u.%d.%d, Host %s, Id %d\n",
2438             Fid->Volume, Fid->Vnode, Fid->Unique,
2439             inet_ntoa(logHostAddr), t_client->ViceId));
2440     FS_LOCK
2441     AFSCallStats.FetchStatus++, AFSCallStats.TotalCalls++;
2442     FS_UNLOCK
2443     /*
2444      * Get volume/vnode for the fetched file; caller's rights to it are
2445      * also returned
2446      */
2447     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2448                                      DONTCHECK, &parentwhentargetnotdir,
2449                                      &client, READ_LOCK, &rights, &anyrights)))
2450         goto Bad_FetchStatus;
2451
2452     /* set volume synchronization information */
2453     SetVolumeSync(Sync, volptr);
2454
2455     /* Are we allowed to fetch Fid's status? */
2456     if (targetptr->disk.type != vDirectory) {
2457       if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2458                                              CHK_FETCHSTATUS, 0))) {
2459           if (rx_GetCallAbortCode(acall) == errorCode) 
2460               rx_SetCallAbortCode(acall, 0);
2461           goto Bad_FetchStatus;
2462       }
2463     }
2464
2465     /* set OutStatus From the Fid  */
2466     GetStatus(targetptr, OutStatus, rights, anyrights, parentwhentargetnotdir);
2467
2468     /* If a r/w volume, also set the CallBack state */
2469     if (VolumeWriteable(volptr))
2470         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2471     else {
2472       struct AFSFid myFid;              
2473       memset(&myFid, 0, sizeof(struct AFSFid));
2474       myFid.Volume = Fid->Volume;
2475       SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2476       }
2477
2478 Bad_FetchStatus: 
2479     /* Update and store volume/vnode and parent vnodes back */
2480     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2481                             volptr);
2482     ViceLog(2, ("SAFS_FetchStatus returns %d\n", errorCode)); 
2483     return errorCode;
2484
2485 } /*SAFSS_FetchStatus*/
2486
2487
2488 afs_int32 SRXAFS_BulkStatus(struct rx_call *acall,
2489                             struct AFSCBFids *Fids,
2490                             struct AFSBulkStats *OutStats,
2491                             struct AFSCBs *CallBacks,
2492                             struct AFSVolSync *Sync)
2493 {
2494     register int i;
2495     afs_int32 nfiles;
2496     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2497     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2498     int     errorCode = 0;              /* return code to caller */
2499     Volume * volptr = 0;                /* pointer to the volume */
2500     struct client *client;              /* pointer to the client data */
2501     afs_int32 rights, anyrights;                /* rights for this and any user */
2502     register struct AFSFid *tfid;       /* file id we're dealing with now */
2503     struct rx_connection *tcon = rx_ConnectionOf(acall);
2504 #if FS_STATS_DETAILED
2505     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2506     struct timeval opStartTime,
2507                    opStopTime;              /* Start/stop times for RPC op*/
2508     struct timeval elapsedTime;             /* Transfer time */
2509
2510     /*
2511      * Set our stats pointer, remember when the RPC operation started, and
2512      * tally the operation.
2513      */
2514     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2515     FS_LOCK
2516     (opP->numOps)++;
2517     FS_UNLOCK
2518     TM_GetTimeOfDay(&opStartTime, 0);
2519 #endif /* FS_STATS_DETAILED */
2520
2521     ViceLog(1, ("SAFS_BulkStatus\n"));
2522     FS_LOCK
2523     AFSCallStats.TotalCalls++;
2524     FS_UNLOCK
2525
2526     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2527     if (nfiles <= 0) {                  /* Sanity check */
2528         errorCode = EINVAL;
2529         goto Audit_and_Return;
2530     }
2531
2532     /* allocate space for return output parameters */
2533     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2534         malloc(nfiles * sizeof(struct AFSFetchStatus));
2535     if (!OutStats->AFSBulkStats_val) {
2536         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2537         assert(0);
2538     }
2539     OutStats->AFSBulkStats_len = nfiles;
2540     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2541         malloc(nfiles * sizeof(struct AFSCallBack));
2542     if (!CallBacks->AFSCBs_val) {
2543         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2544         assert(0);
2545     }
2546     CallBacks->AFSCBs_len = nfiles;
2547
2548     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
2549         goto Bad_BulkStatus;
2550
2551     tfid = Fids->AFSCBFids_val;
2552     for (i=0; i<nfiles; i++, tfid++) {
2553         /*
2554          * Get volume/vnode for the fetched file; caller's rights to it
2555          * are also returned
2556          */
2557         if ((errorCode =
2558             GetVolumePackage(tcon, tfid, &volptr, &targetptr,
2559                              DONTCHECK, &parentwhentargetnotdir, &client,
2560                              READ_LOCK, &rights, &anyrights)))
2561                 goto Bad_BulkStatus;
2562         /* set volume synchronization information, but only once per call */
2563         if (i == nfiles)
2564             SetVolumeSync(Sync, volptr);
2565
2566         /* Are we allowed to fetch Fid's status? */
2567         if (targetptr->disk.type != vDirectory) {
2568             if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2569                                                    CHK_FETCHSTATUS, 0))) {
2570                 if (rx_GetCallAbortCode(acall) == errorCode) 
2571                     rx_SetCallAbortCode(acall, 0);
2572                 goto Bad_BulkStatus;
2573             }
2574         }
2575
2576         /* set OutStatus From the Fid  */
2577         GetStatus(targetptr, &OutStats->AFSBulkStats_val[i],
2578                   rights, anyrights, parentwhentargetnotdir);
2579
2580         /* If a r/w volume, also set the CallBack state */
2581         if (VolumeWriteable(volptr))
2582             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2583                               &CallBacks->AFSCBs_val[i]);
2584         else {
2585           struct AFSFid myFid;          
2586           memset(&myFid, 0, sizeof(struct AFSFid));
2587           myFid.Volume = tfid->Volume;
2588           SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2589                               &CallBacks->AFSCBs_val[i]);
2590         }
2591
2592         /* put back the file ID and volume */
2593         (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2594                                 volptr);
2595         parentwhentargetnotdir = (Vnode *) 0;
2596         targetptr = (Vnode *) 0;
2597         volptr = (Volume *) 0;
2598     }
2599
2600 Bad_BulkStatus: 
2601     /* Update and store volume/vnode and parent vnodes back */
2602     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2603                             volptr);
2604     errorCode = CallPostamble(tcon, errorCode);
2605
2606 #if FS_STATS_DETAILED
2607     TM_GetTimeOfDay(&opStopTime, 0);
2608     if (errorCode == 0) {
2609         FS_LOCK
2610         (opP->numSuccesses)++;
2611         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2612         fs_stats_AddTo((opP->sumTime), elapsedTime);
2613         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2614         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2615             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2616         }
2617         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2618             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2619         }
2620         FS_UNLOCK
2621     }   
2622
2623 #endif /* FS_STATS_DETAILED */
2624
2625 Audit_and_Return:
2626     ViceLog(2, ("SAFS_BulkStatus        returns %d\n", errorCode)); 
2627     osi_auditU (acall, BulkFetchStatusEvent, errorCode, AUD_FIDS, Fids, AUD_END);
2628     return errorCode;
2629
2630 } /*SRXAFS_BulkStatus*/
2631
2632
2633 afs_int32 SRXAFS_InlineBulkStatus(struct rx_call *acall,
2634                                   struct AFSCBFids *Fids,
2635                                   struct AFSBulkStats *OutStats,
2636                                   struct AFSCBs *CallBacks,
2637                                   struct AFSVolSync *Sync)
2638 {
2639     register int i;
2640     afs_int32 nfiles;
2641     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2642     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2643     int     errorCode = 0;              /* return code to caller */
2644     Volume * volptr = 0;                /* pointer to the volume */
2645     struct client *client;              /* pointer to the client data */
2646     afs_int32 rights, anyrights;                /* rights for this and any user */
2647     register struct AFSFid *tfid;       /* file id we're dealing with now */
2648     struct rx_connection *tcon;
2649     AFSFetchStatus *tstatus;
2650 #if FS_STATS_DETAILED
2651     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2652     struct timeval opStartTime,
2653                    opStopTime;              /* Start/stop times for RPC op*/
2654     struct timeval elapsedTime;             /* Transfer time */
2655
2656     /*
2657      * Set our stats pointer, remember when the RPC operation started, and
2658      * tally the operation.
2659      */
2660     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2661     FS_LOCK
2662     (opP->numOps)++;
2663     FS_UNLOCK
2664     TM_GetTimeOfDay(&opStartTime, 0);
2665 #endif /* FS_STATS_DETAILED */
2666
2667     ViceLog(1, ("SAFS_InlineBulkStatus\n"));
2668     FS_LOCK
2669     AFSCallStats.TotalCalls++;
2670     FS_UNLOCK
2671
2672     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2673     if (nfiles <= 0) {                  /* Sanity check */
2674         errorCode = EINVAL;
2675         goto Audit_and_Return;
2676     }
2677
2678     /* allocate space for return output parameters */
2679     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2680         malloc(nfiles * sizeof(struct AFSFetchStatus));
2681     if (!OutStats->AFSBulkStats_val) {
2682         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2683         assert(0);
2684     }
2685     OutStats->AFSBulkStats_len = nfiles;
2686     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2687         malloc(nfiles * sizeof(struct AFSCallBack));
2688     if (!CallBacks->AFSCBs_val) {
2689         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2690         assert(0);
2691     }
2692     CallBacks->AFSCBs_len = nfiles;
2693
2694     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon))) {
2695         goto Bad_InlineBulkStatus;
2696     }
2697
2698     tfid = Fids->AFSCBFids_val;
2699     for (i=0; i<nfiles; i++, tfid++) {
2700         /*
2701          * Get volume/vnode for the fetched file; caller's rights to it
2702          * are also returned
2703          */
2704         if ((errorCode =
2705             GetVolumePackage(tcon, tfid, &volptr, &targetptr,
2706                              DONTCHECK, &parentwhentargetnotdir, &client,
2707                              READ_LOCK, &rights, &anyrights))) {
2708             tstatus = &OutStats->AFSBulkStats_val[i];
2709             tstatus->errorCode = errorCode;
2710             parentwhentargetnotdir = (Vnode *) 0;
2711             targetptr = (Vnode *) 0;
2712             volptr = (Volume *) 0;
2713             continue;
2714         }
2715
2716         /* set volume synchronization information, but only once per call */
2717         if (i == nfiles)
2718             SetVolumeSync(Sync, volptr);
2719
2720         /* Are we allowed to fetch Fid's status? */
2721         if (targetptr->disk.type != vDirectory) {
2722             if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2723                                                    CHK_FETCHSTATUS, 0))) {
2724                 tstatus = &OutStats->AFSBulkStats_val[i];
2725                 tstatus->errorCode = errorCode;
2726                 (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, volptr);
2727                 parentwhentargetnotdir = (Vnode *) 0;
2728                 targetptr = (Vnode *) 0;
2729                 volptr = (Volume *) 0;
2730                 continue;
2731             }
2732         }
2733
2734         /* set OutStatus From the Fid  */
2735         GetStatus(targetptr, (struct AFSFetchStatus *) &OutStats->AFSBulkStats_val[i], 
2736           rights, anyrights, parentwhentargetnotdir);
2737
2738         /* If a r/w volume, also set the CallBack state */
2739         if (VolumeWriteable(volptr))
2740             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2741                               &CallBacks->AFSCBs_val[i]);
2742         else {
2743           struct AFSFid myFid;          
2744           memset(&myFid, 0, sizeof(struct AFSFid));
2745           myFid.Volume = tfid->Volume;
2746           SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2747                               &CallBacks->AFSCBs_val[i]);
2748         }
2749
2750         /* put back the file ID and volume */
2751         (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, volptr);
2752         parentwhentargetnotdir = (Vnode *) 0;
2753         targetptr = (Vnode *) 0;
2754         volptr = (Volume *) 0;
2755     }
2756
2757 Bad_InlineBulkStatus: 
2758     /* Update and store volume/vnode and parent vnodes back */
2759     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
2760     errorCode = CallPostamble(tcon, errorCode);
2761
2762 #if FS_STATS_DETAILED
2763     TM_GetTimeOfDay(&opStopTime, 0);
2764     if (errorCode == 0) {
2765         FS_LOCK
2766         (opP->numSuccesses)++;
2767         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2768         fs_stats_AddTo((opP->sumTime), elapsedTime);
2769         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2770         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2771             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2772         }
2773         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2774             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2775         }
2776         FS_UNLOCK
2777     }   
2778
2779 #endif /* FS_STATS_DETAILED */
2780
2781 Audit_and_Return:
2782     ViceLog(2, ("SAFS_InlineBulkStatus  returns %d\n", errorCode)); 
2783     osi_auditU (acall, InlineBulkFetchStatusEvent, errorCode, AUD_FIDS, Fids, AUD_END);
2784     return 0;
2785
2786 } /*SRXAFS_InlineBulkStatus*/
2787
2788
2789 afs_int32 SRXAFS_FetchStatus (struct rx_call *acall,            
2790                               struct AFSFid *Fid,               
2791                               struct AFSFetchStatus *OutStatus, 
2792                               struct AFSCallBack *CallBack,     
2793                               struct AFSVolSync *Sync)
2794 {
2795     afs_int32 code;
2796     struct rx_connection *tcon;
2797 #if FS_STATS_DETAILED
2798     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2799     struct timeval opStartTime,
2800                    opStopTime;              /* Start/stop times for RPC op*/
2801     struct timeval elapsedTime;             /* Transfer time */
2802
2803     /*
2804      * Set our stats pointer, remember when the RPC operation started, and
2805      * tally the operation.
2806      */
2807     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHSTATUS]);
2808     FS_LOCK
2809     (opP->numOps)++;
2810     FS_UNLOCK
2811     TM_GetTimeOfDay(&opStartTime, 0);
2812 #endif /* FS_STATS_DETAILED */
2813
2814     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
2815         goto Bad_FetchStatus;
2816
2817     code = SAFSS_FetchStatus (acall, Fid, OutStatus, CallBack, Sync);
2818
2819 Bad_FetchStatus:    
2820     code = CallPostamble(tcon, code);
2821
2822 #if FS_STATS_DETAILED
2823     TM_GetTimeOfDay(&opStopTime, 0);
2824     if (code == 0) {
2825         FS_LOCK
2826         (opP->numSuccesses)++;
2827         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2828         fs_stats_AddTo((opP->sumTime), elapsedTime);
2829         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2830         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2831             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2832         }
2833         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2834             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2835         }
2836         FS_UNLOCK
2837       }
2838
2839 #endif /* FS_STATS_DETAILED */
2840
2841     osi_auditU (acall, FetchStatusEvent, code, AUD_FID, Fid, AUD_END);
2842     return code;
2843
2844 } /*SRXAFS_FetchStatus*/
2845
2846 static
2847 afs_int32 common_StoreData64 (struct rx_call *acall,            
2848                               struct AFSFid *Fid,                       
2849                               struct AFSStoreStatus *InStatus,  
2850                               afs_uint32 Pos,                     
2851                               afs_uint32 Length,                  
2852                               afs_uint32 FileLength,              
2853                               struct AFSFetchStatus *OutStatus, 
2854                               struct AFSVolSync *Sync)
2855 {
2856     Vnode * targetptr = 0;              /* pointer to input fid */
2857     Vnode * parentwhentargetnotdir = 0; /* parent of Fid to get ACL */
2858     Vnode   tparentwhentargetnotdir;    /* parent vnode for GetStatus */
2859     int     errorCode = 0;              /* return code for caller */
2860     int     fileCode =  0;              /* return code from vol package */
2861     Volume * volptr = 0;                /* pointer to the volume header */
2862     struct client * client;             /* pointer to client structure */
2863     afs_int32 rights, anyrights;                /* rights for this and any user */
2864     struct client *t_client;            /* tmp ptr to client data */
2865     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
2866     struct rx_connection *tcon;
2867 #if FS_STATS_DETAILED
2868     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2869     struct fs_stats_xferData *xferP;        /* Ptr to this op's byte size struct */
2870     struct timeval opStartTime,
2871                    opStopTime;              /* Start/stop times for RPC op*/
2872     struct timeval xferStartTime,
2873                    xferStopTime;            /* Start/stop times for xfer portion*/
2874     struct timeval elapsedTime;             /* Transfer time */
2875     afs_int32 bytesToXfer;                          /* # bytes to xfer */
2876     afs_int32 bytesXferred;                         /* # bytes actually xfer */
2877     static afs_int32 tot_bytesXferred; /* shared access protected by FS_LOCK */
2878
2879     /*
2880      * Set our stats pointers, remember when the RPC operation started, and
2881      * tally the operation.
2882      */
2883     opP   = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREDATA]);
2884     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_STOREDATA]);
2885     FS_LOCK
2886     (opP->numOps)++;
2887     FS_UNLOCK
2888
2889     ViceLog(1, ("StoreData: Fid = %u.%d.%d\n",
2890             Fid->Volume, Fid->Vnode, Fid->Unique));
2891     TM_GetTimeOfDay(&opStartTime, 0);
2892 #endif /* FS_STATS_DETAILED */
2893
2894     FS_LOCK
2895     AFSCallStats.StoreData++, AFSCallStats.TotalCalls++;
2896     FS_UNLOCK
2897
2898     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
2899         goto Bad_StoreData;
2900
2901     /* Get ptr to client data for user Id for logging */
2902     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
2903     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2904     ViceLog(5, ("StoreData: Fid = %u.%d.%d, Host %s, Id %d\n",
2905             Fid->Volume, Fid->Vnode, Fid->Unique,
2906             inet_ntoa(logHostAddr), t_client->ViceId));
2907
2908     /*
2909      * Get associated volume/vnode for the stored file; caller's rights
2910      * are also returned
2911      */
2912     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2913                                      MustNOTBeDIR, &parentwhentargetnotdir,
2914                                      &client, WRITE_LOCK, &rights, &anyrights))) {
2915         goto Bad_StoreData;
2916     }
2917
2918     /* set volume synchronization information */
2919     SetVolumeSync(Sync, volptr);
2920
2921     if ((targetptr->disk.type == vSymlink)) {
2922         /* Should we return a better error code here??? */
2923         errorCode = EISDIR;
2924         goto Bad_StoreData;
2925     }
2926
2927     /* Check if we're allowed to store the data */
2928     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2929                                            CHK_STOREDATA, InStatus))) {
2930         goto Bad_StoreData;
2931     }
2932
2933     /*
2934      * Drop the read lock on the parent directory after saving the parent
2935      * vnode information we need to pass to GetStatus
2936      */
2937     if (parentwhentargetnotdir != NULL) {
2938         tparentwhentargetnotdir = *parentwhentargetnotdir;
2939         VPutVnode(&fileCode, parentwhentargetnotdir);
2940         assert(!fileCode || (fileCode == VSALVAGE));
2941         parentwhentargetnotdir = NULL;
2942     }
2943
2944
2945
2946 #if FS_STATS_DETAILED
2947     /*
2948      * Remember when the data transfer started.
2949      */
2950     TM_GetTimeOfDay(&xferStartTime, 0);
2951 #endif /* FS_STATS_DETAILED */
2952
2953     /* Do the actual storing of the data */
2954 #if FS_STATS_DETAILED
2955     errorCode = StoreData_RXStyle(volptr, targetptr, Fid, client, acall,
2956                                   Pos, Length, FileLength,
2957                                   (InStatus->Mask & AFS_FSYNC),
2958                                   &bytesToXfer, &bytesXferred);
2959 #else
2960     errorCode = StoreData_RXStyle(volptr, targetptr, Fid, client,
2961                                       acall, Pos, Length, FileLength,
2962                                       (InStatus->Mask & AFS_FSYNC));
2963     if (errorCode && (!targetptr->changed_newTime))
2964             goto Bad_StoreData;
2965 #endif /* FS_STATS_DETAILED */
2966 #if FS_STATS_DETAILED
2967     /*
2968      * At this point, the data transfer is done, for good or ill.  Remember
2969      * when the transfer ended, bump the number of successes/failures, and
2970      * integrate the transfer size and elapsed time into the stats.  If the
2971      * operation failed, we jump to the appropriate point.
2972      */
2973     TM_GetTimeOfDay(&xferStopTime, 0);
2974     FS_LOCK
2975     (xferP->numXfers)++;
2976     if (!errorCode) {
2977         (xferP->numSuccesses)++;
2978
2979         /*
2980          * Bump the xfer sum by the number of bytes actually sent, NOT the
2981          * target number.
2982          */
2983         tot_bytesXferred += bytesXferred;
2984         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2985         tot_bytesXferred &= 0x3FF;
2986         if (bytesXferred < xferP->minBytes)
2987             xferP->minBytes = bytesXferred;
2988         if (bytesXferred > xferP->maxBytes)
2989             xferP->maxBytes = bytesXferred;
2990       
2991         /*
2992          * Tally the size of the object.  Note: we tally the actual size,
2993          * NOT the number of bytes that made it out over the wire.
2994          */
2995         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2996             (xferP->count[0])++;
2997         else
2998             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2999                 (xferP->count[1])++;
3000         else
3001             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
3002                 (xferP->count[2])++;
3003         else
3004             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
3005                 (xferP->count[3])++;
3006         else
3007             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
3008                 (xferP->count[4])++;
3009         else
3010             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
3011                 (xferP->count[5])++;
3012         else
3013             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
3014                 (xferP->count[6])++;
3015         else
3016             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
3017                 (xferP->count[7])++;
3018         else
3019             (xferP->count[8])++;
3020       
3021         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
3022         fs_stats_AddTo((xferP->sumTime), elapsedTime);
3023         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
3024         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
3025             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
3026         }
3027         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
3028             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
3029         }
3030     }
3031     FS_UNLOCK
3032
3033     /*
3034      * Finally, go off to tell our caller the bad news in case the
3035      * store failed.
3036      */
3037     if (errorCode && (!targetptr->changed_newTime))
3038             goto Bad_StoreData;
3039 #endif /* FS_STATS_DETAILED */
3040
3041     /* Update the status of the target's vnode */
3042     Update_TargetVnodeStatus(targetptr, TVS_SDATA, client, InStatus, targetptr,
3043                              volptr, 0);
3044
3045     /* Get the updated File's status back to the caller */
3046     GetStatus(targetptr, OutStatus, rights, anyrights, &tparentwhentargetnotdir);
3047
3048 Bad_StoreData: 
3049     /* Update and store volume/vnode and parent vnodes back */
3050     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
3051                             volptr);
3052     ViceLog(2, ("SAFS_StoreData returns %d\n", errorCode));
3053
3054     errorCode = CallPostamble(tcon, errorCode);
3055
3056 #if FS_STATS_DETAILED
3057     TM_GetTimeOfDay(&opStopTime, 0);
3058     if (errorCode == 0) {
3059         FS_LOCK
3060         (opP->numSuccesses)++;
3061         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3062         fs_stats_AddTo((opP->sumTime), elapsedTime);
3063         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3064         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3065             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3066         }
3067         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3068             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3069         }
3070         FS_UNLOCK
3071       }
3072 #endif /* FS_STATS_DETAILED */
3073
3074     osi_auditU (acall, StoreDataEvent, errorCode, AUD_FID, Fid, AUD_END);
3075     return(errorCode);
3076
3077 } /*common_StoreData64*/
3078
3079 afs_int32 SRXAFS_StoreData (struct rx_call *acall,              
3080                             struct AFSFid *Fid,                 
3081                             struct AFSStoreStatus *InStatus,    
3082                             afs_uint32 Pos,                     
3083                             afs_uint32 Length,                  
3084                             afs_uint32 FileLength,              
3085                             struct AFSFetchStatus *OutStatus,   
3086                             struct AFSVolSync *Sync)
3087 {
3088     int code;
3089
3090     code = common_StoreData64 (acall, Fid, InStatus, Pos, Length, FileLength,
3091                                OutStatus, Sync);
3092     return code;
3093
3094 } /*SRXAFS_StoreData*/
3095
3096 afs_int32 SRXAFS_StoreData64 (struct rx_call *acall,            
3097                               struct AFSFid *Fid,               
3098                               struct AFSStoreStatus *InStatus,  
3099                               afs_uint64 Pos,                   
3100                               afs_uint64 Length,                
3101                               afs_uint64 FileLength,            
3102                               struct AFSFetchStatus *OutStatus, 
3103                               struct AFSVolSync *Sync)
3104 {
3105     int code;
3106     afs_int32 tPos;
3107     afs_int32 tLength;
3108     afs_int32 tFileLength;
3109
3110 #ifdef AFS_64BIT_ENV
3111     if (FileLength > 0x7fffffff)
3112         return E2BIG;
3113     tPos = Pos;
3114     tLength = Length;
3115     tFileLength = FileLength;
3116 #else /* AFS_64BIT_ENV */
3117     if (FileLength.high)
3118         return E2BIG;
3119     tPos = Pos.low;
3120     tLength = Length.low;
3121     tFileLength = FileLength.low;
3122 #endif /* AFS_64BIT_ENV */
3123
3124     code = common_StoreData64 (acall, Fid, InStatus, tPos, tLength, tFileLength,
3125                                OutStatus, Sync);
3126     return code;
3127 }
3128
3129 afs_int32 SRXAFS_StoreACL (struct rx_call *acall,               
3130                            struct AFSFid *Fid,                  
3131                            struct AFSOpaque *AccessList,        
3132                            struct AFSFetchStatus *OutStatus,
3133                            struct AFSVolSync *Sync)
3134 {
3135     Vnode * targetptr = 0;              /* pointer to input fid */
3136     Vnode * parentwhentargetnotdir = 0; /* parent of Fid to get ACL */
3137     int     errorCode = 0;              /* return code for caller */
3138     struct AFSStoreStatus InStatus;     /* Input status for fid */
3139     Volume * volptr = 0;                /* pointer to the volume header */
3140     struct client * client;             /* pointer to client structure */
3141     afs_int32 rights, anyrights;                /* rights for this and any user */
3142     struct rx_connection *tcon;
3143     struct client *t_client;            /* tmp ptr to client data */
3144     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
3145 #if FS_STATS_DETAILED
3146     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
3147     struct timeval opStartTime,
3148                    opStopTime;              /* Start/stop times for RPC op*/
3149     struct timeval elapsedTime;             /* Transfer time */
3150
3151     /*
3152      * Set our stats pointer, remember when the RPC operation started, and
3153      * tally the operation.
3154      */
3155     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREACL]);
3156     FS_LOCK
3157     (opP->numOps)++;
3158     FS_UNLOCK
3159     TM_GetTimeOfDay(&opStartTime, 0);
3160 #endif /* FS_STATS_DETAILED */
3161     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
3162         goto Bad_StoreACL;
3163
3164     /* Get ptr to client data for user Id for logging */
3165     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3166     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3167     ViceLog(1, ("SAFS_StoreACL, Fid = %u.%d.%d, ACL=%s, Host %s, Id %d\n",
3168             Fid->Volume, Fid->Vnode, Fid->Unique, AccessList->AFSOpaque_val,
3169             inet_ntoa(logHostAddr), t_client->ViceId));
3170     FS_LOCK
3171     AFSCallStats.StoreACL++, AFSCallStats.TotalCalls++;
3172     FS_UNLOCK
3173
3174     InStatus.Mask = 0;      /* not storing any status */
3175
3176     /*
3177      * Get associated volume/vnode for the target dir; caller's rights
3178      * are also returned.
3179      */
3180     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
3181                                      MustBeDIR, &parentwhentargetnotdir,
3182                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3183         goto Bad_StoreACL;
3184     }
3185
3186     /* set volume synchronization information */
3187     SetVolumeSync(Sync, volptr);
3188
3189     /* Check if we have permission to change the dir's ACL */
3190     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
3191                                            CHK_STOREACL, &InStatus))) {
3192         goto Bad_StoreACL;
3193     }
3194
3195     /* Build and store the new Access List for the dir */
3196     if ((errorCode = RXStore_AccessList(targetptr, AccessList))) {
3197         goto Bad_StoreACL;
3198     }
3199     
3200     targetptr->changed_newTime = 1; /* status change of directory */
3201
3202     /* convert the write lock to a read lock before breaking callbacks */
3203     VVnodeWriteToRead(&errorCode, targetptr);
3204     assert(!errorCode || errorCode == VSALVAGE);
3205
3206     /* break call backs on the directory  */
3207     BreakCallBack(client->host, Fid, 0);
3208
3209     /* Get the updated dir's status back to the caller */
3210     GetStatus(targetptr, OutStatus, rights, anyrights, 0);
3211
3212 Bad_StoreACL: 
3213     /* Update and store volume/vnode and parent vnodes back */
3214     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
3215     ViceLog(2, ("SAFS_StoreACL returns %d\n", errorCode)); 
3216     errorCode = CallPostamble(tcon, errorCode);
3217
3218 #if FS_STATS_DETAILED
3219     TM_GetTimeOfDay(&opStopTime, 0);
3220     if (errorCode == 0) {
3221       FS_LOCK
3222       (opP->numSuccesses)++;
3223       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3224       fs_stats_AddTo((opP->sumTime), elapsedTime);
3225       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3226       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3227         fs_stats_TimeAssign((opP->minTime), elapsedTime);
3228       }
3229       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3230         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3231       }
3232       FS_UNLOCK
3233     }
3234 #endif /* FS_STATS_DETAILED */
3235
3236     osi_auditU (acall, StoreACLEvent, errorCode, AUD_FID, Fid, AUD_END);
3237     return errorCode;
3238
3239 } /*SRXAFS_StoreACL*/
3240
3241
3242 /*
3243  * Note: This routine is called exclusively from SRXAFS_StoreStatus(), and
3244  * should be merged when possible.
3245  */
3246 static afs_int32
3247 SAFSS_StoreStatus (struct rx_call *acall,               
3248                    struct AFSFid *Fid,                  
3249                    struct AFSStoreStatus *InStatus,     
3250                    struct AFSFetchStatus *OutStatus,    
3251                    struct AFSVolSync *Sync)
3252
3253 {
3254     Vnode * targetptr = 0;              /* pointer to input fid */
3255     Vnode * parentwhentargetnotdir = 0; /* parent of Fid to get ACL */
3256     int     errorCode = 0;              /* return code for caller */
3257     Volume * volptr = 0;                /* pointer to the volume header */
3258     struct client * client;             /* pointer to client structure */
3259     afs_int32 rights, anyrights;                /* rights for this and any user */
3260     struct client *t_client;            /* tmp ptr to client data */
3261     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
3262     struct rx_connection *tcon = rx_ConnectionOf(acall);
3263
3264     /* Get ptr to client data for user Id for logging */
3265     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3266     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3267     ViceLog(1, ("SAFS_StoreStatus,  Fid = %u.%d.%d, Host %s, Id %d\n",
3268             Fid->Volume, Fid->Vnode,    Fid->Unique,
3269             inet_ntoa(logHostAddr), t_client->ViceId));
3270     FS_LOCK
3271     AFSCallStats.StoreStatus++, AFSCallStats.TotalCalls++;
3272     FS_UNLOCK
3273     /*
3274      * Get volume/vnode for the target file; caller's rights to it are
3275      * also returned
3276      */
3277     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
3278                                      DONTCHECK, &parentwhentargetnotdir,
3279                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3280         goto Bad_StoreStatus;
3281     }
3282
3283     /* set volume synchronization information */
3284     SetVolumeSync(Sync, volptr);
3285
3286     /* Check if the caller has proper permissions to store status to Fid */
3287     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
3288                                            CHK_STORESTATUS, InStatus))) {
3289         goto Bad_StoreStatus;
3290     }
3291     /*
3292      * Check for a symbolic link; we can't chmod these (otherwise could
3293      * change a symlink to a mt pt or vice versa)
3294      */
3295     if (targetptr->disk.type == vSymlink && (InStatus->Mask & AFS_SETMODE)) {
3296         errorCode = EINVAL;
3297         goto Bad_StoreStatus;
3298     }
3299
3300     /* Update the status of the target's vnode */
3301     Update_TargetVnodeStatus(targetptr, TVS_SSTATUS, client, InStatus,
3302                              (parentwhentargetnotdir ?
3303                               parentwhentargetnotdir : targetptr), volptr, 0);
3304
3305     /* convert the write lock to a read lock before breaking callbacks */
3306     VVnodeWriteToRead(&errorCode, targetptr);
3307     assert(!errorCode || errorCode == VSALVAGE);
3308
3309     /* Break call backs on Fid */
3310     BreakCallBack(client->host, Fid, 0);
3311
3312     /* Return the updated status back to caller */
3313     GetStatus(targetptr, OutStatus, rights, anyrights, parentwhentargetnotdir);
3314
3315 Bad_StoreStatus: 
3316     /* Update and store volume/vnode and parent vnodes back */
3317     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
3318     ViceLog(2, ("SAFS_StoreStatus returns %d\n", errorCode));
3319     return errorCode;
3320
3321 } /*SAFSS_StoreStatus*/
3322
3323
3324 afs_int32 SRXAFS_StoreStatus (struct rx_call *acall,            
3325                               struct AFSFid *Fid,               
3326                               struct AFSStoreStatus *InStatus,  
3327                               struct AFSFetchStatus *OutStatus, 
3328                               struct AFSVolSync *Sync)
3329 {
3330     afs_int32 code;
3331     struct rx_connection *tcon;
3332 #if FS_STATS_DETAILED
3333     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
3334     struct timeval opStartTime,
3335                    opStopTime;              /* Start/stop times for RPC op*/
3336     struct timeval elapsedTime;             /* Transfer time */
3337
3338     /*
3339      * Set our stats pointer, remember when the RPC operation started, and
3340      * tally the operation.
3341      */
3342     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STORESTATUS]);
3343     FS_LOCK
3344     (opP->numOps)++;
3345     FS_UNLOCK
3346     TM_GetTimeOfDay(&opStartTime, 0);
3347 #endif /* FS_STATS_DETAILED */
3348
3349     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
3350         goto Bad_StoreStatus;
3351
3352     code = SAFSS_StoreStatus (acall, Fid, InStatus, OutStatus, Sync);
3353
3354 Bad_StoreStatus:
3355     code = CallPostamble(tcon, code);
3356
3357 #if FS_STATS_DETAILED
3358     TM_GetTimeOfDay(&opStopTime, 0);
3359     if (code == 0) {
3360       FS_LOCK
3361       (opP->numSuccesses)++;
3362       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3363       fs_stats_AddTo((opP->sumTime), elapsedTime);
3364       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3365       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3366         fs_stats_TimeAssign((opP->minTime), elapsedTime);
3367       }
3368       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3369         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3370       }
3371       FS_UNLOCK
3372     }
3373
3374 #endif /* FS_STATS_DETAILED */
3375
3376     osi_auditU (acall, StoreStatusEvent, code, AUD_FID, Fid, AUD_END);
3377     return code;
3378
3379 } /*SRXAFS_StoreStatus*/
3380
3381
3382 /*
3383  * This routine is called exclusively by SRXAFS_RemoveFile(), and should be
3384  * merged in when possible.
3385  */
3386 static afs_int32
3387 SAFSS_RemoveFile (struct rx_call *acall,               
3388                   struct AFSFid *DirFid,               
3389                   char *Name,                          
3390                   struct AFSFetchStatus *OutDirStatus, 
3391                   struct AFSVolSync *Sync)
3392 {
3393     Vnode * parentptr = 0;              /* vnode of input Directory */
3394     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
3395     Vnode * targetptr = 0;              /* file to be deleted */
3396     Volume * volptr = 0;                /* pointer to the volume header */
3397     AFSFid fileFid;                     /* area for Fid from the directory */
3398     int     errorCode = 0;              /* error code */
3399     DirHandle dir;                      /* Handle for dir package I/O */
3400     struct client * client;             /* pointer to client structure */
3401     afs_int32 rights, anyrights;                /* rights for this and any user */
3402     struct client *t_client;            /* tmp ptr to client data */
3403     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
3404     struct rx_connection *tcon = rx_ConnectionOf(acall);
3405
3406     FidZero(&dir);
3407     /* Get ptr to client data for user Id for logging */
3408     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3409     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3410     ViceLog(1, ("SAFS_RemoveFile %s,  Did = %u.%d.%d, Host %s, Id %d\n",
3411             Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3412             inet_ntoa(logHostAddr), t_client->ViceId));
3413     FS_LOCK
3414     AFSCallStats.RemoveFile++, AFSCallStats.TotalCalls++;
3415     FS_UNLOCK
3416     /*
3417      * Get volume/vnode for the parent dir; caller's access rights are
3418      * also returned
3419      */
3420     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
3421                                      MustBeDIR, &parentwhentargetnotdir,
3422                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3423         goto Bad_RemoveFile;
3424     }
3425     /* set volume synchronization information */
3426     SetVolumeSync(Sync, volptr);
3427
3428     /* Does the caller has delete (& write) access to the parent directory? */
3429     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
3430         goto Bad_RemoveFile;
3431     }
3432
3433     /* Actually delete the desired file */
3434     if ((errorCode = DeleteTarget(parentptr, volptr, &targetptr, &dir,
3435                                  &fileFid, Name, MustNOTBeDIR))) {
3436         goto Bad_RemoveFile;
3437     }
3438
3439     /* Update the vnode status of the parent dir */
3440 #if FS_STATS_DETAILED
3441     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3442                              parentptr->disk.linkCount, client->InSameNetwork);
3443 #else
3444     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3445                              parentptr->disk.linkCount);
3446 #endif /* FS_STATS_DETAILED */
3447
3448     /* Return the updated parent dir's status back to caller */
3449     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3450
3451     /* Handle internal callback state for the parent and the deleted file */
3452     if (targetptr->disk.linkCount == 0) {
3453         /* no references left, discard entry */
3454         DeleteFileCallBacks(&fileFid);
3455         /* convert the parent lock to a read lock before breaking callbacks */
3456         VVnodeWriteToRead(&errorCode, parentptr);
3457         assert(!errorCode || errorCode == VSALVAGE);
3458     } else {
3459         /* convert the parent lock to a read lock before breaking callbacks */
3460         VVnodeWriteToRead(&errorCode, parentptr);
3461         assert(!errorCode || errorCode == VSALVAGE);
3462         /* convert the target lock to a read lock before breaking callbacks */
3463         VVnodeWriteToRead(&errorCode, targetptr);
3464         assert(!errorCode || errorCode == VSALVAGE);
3465         /* tell all the file has changed */
3466         BreakCallBack(client->host, &fileFid, 1);
3467     }
3468
3469     /* break call back on the directory */
3470     BreakCallBack(client->host, DirFid, 0);
3471
3472 Bad_RemoveFile: 
3473     /* Update and store volume/vnode and parent vnodes back */
3474     PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr, volptr);
3475     FidZap(&dir);
3476     ViceLog(2, ("SAFS_RemoveFile returns %d\n", errorCode)); 
3477     return errorCode;
3478
3479 } /*SAFSS_RemoveFile*/
3480
3481
3482 afs_int32 SRXAFS_RemoveFile (struct rx_call *acall,
3483                              struct AFSFid *DirFid,
3484                              char *Name,
3485                              struct AFSFetchStatus *OutDirStatus,
3486                              struct AFSVolSync *Sync)
3487 {
3488     afs_int32 code;
3489     struct rx_connection *tcon;
3490 #if FS_STATS_DETAILED
3491     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
3492     struct timeval opStartTime,
3493                    opStopTime;              /* Start/stop times for RPC op*/
3494     struct timeval elapsedTime;             /* Transfer time */
3495
3496     /*
3497      * Set our stats pointer, remember when the RPC operation started, and
3498      * tally the operation.
3499      */
3500     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEFILE]);
3501     FS_LOCK
3502     (opP->numOps)++;
3503     FS_UNLOCK
3504     TM_GetTimeOfDay(&opStartTime, 0);
3505 #endif /* FS_STATS_DETAILED */
3506
3507     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
3508         goto Bad_RemoveFile;
3509
3510     code = SAFSS_RemoveFile (acall, DirFid, Name, OutDirStatus, Sync);
3511
3512 Bad_RemoveFile:    
3513     code = CallPostamble(tcon, code);
3514
3515 #if FS_STATS_DETAILED
3516     TM_GetTimeOfDay(&opStopTime, 0);
3517     if (code == 0) {
3518       FS_LOCK
3519       (opP->numSuccesses)++;
3520       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3521       fs_stats_AddTo((opP->sumTime), elapsedTime);
3522       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3523       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3524         fs_stats_TimeAssign((opP->minTime), elapsedTime);
3525       }
3526       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3527         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3528       }
3529       FS_UNLOCK
3530     }
3531
3532 #endif /* FS_STATS_DETAILED */
3533
3534     osi_auditU (acall, RemoveFileEvent, code, AUD_FID, DirFid, AUD_STR, Name, AUD_END);
3535     return code;
3536
3537 } /*SRXAFS_RemoveFile*/
3538
3539
3540 /*
3541  * This routine is called exclusively from SRXAFS_CreateFile(), and should
3542  * be merged in when possible.
3543  */
3544 static afs_int32
3545 SAFSS_CreateFile (struct rx_call *acall,
3546                   struct AFSFid *DirFid,
3547                   char *Name,
3548                   struct AFSStoreStatus *InStatus,
3549                   struct AFSFid *OutFid,
3550                   struct AFSFetchStatus *OutFidStatus,
3551                   struct AFSFetchStatus *OutDirStatus,
3552                   struct AFSCallBack *CallBack,
3553                   struct AFSVolSync *Sync)
3554 {
3555     Vnode * parentptr = 0;              /* vnode of input Directory */
3556     Vnode * targetptr = 0;              /* vnode of the new file */
3557     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
3558     Volume * volptr = 0;                /* pointer to the volume header */
3559     int     errorCode = 0;              /* error code */
3560     DirHandle dir;                      /* Handle for dir package I/O */
3561     struct client * client;             /* pointer to client structure */
3562     afs_int32 rights, anyrights;                /* rights for this and any user */
3563     struct client *t_client;            /* tmp ptr to client data */
3564     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
3565     struct rx_connection *tcon = rx_ConnectionOf(acall);
3566
3567     FidZero(&dir);
3568
3569     /* Get ptr to client data for user Id for logging */
3570     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3571     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3572     ViceLog(1, ("SAFS_CreateFile %s,  Did = %u.%d.%d, Host %s, Id %d\n",
3573             Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3574             inet_ntoa(logHostAddr), t_client->ViceId));
3575     FS_LOCK
3576     AFSCallStats.CreateFile++, AFSCallStats.TotalCalls++;
3577     FS_UNLOCK
3578     if (!FileNameOK(Name)) {
3579       errorCode = EINVAL;
3580       goto Bad_CreateFile;
3581     }
3582
3583     /*
3584      * Get associated volume/vnode for the parent dir; caller long are
3585      * also returned
3586      */
3587     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
3588                                      MustBeDIR, &parentwhentargetnotdir,
3589                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3590         goto Bad_CreateFile;
3591     }
3592
3593     /* set volume synchronization information */
3594     SetVolumeSync(Sync, volptr);
3595
3596     /* Can we write (and insert) onto the parent directory? */
3597     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
3598         goto Bad_CreateFile;
3599     }
3600     /* get a new vnode for the file to be created and set it up */
3601     if ((errorCode = Alloc_NewVnode(parentptr, &dir, volptr, &targetptr,
3602                                    Name, OutFid, vFile, nBlocks(0)))) {
3603         goto Bad_CreateFile;
3604     }
3605
3606     /* update the status of the parent vnode */
3607 #if FS_STATS_DETAILED
3608     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3609                              parentptr->disk.linkCount, client->InSameNetwork);
3610 #else
3611     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3612                              parentptr->disk.linkCount);
3613 #endif /* FS_STATS_DETAILED */
3614
3615     /* update the status of the new file's vnode */
3616     Update_TargetVnodeStatus(targetptr, TVS_CFILE, client, InStatus,
3617                              parentptr, volptr, 0);
3618
3619     /* set up the return status for the parent dir and the newly created file */
3620     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
3621     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3622
3623     /* convert the write lock to a read lock before breaking callbacks */
3624     VVnodeWriteToRead(&errorCode, parentptr);
3625     assert(!errorCode || errorCode == VSALVAGE);
3626     
3627     /* break call back on parent dir */
3628     BreakCallBack(client->host, DirFid, 0);
3629
3630     /* Return a callback promise for the newly created file to the caller */
3631     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
3632
3633 Bad_CreateFile:
3634     /* Update and store volume/vnode and parent vnodes back */
3635     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
3636                             volptr);
3637     FidZap(&dir);
3638     ViceLog(2, ("SAFS_CreateFile returns %d\n", errorCode)); 
3639     return errorCode;
3640
3641 } /*SAFSS_CreateFile*/
3642
3643
3644 afs_int32 SRXAFS_CreateFile (struct rx_call *acall,
3645                              struct AFSFid *DirFid,
3646                              char *Name,
3647                              struct AFSStoreStatus *InStatus,
3648                              struct AFSFid *OutFid,
3649                              struct AFSFetchStatus *OutFidStatus,
3650                              struct AFSFetchStatus *OutDirStatus, 
3651                              struct AFSCallBack *CallBack,       
3652                              struct AFSVolSync *Sync)
3653 {
3654     afs_int32 code;
3655     struct rx_connection *tcon;
3656 #if FS_STATS_DETAILED
3657     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
3658     struct timeval opStartTime,
3659                    opStopTime;              /* Start/stop times for RPC op*/
3660     struct timeval elapsedTime;             /* Transfer time */
3661
3662     /*
3663      * Set our stats pointer, remember when the RPC operation started, and
3664      * tally the operation.
3665      */
3666     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CREATEFILE]);
3667     FS_LOCK
3668     (opP->numOps)++;
3669     FS_UNLOCK
3670     TM_GetTimeOfDay(&opStartTime, 0);
3671 #endif /* FS_STATS_DETAILED */
3672
3673     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
3674         goto Bad_CreateFile;
3675
3676     code = SAFSS_CreateFile (acall, DirFid, Name, InStatus, OutFid,
3677                             OutFidStatus, OutDirStatus, CallBack, Sync);
3678
3679 Bad_CreateFile:    
3680     code = CallPostamble(tcon, code);
3681
3682 #if FS_STATS_DETAILED
3683     TM_GetTimeOfDay(&opStopTime, 0);
3684     if (code == 0) {
3685       FS_LOCK
3686       (opP->numSuccesses)++;
3687       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3688       fs_stats_AddTo((opP->sumTime), elapsedTime);
3689       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3690       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3691         fs_stats_TimeAssign((opP->minTime), elapsedTime);
3692       }
3693       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3694         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3695       }
3696       FS_UNLOCK
3697     }
3698 #endif /* FS_STATS_DETAILED */
3699
3700     osi_auditU (acall, CreateFileEvent, code, AUD_FID, DirFid, AUD_STR, Name, AUD_END);
3701     return code;
3702
3703 } /*SRXAFS_CreateFile*/
3704
3705
3706 /*
3707  * This routine is called exclusively from SRXAFS_Rename(), and should be
3708  * merged in when possible.
3709  */
3710 static afs_int32
3711 SAFSS_Rename (struct rx_call *acall,
3712               struct AFSFid *OldDirFid,
3713               char *OldName,
3714               struct AFSFid *NewDirFid,
3715               char *NewName,
3716               struct AFSFetchStatus *OutOldDirStatus,
3717               struct AFSFetchStatus *OutNewDirStatus,
3718               struct AFSVolSync *Sync)
3719 {
3720     Vnode * oldvptr = 0;        /* vnode of the old Directory */
3721     Vnode * newvptr = 0;        /* vnode of the new Directory */
3722     Vnode * fileptr = 0;        /* vnode of the file to move */
3723     Vnode * newfileptr = 0;     /* vnode of the file to delete */
3724     Vnode * testvptr = 0;       /* used in directory tree walk */
3725     Vnode * parent = 0;         /* parent for use in SetAccessList */
3726     int     errorCode = 0;      /* error code */
3727     int     fileCode = 0;       /* used when writing Vnodes */
3728     VnodeId testnode;           /* used in directory tree walk */
3729     AFSFid fileFid;             /* Fid of file to move */
3730     AFSFid newFileFid;          /* Fid of new file */
3731     DirHandle olddir;           /* Handle for dir package I/O */
3732     DirHandle newdir;           /* Handle for dir package I/O */
3733     DirHandle filedir;          /* Handle for dir package I/O */
3734     DirHandle newfiledir;       /* Handle for dir package I/O */
3735     Volume * volptr = 0;        /* pointer to the volume header */
3736     struct client * client;     /* pointer to client structure */
3737     afs_int32 rights, anyrights;        /* rights for this and any user */
3738     afs_int32 newrights;                /* rights for this user */
3739     afs_int32 newanyrights;             /* rights for any user */
3740     int doDelete;               /* deleted the rename target (ref count now 0) */
3741     int code;
3742     struct client *t_client;            /* tmp ptr to client data */
3743     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
3744     struct rx_connection *tcon = rx_ConnectionOf(acall);
3745
3746     FidZero(&olddir);
3747     FidZero(&newdir);
3748     FidZero(&filedir);
3749     FidZero(&newfiledir);
3750
3751     /* Get ptr to client data for user Id for logging */
3752     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3753     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3754     ViceLog(1, ("SAFS_Rename %s to %s,  Fid = %u.%d.%d to %u.%d.%d, Host %s, Id %d\n",
3755             OldName, NewName, OldDirFid->Volume, OldDirFid->Vnode,
3756             OldDirFid->Unique, NewDirFid->Volume, NewDirFid->Vnode,
3757             NewDirFid->Unique,
3758             inet_ntoa(logHostAddr), t_client->ViceId));
3759     FS_LOCK
3760     AFSCallStats.Rename++, AFSCallStats.TotalCalls++;
3761     FS_UNLOCK
3762     if (!FileNameOK(NewName)) {
3763         errorCode = EINVAL;
3764         goto Bad_Rename;
3765     }
3766     if (OldDirFid->Volume != NewDirFid->Volume) {
3767         DFlush();
3768         errorCode = EXDEV;
3769         goto Bad_Rename;
3770     }
3771     if ( (strcmp(OldName, ".") == 0) || (strcmp(OldName, "..") == 0) ||
3772          (strcmp(NewName, ".") == 0) || (strcmp(NewName, "..") == 0) || 
3773          (strlen(NewName) == 0) || (strlen(OldName) == 0)  ) {
3774         DFlush();
3775         errorCode = EINVAL;
3776         goto Bad_Rename;
3777     }
3778
3779     if (OldDirFid->Vnode <= NewDirFid->Vnode) {
3780         if  (errorCode = GetVolumePackage(tcon, OldDirFid, &volptr,
3781                                           &oldvptr, MustBeDIR, &parent,
3782                                           &client, WRITE_LOCK, &rights,
3783                                           &anyrights)) {
3784             DFlush();
3785             goto Bad_Rename;
3786         }
3787         if (OldDirFid->Vnode == NewDirFid->Vnode) {
3788             newvptr = oldvptr;
3789             newrights = rights, newanyrights = anyrights;
3790         }
3791         else
3792             if ((errorCode = GetVolumePackage(tcon, NewDirFid, &volptr,
3793                                              &newvptr, MustBeDIR, &parent,
3794                                              &client, WRITE_LOCK, &newrights,
3795                                              &newanyrights))) {
3796                 DFlush();
3797                 goto Bad_Rename;
3798             }
3799     }
3800     else {
3801         if ((errorCode = GetVolumePackage(tcon, NewDirFid, &volptr,
3802                                          &newvptr, MustBeDIR, &parent,
3803                                          &client, WRITE_LOCK, &newrights,
3804                                          &newanyrights))) {
3805             DFlush();
3806             goto Bad_Rename;
3807         }
3808         if ((errorCode = GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr,
3809                                          MustBeDIR, &parent, &client, WRITE_LOCK,
3810                                          &rights, &anyrights))) {
3811             DFlush();
3812             goto Bad_Rename;
3813         }
3814     }
3815
3816     /* set volume synchronization information */
3817     SetVolumeSync(Sync, volptr);
3818
3819     if ((errorCode = CheckWriteMode(oldvptr, rights, PRSFS_DELETE))) {
3820         goto Bad_Rename;
3821     }
3822     if ((errorCode = CheckWriteMode(newvptr, newrights, PRSFS_INSERT))) {
3823         goto Bad_Rename;
3824     }
3825
3826     /* The CopyOnWrite might return ENOSPC ( disk full). Even if the second
3827     *  call to CopyOnWrite returns error, it is not necessary to revert back
3828     *  the effects of the first call because the contents of the volume is 
3829     *  not modified, it is only replicated.
3830     */
3831     if (oldvptr->disk.cloned)
3832     {
3833         ViceLog(25, ("Rename : calling CopyOnWrite on  old dir\n"));
3834          if ( ( errorCode = CopyOnWrite(oldvptr, volptr) ) )
3835                 goto Bad_Rename;
3836     }
3837     SetDirHandle(&olddir, oldvptr);
3838     if (newvptr->disk.cloned)
3839     {
3840         ViceLog(25, ("Rename : calling CopyOnWrite on  new dir\n"));
3841         if ( ( errorCode = CopyOnWrite(newvptr, volptr) ) )
3842                 goto Bad_Rename;        
3843     }
3844
3845     SetDirHandle(&newdir, newvptr);
3846
3847     /* Lookup the file to delete its vnode */
3848     if (Lookup(&olddir, OldName, &fileFid)) {
3849         errorCode = ENOENT;
3850         goto Bad_Rename;
3851     }
3852     if (fileFid.Vnode == oldvptr->vnodeNumber ||
3853         fileFid.Vnode == newvptr->vnodeNumber) {
3854         errorCode = FSERR_ELOOP;
3855         goto Bad_Rename;
3856     }
3857     fileFid.Volume = V_id(volptr);
3858     fileptr = VGetVnode(&errorCode, volptr, fileFid.Vnode, WRITE_LOCK);
3859     if (errorCode != 0) {
3860         ViceLog (0, ("SAFSS_Rename(): Error in VGetVnode() for old file %s, code %d\n", OldName, errorCode));
3861         VTakeOffline (volptr);
3862         goto Bad_Rename;
3863     }
3864     if (fileptr->disk.uniquifier != fileFid.Unique) {
3865         ViceLog (0, ("SAFSS_Rename(): Old file %s uniquifier mismatch\n", OldName));
3866         VTakeOffline (volptr);
3867         errorCode = EIO;
3868         goto Bad_Rename;
3869     }
3870
3871     if (fileptr->disk.type != vDirectory &&
3872         oldvptr != newvptr &&
3873         fileptr->disk.linkCount != 1) {
3874         /*
3875          * Hard links exist to this file - cannot move one of the links to
3876          * a new directory because of AFS restrictions (this is the same
3877          * reason that links cannot be made across directories, i.e.
3878          * access lists)
3879          */
3880         errorCode = EXDEV;
3881         goto Bad_Rename;
3882     }
3883
3884     /* Lookup the new file  */
3885     if (!(Lookup(&newdir, NewName, &newFileFid))) {
3886         if (readonlyServer) {
3887             errorCode = VREADONLY;
3888             goto Bad_Rename;
3889         }
3890         if (!(newrights & PRSFS_DELETE)) {
3891             errorCode = EACCES;
3892             goto Bad_Rename;
3893         }
3894         if (newFileFid.Vnode == oldvptr->vnodeNumber ||
3895                 newFileFid.Vnode == newvptr->vnodeNumber ||
3896                 newFileFid.Vnode == fileFid.Vnode) {
3897             errorCode = EINVAL;
3898             goto Bad_Rename;
3899         }
3900         newFileFid.Volume = V_id(volptr);
3901         newfileptr = VGetVnode(&errorCode, volptr, newFileFid.Vnode, WRITE_LOCK);
3902         if (errorCode != 0) {
3903             ViceLog (0, ("SAFSS_Rename(): Error in VGetVnode() for new file %s, code %d\n", NewName, errorCode));
3904             VTakeOffline (volptr);
3905             goto Bad_Rename;
3906         }
3907         if (fileptr->disk.uniquifier != fileFid.Unique) {
3908             ViceLog (0, ("SAFSS_Rename(): New file %s uniquifier mismatch\n", NewName));
3909             VTakeOffline (volptr);
3910             errorCode = EIO;
3911             goto Bad_Rename;
3912         }
3913         SetDirHandle(&newfiledir, newfileptr);
3914         /* Now check that we're moving directories over directories properly, etc.
3915          * return proper POSIX error codes:
3916          * if fileptr is a file and new is a dir: EISDIR.
3917          * if fileptr is a dir and new is a file: ENOTDIR.
3918          * Also, dir to be removed must be empty, of course.
3919          */
3920         if (newfileptr->disk.type == vDirectory) {
3921             if (fileptr->disk.type != vDirectory) {
3922                 errorCode = EISDIR;
3923                 goto Bad_Rename;
3924             }
3925             if ((IsEmpty(&newfiledir))) {
3926                 errorCode = EEXIST;
3927                 goto Bad_Rename;
3928             }
3929         }
3930         else {
3931             if (fileptr->disk.type == vDirectory) {
3932                 errorCode = ENOTDIR;
3933                 goto Bad_Rename;
3934             }
3935         }
3936     }
3937
3938     /*
3939      * ok - now we check that the old name is not above new name in the
3940      * directory structure.  This is to prevent removing a subtree alltogether
3941      */
3942     if ((oldvptr != newvptr) && (fileptr->disk.type == vDirectory)) {
3943         for (testnode = newvptr->disk.parent; testnode != 0;) {
3944             if (testnode == oldvptr->vnodeNumber) {
3945                 testnode = oldvptr->disk.parent;
3946                 continue;
3947             }
3948             if ((testnode == fileptr->vnodeNumber) ||
3949                 (testnode == newvptr->vnodeNumber)) {
3950                 errorCode = FSERR_ELOOP;
3951                 goto Bad_Rename;
3952             }
3953             if ((newfileptr) && (testnode == newfileptr->vnodeNumber)) {
3954                 errorCode = FSERR_ELOOP;
3955                 goto Bad_Rename;
3956             }
3957             testvptr = VGetVnode(&errorCode, volptr, testnode, READ_LOCK);
3958             assert(errorCode == 0);
3959             testnode = testvptr->disk.parent;
3960             VPutVnode(&errorCode, testvptr);
3961             assert(errorCode == 0);
3962         }
3963     }
3964     /* Do the CopyonWrite first before modifying anything else. Copying is
3965      *  required because we may have to change entries for .. 
3966      */
3967     if ((fileptr->disk.type == vDirectory ) && (fileptr->disk.cloned) )
3968     {
3969         ViceLog(25, ("Rename : calling CopyOnWrite on  target dir\n"));
3970         if ( ( errorCode = CopyOnWrite(fileptr, volptr) ) )
3971                 goto Bad_Rename;
3972     }
3973
3974     /* If the new name exists already, delete it and the file it points to */
3975     doDelete = 0;
3976     if (newfileptr) {
3977         /* Delete NewName from its directory */
3978         code = Delete(&newdir, NewName);
3979         assert(code == 0);
3980
3981         /* Drop the link count */
3982         newfileptr->disk.linkCount--;
3983         if (newfileptr->disk.linkCount == 0) {      /* Link count 0 - delete */
3984             afs_fsize_t newSize;
3985             VN_GET_LEN(newSize, newfileptr);
3986             VAdjustDiskUsage(&errorCode, volptr, -nBlocks(newSize), 0);
3987             if (VN_GET_INO(newfileptr)) {
3988                 IH_REALLYCLOSE(newfileptr->handle);
3989                 errorCode = IH_DEC(V_linkHandle(volptr),
3990                                  VN_GET_INO(newfileptr),
3991                                  V_parentId(volptr));
3992                 IH_RELEASE(newfileptr->handle);
3993                 if (errorCode == -1) {
3994                     ViceLog(0, ("Del: inode=%s, name=%s, errno=%d\n",
3995                                 PrintInode(NULL, VN_GET_INO(newfileptr)),
3996                                 NewName, errno));
3997                     if ((errno != ENOENT) && (errno != EIO) && (errno != ENXIO))
3998                         ViceLog(0, ("Do we need to fsck?"));
3999                 } 
4000             }
4001             VN_SET_INO(newfileptr, (Inode)0);
4002             newfileptr->delete = 1;         /* Mark NewName vnode to delete */
4003             doDelete = 1;
4004         } else {
4005             /* Link count did not drop to zero.
4006              * Mark NewName vnode as changed - updates stime.
4007              */
4008             newfileptr->changed_newTime = 1;
4009         }
4010     }
4011     
4012     /*
4013      * If the create below fails, and the delete above worked, we have
4014      * removed the new name and not replaced it.  This is not very likely,
4015      * but possible.  We could try to put the old file back, but it is
4016      * highly unlikely that it would work since it would involve issuing
4017      * another create.
4018      */
4019     if ((errorCode = Create(&newdir,(char *) NewName, &fileFid)))
4020         goto Bad_Rename;
4021
4022     /* Delete the old name */
4023     assert(Delete(&olddir,(char *) OldName) == 0);
4024
4025     /* if the directory length changes, reflect it in the statistics */
4026 #if FS_STATS_DETAILED
4027     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4028                              oldvptr->disk.linkCount, client->InSameNetwork);
4029     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4030                              newvptr->disk.linkCount, client->InSameNetwork);
4031 #else
4032     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4033                              oldvptr->disk.linkCount);
4034     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4035                              newvptr->disk.linkCount);
4036 #endif /* FS_STATS_DETAILED */
4037
4038     if (oldvptr == newvptr)
4039         oldvptr->disk.dataVersion--;    /* Since it was bumped by 2! */
4040
4041     fileptr->disk.parent = newvptr->vnodeNumber;
4042     fileptr->changed_newTime = 1;       /* status change of moved file */
4043
4044     /* if we are dealing with a rename of a directory */
4045     if (fileptr->disk.type == vDirectory) {
4046         assert(!fileptr->disk.cloned);          
4047         SetDirHandle(&filedir, fileptr);
4048         /* fix .. to point to the correct place */
4049         Delete(&filedir, ".."); /* No assert--some directories may be bad */
4050         assert(Create(&filedir, "..", NewDirFid) == 0);
4051         fileptr->disk.dataVersion++;
4052         /* if the parent directories are different the link counts have to be   */
4053         /* changed due to .. in the renamed directory */
4054         if (oldvptr != newvptr) {
4055             oldvptr->disk.linkCount--;
4056             newvptr->disk.linkCount++;
4057         }
4058     }
4059
4060     /* set up return status */
4061     GetStatus(oldvptr, OutOldDirStatus, rights, anyrights, 0);
4062     GetStatus(newvptr, OutNewDirStatus, newrights, newanyrights, 0);
4063     if (newfileptr && doDelete) {
4064         DeleteFileCallBacks(&newFileFid);       /* no other references */
4065     }
4066
4067     DFlush();
4068
4069     /* convert the write locks to a read locks before breaking callbacks */
4070     VVnodeWriteToRead(&errorCode, newvptr);
4071     assert(!errorCode || errorCode == VSALVAGE);
4072     if (oldvptr != newvptr) {
4073         VVnodeWriteToRead(&errorCode, oldvptr);
4074         assert(!errorCode || errorCode == VSALVAGE);
4075     }
4076     if (newfileptr && !doDelete) {
4077         /* convert the write lock to a read lock before breaking callbacks */
4078         VVnodeWriteToRead(&errorCode, newfileptr);
4079         assert(!errorCode || errorCode == VSALVAGE);
4080     }
4081
4082     /* break call back on NewDirFid, OldDirFid, NewDirFid and newFileFid  */
4083     BreakCallBack(client->host, NewDirFid, 0);
4084     if (oldvptr != newvptr) {
4085         BreakCallBack(client->host, OldDirFid, 0);
4086         if (fileptr->disk.type == vDirectory) /* if a dir moved, .. changed */
4087             BreakCallBack(client->host, &fileFid, 0);
4088     }
4089     if (newfileptr) {
4090         /* Note:  it is not necessary to break the callback */
4091         if (doDelete)
4092             DeleteFileCallBacks(&newFileFid);   /* no other references */
4093         else
4094             /* other's still exist (with wrong link count) */
4095             BreakCallBack(client->host, &newFileFid, 1);
4096     }
4097
4098 Bad_Rename: 
4099     if (newfileptr) {
4100         VPutVnode(&fileCode, newfileptr);
4101         assert(fileCode == 0);
4102     }
4103     (void) PutVolumePackage(fileptr,
4104                             (newvptr && newvptr != oldvptr? newvptr : 0),
4105                             oldvptr, volptr);
4106     FidZap(&olddir);
4107     FidZap(&newdir);
4108     FidZap(&filedir);
4109     FidZap(&newfiledir);
4110     ViceLog(2, ("SAFS_Rename returns %d\n", errorCode));
4111     return errorCode;
4112
4113 } /*SAFSS_Rename*/
4114
4115
4116 afs_int32 SRXAFS_Rename (struct rx_call *acall,              
4117                          struct AFSFid *OldDirFid,                   
4118                          char *OldName,                      
4119                          struct AFSFid *NewDirFid,
4120                          char *NewName,
4121                          struct AFSFetchStatus *OutOldDirStatus,
4122                          struct AFSFetchStatus *OutNewDirStatus,
4123                          struct AFSVolSync *Sync)
4124 {
4125     afs_int32 code;
4126     struct rx_connection *tcon;
4127 #if FS_STATS_DETAILED
4128     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
4129     struct timeval opStartTime,
4130                    opStopTime;              /* Start/stop times for RPC op*/
4131     struct timeval elapsedTime;             /* Transfer time */
4132
4133     /*
4134      * Set our stats pointer, remember when the RPC operation started, and
4135      * tally the operation.
4136      */
4137     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RENAME]);
4138     FS_LOCK
4139     (opP->numOps)++;
4140     FS_UNLOCK
4141     TM_GetTimeOfDay(&opStartTime, 0);
4142 #endif /* FS_STATS_DETAILED */
4143
4144     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
4145         goto Bad_Rename;
4146
4147     code = SAFSS_Rename (acall, OldDirFid, OldName, NewDirFid, NewName,
4148                          OutOldDirStatus, OutNewDirStatus, Sync);
4149
4150 Bad_Rename:    
4151     code = CallPostamble(tcon, code);
4152
4153 #if FS_STATS_DETAILED
4154     TM_GetTimeOfDay(&opStopTime, 0);
4155     if (code == 0) {
4156       FS_LOCK
4157       (opP->numSuccesses)++;
4158       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4159       fs_stats_AddTo((opP->sumTime), elapsedTime);
4160       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4161       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4162         fs_stats_TimeAssign((opP->minTime), elapsedTime);
4163       }
4164       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4165         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4166       }
4167       FS_UNLOCK
4168     }
4169
4170 #endif /* FS_STATS_DETAILED */
4171
4172     osi_auditU (acall, RenameFileEvent, code, AUD_FID, OldDirFid, AUD_STR, OldName, AUD_FID, NewDirFid, AUD_STR, NewName, AUD_END);
4173     return code;
4174
4175 } /*SRXAFS_Rename*/
4176
4177
4178 /*
4179  * This routine is called exclusively by SRXAFS_Symlink(), and should be
4180  * merged into it when possible.
4181  */
4182 static afs_int32 
4183 SAFSS_Symlink (struct rx_call *acall,
4184                struct AFSFid *DirFid,
4185                char *Name,
4186                char *LinkContents,
4187                struct AFSStoreStatus *InStatus,
4188                struct AFSFid *OutFid,
4189                struct AFSFetchStatus *OutFidStatus,
4190                struct AFSFetchStatus *OutDirStatus,
4191                struct AFSVolSync *Sync)         
4192
4193 {
4194     Vnode * parentptr = 0;              /* vnode of input Directory */
4195     Vnode * targetptr = 0;              /* vnode of the new link */
4196     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
4197     int     errorCode = 0;              /* error code */
4198     int code = 0;
4199     DirHandle dir;                      /* Handle for dir package I/O */
4200     Volume * volptr = 0;                /* pointer to the volume header */
4201     struct client * client;             /* pointer to client structure */
4202     afs_int32 rights, anyrights, fd;    /* rights for this and any user */
4203     struct client *t_client;            /* tmp ptr to client data */
4204     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
4205     FdHandle_t *fdP;
4206     struct rx_connection *tcon = rx_ConnectionOf(acall);
4207
4208     FidZero(&dir);
4209
4210     /* Get ptr to client data for user Id for logging */
4211     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
4212     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
4213     ViceLog(1, ("SAFS_Symlink %s to %s,  Did = %u.%d.%d, Host %s, Id %d\n", Name,
4214             LinkContents, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4215             inet_ntoa(logHostAddr), t_client->ViceId));
4216     FS_LOCK
4217     AFSCallStats.Symlink++, AFSCallStats.TotalCalls++;
4218     FS_UNLOCK
4219     if (!FileNameOK(Name)) {
4220         errorCode = EINVAL;
4221         goto Bad_SymLink;
4222     }
4223
4224     /*
4225      * Get the vnode and volume for the parent dir along with the caller's
4226      * rights to it
4227      */
4228     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
4229                                      MustBeDIR, &parentwhentargetnotdir,
4230                                      &client, WRITE_LOCK, &rights, &anyrights))) {
4231         goto Bad_SymLink;
4232     }
4233
4234     /* set volume synchronization information */
4235     SetVolumeSync(Sync, volptr);
4236
4237     /* Does the caller has insert (and write) access to the parent directory? */
4238     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4239         goto Bad_SymLink;
4240     }
4241
4242     /*
4243      * If we're creating a mount point (any x bits clear), we must have
4244      * administer access to the directory, too.  Always allow sysadmins
4245      * to do this.
4246      */
4247     if ((InStatus->Mask & AFS_SETMODE) && !(InStatus->UnixModeBits & 0111)) {
4248         if (readonlyServer) {
4249             errorCode = VREADONLY;
4250             goto Bad_SymLink;
4251         }
4252         /*
4253          * We have a mountpoint, 'cause we're trying to set the Unix mode
4254          * bits to something with some x bits missing (default mode bits
4255          * if AFS_SETMODE is false is 0777)
4256          */
4257         if (VanillaUser(client) && !(rights & PRSFS_ADMINISTER)) {
4258             errorCode = EACCES;
4259             goto Bad_SymLink;
4260         }
4261     }
4262  
4263     /* get a new vnode for the symlink and set it up */
4264     if ((errorCode = Alloc_NewVnode(parentptr, &dir, volptr, &targetptr,
4265                                    Name, OutFid, vSymlink,
4266                                    nBlocks(strlen((char *) LinkContents))))) {
4267         goto Bad_SymLink;
4268     }
4269
4270     /* update the status of the parent vnode */
4271 #if FS_STATS_DETAILED
4272     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4273                              parentptr->disk.linkCount, client->InSameNetwork);
4274 #else
4275     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4276                              parentptr->disk.linkCount);
4277 #endif /* FS_STATS_DETAILED */
4278
4279     /* update the status of the new symbolic link file vnode */
4280     Update_TargetVnodeStatus(targetptr, TVS_SLINK, client, InStatus, parentptr,
4281                              volptr, strlen((char *)LinkContents));
4282
4283     /* Write the contents of the symbolic link name into the target inode */
4284     fdP = IH_OPEN(targetptr->handle);
4285     assert(fdP != NULL);
4286     assert(FDH_WRITE(fdP, (char *) LinkContents, strlen((char *) LinkContents)) == strlen((char *) LinkContents));
4287     FDH_CLOSE(fdP);
4288     /*
4289      * Set up and return modified status for the parent dir and new symlink
4290      * to caller.
4291      */
4292     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4293     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4294
4295     /* convert the write lock to a read lock before breaking callbacks */
4296     VVnodeWriteToRead(&errorCode, parentptr);
4297     assert(!errorCode || errorCode == VSALVAGE);
4298
4299     /* break call back on the parent dir */
4300     BreakCallBack(client->host, DirFid, 0);
4301
4302 Bad_SymLink: 
4303     /* Write the all modified vnodes (parent, new files) and volume back */
4304     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4305                             volptr);
4306     FidZap(&dir);
4307     ViceLog(2, ("SAFS_Symlink returns %d\n", errorCode));
4308     return errorCode;
4309
4310 } /*SAFSS_Symlink*/
4311
4312
4313 afs_int32 SRXAFS_Symlink (acall, DirFid, Name, LinkContents, InStatus, OutFid, OutFidStatus, OutDirStatus, Sync)
4314     struct AFSVolSync *Sync;
4315     struct rx_call *acall;               /* Rx call */
4316     struct AFSFid *DirFid;               /* Parent dir's fid */
4317     char *Name;                          /* File name to create */
4318     char *LinkContents;                  /* Contents of the new created file */
4319     struct AFSStoreStatus *InStatus;     /* Input status for the new symbolic link */
4320     struct AFSFid *OutFid;               /* Fid for newly created symbolic link */
4321     struct AFSFetchStatus *OutFidStatus; /* Output status for new symbolic link */
4322     struct AFSFetchStatus *OutDirStatus; /* Output status for parent dir */
4323
4324 {
4325     afs_int32 code;
4326     struct rx_connection *tcon;
4327 #if FS_STATS_DETAILED
4328     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
4329     struct timeval opStartTime,
4330                    opStopTime;              /* Start/stop times for RPC op*/
4331     struct timeval elapsedTime;             /* Transfer time */
4332
4333     /*
4334      * Set our stats pointer, remember when the RPC operation started, and
4335      * tally the operation.
4336      */
4337     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SYMLINK]);
4338     FS_LOCK
4339     (opP->numOps)++;
4340     FS_UNLOCK
4341     TM_GetTimeOfDay(&opStartTime, 0);
4342 #endif /* FS_STATS_DETAILED */
4343
4344     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
4345         goto Bad_Symlink;
4346
4347     code = SAFSS_Symlink (acall, DirFid, Name, LinkContents, InStatus, OutFid,
4348                          OutFidStatus, OutDirStatus, Sync);
4349
4350 Bad_Symlink:    
4351     code = CallPostamble(tcon, code);
4352
4353 #if FS_STATS_DETAILED
4354     TM_GetTimeOfDay(&opStopTime, 0);
4355     if (code == 0) {
4356       FS_LOCK
4357       (opP->numSuccesses)++;
4358       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4359       fs_stats_AddTo((opP->sumTime), elapsedTime);
4360       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4361       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4362         fs_stats_TimeAssign((opP->minTime), elapsedTime);
4363       }
4364       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4365         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4366       }
4367       FS_UNLOCK
4368     }
4369
4370 #endif /* FS_STATS_DETAILED */
4371
4372     osi_auditU (acall, SymlinkEvent, code, AUD_FID, DirFid, AUD_STR, Name, AUD_END);
4373     return code;
4374
4375 } /*SRXAFS_Symlink*/
4376
4377
4378 /*
4379  * This routine is called exclusively by SRXAFS_Link(), and should be
4380  * merged into it when possible.
4381  */
4382 static afs_int32 
4383 SAFSS_Link (struct rx_call *acall,
4384             struct AFSFid *DirFid,
4385             char *Name,
4386             struct AFSFid *ExistingFid,
4387             struct AFSFetchStatus *OutFidStatus,
4388             struct AFSFetchStatus *OutDirStatus,
4389             struct AFSVolSync *Sync)
4390 {
4391     Vnode * parentptr = 0;              /* vnode of input Directory */
4392     Vnode * targetptr = 0;              /* vnode of the new file */
4393     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
4394     Volume * volptr = 0;                /* pointer to the volume header */
4395     int     errorCode = 0;              /* error code */
4396     DirHandle dir;                      /* Handle for dir package I/O */
4397     struct client * client;             /* pointer to client structure */
4398     afs_int32 rights, anyrights;                /* rights for this and any user */
4399     struct client *t_client;            /* tmp ptr to client data */
4400     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
4401     struct rx_connection *tcon = rx_ConnectionOf(acall);
4402
4403     FidZero(&dir);
4404
4405     /* Get ptr to client data for user Id for logging */
4406     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
4407     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
4408     ViceLog(1, ("SAFS_Link %s,  Did = %u.%d.%d, Fid = %u.%d.%d, Host %s, Id %d\n",
4409             Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4410             ExistingFid->Volume, ExistingFid->Vnode, ExistingFid->Unique,
4411             inet_ntoa(logHostAddr), t_client->ViceId));
4412     FS_LOCK
4413     AFSCallStats.Link++, AFSCallStats.TotalCalls++;
4414     FS_UNLOCK
4415     if (DirFid->Volume != ExistingFid->Volume) {
4416         errorCode = EXDEV;
4417         goto Bad_Link;
4418     }
4419     if (!FileNameOK(Name)) {
4420         errorCode = EINVAL;
4421         goto Bad_Link;
4422     }
4423
4424     /*
4425      * Get the vnode and volume for the parent dir along with the caller's
4426      * rights to it
4427      */
4428     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
4429                                      MustBeDIR, &parentwhentargetnotdir,
4430                                      &client, WRITE_LOCK, &rights, &anyrights))) {
4431         goto Bad_Link;
4432     }
4433
4434     /* set volume synchronization information */
4435     SetVolumeSync(Sync, volptr);
4436
4437     /* Can the caller insert into the parent directory? */
4438     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4439         goto Bad_Link;
4440     }
4441
4442     if (((DirFid->Vnode & 1) && (ExistingFid->Vnode & 1)) ||
4443         (DirFid->Vnode == ExistingFid->Vnode)) {  /* at present, */
4444       /* AFS fileservers always have directory vnodes that are odd.   */
4445       errorCode = EISDIR;
4446       goto Bad_Link;
4447     }
4448
4449     /* get the file vnode  */
4450     if ((errorCode = CheckVnode(ExistingFid, &volptr, &targetptr, WRITE_LOCK))) {
4451         goto Bad_Link;
4452     }
4453     if (targetptr->disk.type != vFile) {
4454         errorCode = EISDIR;
4455         goto Bad_Link;
4456     }
4457     if (targetptr->disk.parent != DirFid->Vnode) {
4458         errorCode = EXDEV;
4459         goto Bad_Link;
4460     }
4461     if (parentptr->disk.cloned) 
4462     {
4463         ViceLog(25, ("Link : calling CopyOnWrite on  target dir\n"));
4464         if ( ( errorCode = CopyOnWrite(parentptr, volptr)))
4465                 goto Bad_Link;          /* disk full error */
4466     }
4467
4468     /* add the name to the directory */
4469     SetDirHandle(&dir, parentptr);
4470     if ((errorCode = Create(&dir, (char *)Name, ExistingFid)))
4471         goto Bad_Link;
4472     DFlush();
4473
4474     /* update the status in the parent vnode */
4475     /**WARNING** --> disk.author SHOULDN'T be modified???? */
4476 #if FS_STATS_DETAILED
4477     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4478                              parentptr->disk.linkCount, client->InSameNetwork);
4479 #else
4480     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4481                              parentptr->disk.linkCount);
4482 #endif /* FS_STATS_DETAILED */
4483
4484     targetptr->disk.linkCount++;
4485     targetptr->disk.author = client->ViceId;
4486     targetptr->changed_newTime = 1; /* Status change of linked-to file */
4487
4488     /* set up return status */
4489     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4490     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4491
4492     /* convert the write locks to read locks before breaking callbacks */
4493     VVnodeWriteToRead(&errorCode, targetptr);
4494     assert(!errorCode || errorCode == VSALVAGE);
4495     VVnodeWriteToRead(&errorCode, parentptr);
4496     assert(!errorCode || errorCode == VSALVAGE);
4497     
4498     /* break call back on DirFid */
4499     BreakCallBack(client->host, DirFid, 0);
4500     /*
4501      * We also need to break the callback for the file that is hard-linked since part 
4502      * of its status (like linkcount) is changed
4503      */
4504     BreakCallBack(client->host, ExistingFid, 0);
4505
4506 Bad_Link:
4507     /* Write the all modified vnodes (parent, new files) and volume back */
4508     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4509                             volptr);
4510     FidZap(&dir);
4511     ViceLog(2, ("SAFS_Link returns %d\n", errorCode));
4512     return errorCode;
4513
4514 } /*SAFSS_Link*/
4515
4516
4517 afs_int32 SRXAFS_Link (struct rx_call *acall,
4518                        struct AFSFid *DirFid,
4519                        char *Name,
4520                        struct AFSFid *ExistingFid,
4521                        struct AFSFetchStatus *OutFidStatus,
4522                        struct AFSFetchStatus *OutDirStatus,
4523                        struct AFSVolSync *Sync)
4524 {
4525     afs_int32 code;
4526     struct rx_connection *tcon;
4527 #if FS_STATS_DETAILED
4528     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
4529     struct timeval opStartTime,
4530                    opStopTime;              /* Start/stop times for RPC op*/
4531     struct timeval elapsedTime;             /* Transfer time */
4532
4533     /*
4534      * Set our stats pointer, remember when the RPC operation started, and
4535      * tally the operation.
4536      */
4537     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_LINK]);
4538     FS_LOCK
4539     (opP->numOps)++;
4540     FS_UNLOCK
4541     TM_GetTimeOfDay(&opStartTime, 0);
4542 #endif /* FS_STATS_DETAILED */
4543
4544     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
4545         goto Bad_Link;
4546
4547     code = SAFSS_Link (acall, DirFid, Name, ExistingFid, OutFidStatus,
4548                       OutDirStatus, Sync);
4549     
4550 Bad_Link:
4551     code = CallPostamble(tcon, code);
4552
4553 #if FS_STATS_DETAILED
4554     TM_GetTimeOfDay(&opStopTime, 0);
4555     if (code == 0) {
4556       FS_LOCK
4557       (opP->numSuccesses)++;
4558       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4559       fs_stats_AddTo((opP->sumTime), elapsedTime);
4560       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4561       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4562         fs_stats_TimeAssign((opP->minTime), elapsedTime);
4563       }
4564       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4565         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4566       }
4567       FS_UNLOCK
4568     }
4569
4570 #endif /* FS_STATS_DETAILED */
4571
4572     osi_auditU (acall, LinkEvent, code, AUD_FID, DirFid, AUD_STR, Name, AUD_FID, ExistingFid, AUD_END);
4573     return code;
4574
4575 } /*SRXAFS_Link*/
4576
4577
4578 /*
4579  * This routine is called exclusively by SRXAFS_MakeDir(), and should be
4580  * merged into it when possible.
4581  */
4582 static afs_int32
4583 SAFSS_MakeDir (struct rx_call *acall,
4584                struct AFSFid *DirFid,
4585                char *Name,
4586                struct AFSStoreStatus *InStatus,
4587                struct AFSFid *OutFid,
4588                struct AFSFetchStatus *OutFidStatus,
4589                struct AFSFetchStatus *OutDirStatus,
4590                struct AFSCallBack *CallBack,
4591                struct AFSVolSync *Sync)
4592
4593 {
4594     Vnode * parentptr = 0;              /* vnode of input Directory */
4595     Vnode * targetptr = 0;              /* vnode of the new file */
4596     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
4597     Volume * volptr = 0;                /* pointer to the volume header */
4598     int     errorCode = 0;              /* error code */
4599     struct acl_accessList * newACL;     /* Access list */
4600     int     newACLSize;                 /* Size of access list */
4601     DirHandle dir;                      /* Handle for dir package I/O */
4602     DirHandle parentdir;                /* Handle for dir package I/O */
4603     struct client * client;             /* pointer to client structure */
4604     afs_int32 rights, anyrights;                /* rights for this and any user */
4605     struct client *t_client;            /* tmp ptr to client data */
4606     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
4607     struct rx_connection *tcon = rx_ConnectionOf(acall);
4608
4609     FidZero(&dir);
4610     FidZero(&parentdir);
4611
4612     /* Get ptr to client data for user Id for logging */
4613     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
4614     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
4615     ViceLog(1, ("SAFS_MakeDir %s,  Did = %u.%d.%d, Host %s, Id %d\n",
4616             Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4617             inet_ntoa(logHostAddr), t_client->ViceId));
4618     FS_LOCK
4619     AFSCallStats.MakeDir++, AFSCallStats.TotalCalls++;    
4620     FS_UNLOCK
4621     if (!FileNameOK(Name)) {
4622         errorCode = EINVAL;
4623         goto Bad_MakeDir;
4624     }
4625
4626     /*
4627      * Get the vnode and volume for the parent dir along with the caller's
4628      * rights to it.
4629      */
4630     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
4631                                      MustBeDIR, &parentwhentargetnotdir,
4632                                      &client, WRITE_LOCK, &rights, &anyrights))) {
4633         goto Bad_MakeDir;
4634     }
4635  
4636     /* set volume synchronization information */
4637     SetVolumeSync(Sync, volptr);
4638
4639     /* Write access to the parent directory? */
4640 #ifdef DIRCREATE_NEED_WRITE
4641     /*
4642      * requires w access for the user to create a directory. this
4643      * closes a loophole in the current security arrangement, since a
4644      * user with i access only can create a directory and get the
4645      * implcit a access that goes with dir ownership, and proceed to 
4646      * subvert quota in the volume.
4647      */
4648     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT)) ||
4649         (errorCode = CheckWriteMode(parentptr, rights, PRSFS_WRITE))) {
4650 #else 
4651     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4652 #endif /* DIRCREATE_NEED_WRITE */ 
4653         goto Bad_MakeDir;
4654     }
4655
4656 #define EMPTYDIRBLOCKS 2
4657     /* get a new vnode and set it up */
4658     if ((errorCode = Alloc_NewVnode(parentptr, &parentdir, volptr, &targetptr,
4659                                    Name, OutFid, vDirectory, EMPTYDIRBLOCKS))) {
4660         goto Bad_MakeDir;
4661     }
4662
4663     /* Update the status for the parent dir */
4664 #if FS_STATS_DETAILED
4665     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4666                              parentptr->disk.linkCount+1, client->InSameNetwork);
4667 #else
4668     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4669                              parentptr->disk.linkCount+1);
4670 #endif /* FS_STATS_DETAILED */
4671
4672     /* Point to target's ACL buffer and copy the parent's ACL contents to it */
4673     assert((SetAccessList(&targetptr, &volptr, &newACL, &newACLSize,
4674                           &parentwhentargetnotdir, (AFSFid *)0, 0)) == 0);
4675     assert(parentwhentargetnotdir == 0);
4676     memcpy((char *)newACL, (char *)VVnodeACL(parentptr), VAclSize(parentptr));
4677
4678     /* update the status for the target vnode */
4679     Update_TargetVnodeStatus(targetptr, TVS_MKDIR, client, InStatus,
4680                              parentptr, volptr, 0);
4681
4682     /* Actually create the New directory in the directory package */ 
4683     SetDirHandle(&dir, targetptr);
4684     assert(!(MakeDir(&dir, OutFid, DirFid)));
4685     DFlush();
4686     VN_SET_LEN(targetptr, Length(&dir));
4687
4688     /* set up return status */
4689     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4690     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4691
4692     /* convert the write lock to a read lock before breaking callbacks */
4693     VVnodeWriteToRead(&errorCode, parentptr);
4694     assert(!errorCode || errorCode == VSALVAGE);
4695
4696     /* break call back on DirFid */
4697     BreakCallBack(client->host, DirFid, 0);
4698
4699     /* Return a callback promise to caller */
4700     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
4701
4702 Bad_MakeDir: 
4703     /* Write the all modified vnodes (parent, new files) and volume back */
4704     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4705                             volptr);
4706     FidZap(&dir);
4707     FidZap(&parentdir);
4708     ViceLog(2, ("SAFS_MakeDir returns %d\n", errorCode)); 
4709     return errorCode;
4710
4711 } /*SAFSS_MakeDir*/
4712
4713
4714 afs_int32 SRXAFS_MakeDir (struct rx_call *acall,
4715                           struct AFSFid *DirFid,
4716                           char *Name,
4717                           struct AFSStoreStatus *InStatus,
4718                           struct AFSFid *OutFid,
4719                           struct AFSFetchStatus *OutFidStatus,
4720                           struct AFSFetchStatus *OutDirStatus,
4721                           struct AFSCallBack *CallBack,
4722                           struct AFSVolSync *Sync)
4723 {
4724     afs_int32 code;
4725     struct rx_connection *tcon;
4726 #if FS_STATS_DETAILED
4727     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
4728     struct timeval opStartTime,
4729                    opStopTime;              /* Start/stop times for RPC op*/
4730     struct timeval elapsedTime;             /* Transfer time */
4731
4732     /*
4733      * Set our stats pointer, remember when the RPC operation started, and
4734      * tally the operation.
4735      */
4736     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_MAKEDIR]);
4737     FS_LOCK
4738     (opP->numOps)++;
4739     FS_UNLOCK
4740     TM_GetTimeOfDay(&opStartTime, 0);
4741 #endif /* FS_STATS_DETAILED */
4742     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
4743         goto Bad_MakeDir;
4744
4745     code = SAFSS_MakeDir (acall, DirFid, Name, InStatus, OutFid,
4746                          OutFidStatus, OutDirStatus, CallBack, Sync);
4747     
4748 Bad_MakeDir:
4749     code = CallPostamble(tcon, code);
4750
4751 #if FS_STATS_DETAILED
4752     TM_GetTimeOfDay(&opStopTime, 0);
4753     if (code == 0) {
4754       FS_LOCK
4755       (opP->numSuccesses)++;
4756       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4757       fs_stats_AddTo((opP->sumTime), elapsedTime);
4758       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4759       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4760         fs_stats_TimeAssign((opP->minTime), elapsedTime);
4761       }
4762       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4763         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4764       }
4765       FS_UNLOCK
4766     }
4767
4768 #endif /* FS_STATS_DETAILED */
4769
4770     osi_auditU (acall, MakeDirEvent, code, AUD_FID, DirFid, AUD_STR, Name, AUD_END);
4771     return code;
4772
4773 } /*SRXAFS_MakeDir*/
4774
4775
4776 /*
4777  * This routine is called exclusively by SRXAFS_RemoveDir(), and should be
4778  * merged into it when possible.
4779  */
4780 static afs_int32
4781 SAFSS_RemoveDir (struct rx_call *acall,
4782                  struct AFSFid *DirFid,
4783                  char *Name,
4784                  struct AFSFetchStatus *OutDirStatus,
4785                  struct AFSVolSync *Sync)
4786
4787 {
4788     Vnode * parentptr = 0;              /* vnode of input Directory */
4789     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
4790     Vnode * targetptr = 0;              /* file to be deleted */
4791     AFSFid fileFid;                     /* area for Fid from the directory */
4792     int     errorCode = 0;              /* error code */
4793     DirHandle dir;                      /* Handle for dir package I/O */
4794     Volume * volptr = 0;                /* pointer to the volume header */
4795     struct client * client;             /* pointer to client structure */
4796     afs_int32 rights, anyrights;                /* rights for this and any user */
4797     Vnode debugvnode1, debugvnode2;
4798     struct client *t_client;            /* tmp ptr to client data */
4799     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
4800     struct rx_connection *tcon = rx_ConnectionOf(acall);
4801
4802     FidZero(&dir);
4803
4804     /* Get ptr to client data for user Id for logging */
4805     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
4806     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
4807     ViceLog(1, ("SAFS_RemoveDir %s,  Did = %u.%d.%d, Host %s, Id %d\n",
4808             Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4809             inet_ntoa(logHostAddr), t_client->ViceId));
4810     FS_LOCK
4811     AFSCallStats.RemoveDir++, AFSCallStats.TotalCalls++;
4812     FS_UNLOCK
4813     /*
4814      * Get the vnode and volume for the parent dir along with the caller's
4815      * rights to it
4816      */
4817     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
4818                                      MustBeDIR, &parentwhentargetnotdir,
4819                                      &client, WRITE_LOCK, &rights, &anyrights))) {
4820         goto Bad_RemoveDir;
4821     }
4822     debugvnode1 = *parentptr;
4823
4824     /* set volume synchronization information */
4825     SetVolumeSync(Sync, volptr);
4826
4827     /* Does the caller has delete (&write) access to the parent dir? */
4828     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
4829         goto Bad_RemoveDir;
4830     }
4831
4832     debugvnode2 = *parentptr;
4833     /* Do the actual delete of the desired (empty) directory, Name */
4834     if ((errorCode = DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid,
4835                                  Name, MustBeDIR))) {
4836         goto Bad_RemoveDir;
4837     }
4838
4839     /* Update the status for the parent dir; link count is also adjusted */
4840 #if FS_STATS_DETAILED
4841     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4842                              parentptr->disk.linkCount-1, client->InSameNetwork);
4843 #else
4844     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4845                              parentptr->disk.linkCount-1);
4846 #endif /* FS_STATS_DETAILED */
4847
4848     /* Return to the caller the updated parent dir status */
4849     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4850
4851     /*
4852      * Note: it is not necessary to break the callback on fileFid, since
4853      * refcount is now 0, so no one should be able to refer to the dir
4854      * any longer
4855      */
4856     DeleteFileCallBacks(&fileFid);
4857
4858     /* convert the write lock to a read lock before breaking callbacks */
4859     VVnodeWriteToRead(&errorCode, parentptr);
4860     assert(!errorCode || errorCode == VSALVAGE);
4861
4862     /* break call back on DirFid and fileFid */
4863     BreakCallBack(client->host, DirFid, 0);
4864
4865 Bad_RemoveDir: 
4866     /* Write the all modified vnodes (parent, new files) and volume back */
4867     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4868                             volptr);
4869     FidZap(&dir);
4870     ViceLog(2, ("SAFS_RemoveDir returns %d\n", errorCode));
4871     return errorCode;
4872
4873 } /*SAFSS_RemoveDir*/
4874
4875
4876 afs_int32 SRXAFS_RemoveDir (struct rx_call *acall,
4877                             struct AFSFid *DirFid,
4878                             char *Name,
4879                             struct AFSFetchStatus *OutDirStatus,
4880                             struct AFSVolSync *Sync)
4881 {
4882     afs_int32 code;
4883     struct rx_connection *tcon;
4884 #if FS_STATS_DETAILED
4885     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
4886     struct timeval opStartTime,
4887                    opStopTime;              /* Start/stop times for RPC op*/
4888     struct timeval elapsedTime;             /* Transfer time */
4889
4890     /*
4891      * Set our stats pointer, remember when the RPC operation started, and
4892      * tally the operation.
4893      */
4894     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEDIR]);
4895     FS_LOCK
4896     (opP->numOps)++;
4897     FS_UNLOCK
4898     TM_GetTimeOfDay(&opStartTime, 0);
4899 #endif /* FS_STATS_DETAILED */
4900
4901     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
4902         goto Bad_RemoveDir;
4903
4904     code = SAFSS_RemoveDir (acall, DirFid, Name, OutDirStatus, Sync);
4905     
4906 Bad_RemoveDir:
4907     code = CallPostamble(tcon, code);
4908
4909 #if FS_STATS_DETAILED
4910     TM_GetTimeOfDay(&opStopTime, 0);
4911     if (code == 0) {
4912       FS_LOCK
4913       (opP->numSuccesses)++;
4914       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4915       fs_stats_AddTo((opP->sumTime), elapsedTime);
4916       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4917       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4918         fs_stats_TimeAssign((opP->minTime), elapsedTime);
4919       }
4920       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4921         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4922       }
4923       FS_UNLOCK
4924     }
4925
4926 #endif /* FS_STATS_DETAILED */
4927
4928     osi_auditU (acall, RemoveDirEvent, code, AUD_FID, DirFid, AUD_STR, Name, AUD_END);
4929     return code;
4930
4931 } /*SRXAFS_RemoveDir*/
4932
4933
4934 /*
4935  * This routine is called exclusively by SRXAFS_SetLock(), and should be
4936  * merged into it when possible.
4937  */
4938 static afs_int32
4939 SAFSS_SetLock (struct rx_call *acall,
4940                struct AFSFid *Fid,
4941                ViceLockType type,
4942                struct AFSVolSync *Sync)
4943 {
4944     Vnode * targetptr = 0;              /* vnode of input file */
4945     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
4946     int     errorCode = 0;              /* error code */
4947     Volume * volptr = 0;                /* pointer to the volume header */
4948     struct client * client;             /* pointer to client structure */
4949     afs_int32 rights, anyrights;                /* rights for this and any user */
4950     struct client *t_client;            /* tmp ptr to client data */
4951     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
4952     static char * locktype[2] = {"LockRead","LockWrite"};
4953     struct rx_connection *tcon = rx_ConnectionOf(acall);
4954
4955     if (type != LockRead && type != LockWrite) {
4956         errorCode = EINVAL;
4957         goto Bad_SetLock;
4958     }
4959     /* Get ptr to client data for user Id for logging */
4960     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
4961     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
4962     ViceLog(1,("SAFS_SetLock type = %s Fid = %u.%d.%d, Host %s, Id %d\n",
4963             locktype[(int)type], Fid->Volume, Fid->Vnode, Fid->Unique,
4964             inet_ntoa(logHostAddr), t_client->ViceId));
4965     FS_LOCK
4966     AFSCallStats.SetLock++, AFSCallStats.TotalCalls++;
4967     FS_UNLOCK
4968
4969     /*
4970      * Get the vnode and volume for the desired file along with the caller's
4971      * rights to it
4972      */
4973     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
4974                                      DONTCHECK, &parentwhentargetnotdir,
4975                                      &client, WRITE_LOCK, &rights, &anyrights))) {
4976         goto Bad_SetLock;
4977     }
4978
4979     /* set volume synchronization information */
4980     SetVolumeSync(Sync, volptr);
4981
4982     /* Handle the particular type of set locking, type */
4983     errorCode = HandleLocking(targetptr, rights, type);
4984
4985 Bad_SetLock: 
4986     /* Write the all modified vnodes (parent, new files) and volume back */
4987     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
4988                             volptr);
4989
4990     if ((errorCode == VREADONLY) && (type == LockRead))
4991        errorCode = 0;  /* allow read locks on RO volumes without saving state */
4992
4993     ViceLog(2,("SAFS_SetLock returns %d\n", errorCode));
4994     return(errorCode);
4995
4996 }  /*SAFSS_SetLock*/
4997
4998
4999 afs_int32 SRXAFS_OldSetLock(struct rx_call *acall,
5000                             struct AFSFid *Fid,
5001                             ViceLockType type,
5002                             struct AFSVolSync *Sync)
5003 {
5004     return SRXAFS_SetLock(acall, Fid, type, Sync);
5005
5006 } /*SRXAFS_OldSetLock*/
5007
5008
5009 afs_int32 SRXAFS_SetLock (struct rx_call *acall,
5010                           struct AFSFid *Fid,
5011                           ViceLockType type,
5012                           struct AFSVolSync *Sync)
5013 {
5014     afs_int32 code;
5015     struct rx_connection *tcon;
5016 #if FS_STATS_DETAILED
5017     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5018     struct timeval opStartTime,
5019                    opStopTime;              /* Start/stop times for RPC op*/
5020     struct timeval elapsedTime;             /* Transfer time */
5021
5022     /*
5023      * Set our stats pointer, remember when the RPC operation started, and
5024      * tally the operation.
5025      */
5026     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETLOCK]);
5027     FS_LOCK
5028     (opP->numOps)++;
5029     FS_UNLOCK
5030     TM_GetTimeOfDay(&opStartTime, 0);
5031 #endif /* FS_STATS_DETAILED */
5032
5033     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
5034         goto Bad_SetLock;
5035
5036     code = SAFSS_SetLock (acall, Fid, type, Sync);
5037     
5038 Bad_SetLock:
5039     code = CallPostamble(tcon, code);
5040
5041 #if FS_STATS_DETAILED
5042     TM_GetTimeOfDay(&opStopTime, 0); 
5043     if (code == 0) {
5044       FS_LOCK
5045       (opP->numSuccesses)++;
5046       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5047       fs_stats_AddTo((opP->sumTime), elapsedTime);
5048       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5049       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5050         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5051       }
5052       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5053         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5054       }
5055       FS_UNLOCK
5056     }
5057 #endif /* FS_STATS_DETAILED */
5058
5059     osi_auditU (acall, SetLockEvent, code, AUD_FID, Fid, AUD_LONG, type, AUD_END);
5060     return code;
5061
5062 } /*SRXAFS_SetLock*/
5063
5064
5065 /*
5066  * This routine is called exclusively by SRXAFS_ExtendLock(), and should be
5067  * merged into it when possible.
5068  */
5069 static afs_int32 
5070 SAFSS_ExtendLock (struct rx_call *acall,
5071                   struct AFSFid *Fid,
5072                   struct AFSVolSync *Sync)
5073
5074 {
5075     Vnode * targetptr = 0;              /* vnode of input file */
5076     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
5077     int     errorCode = 0;              /* error code */
5078     Volume * volptr = 0;                /* pointer to the volume header */
5079     struct client * client;             /* pointer to client structure */
5080     afs_int32 rights, anyrights;                /* rights for this and any user */
5081     struct client *t_client;            /* tmp ptr to client data */
5082     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
5083     struct rx_connection *tcon = rx_ConnectionOf(acall);
5084
5085     /* Get ptr to client data for user Id for logging */
5086     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
5087     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
5088     ViceLog(1,("SAFS_ExtendLock Fid = %u.%d.%d, Host %s, Id %d\n", 
5089                Fid->Volume, Fid->Vnode, Fid->Unique, 
5090                inet_ntoa(logHostAddr), t_client->ViceId));
5091     FS_LOCK
5092     AFSCallStats.ExtendLock++, AFSCallStats.TotalCalls++;    
5093     FS_UNLOCK
5094     /*
5095      * Get the vnode and volume for the desired file along with the caller's
5096      * rights to it
5097      */
5098     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
5099                                      DONTCHECK, &parentwhentargetnotdir,
5100                                      &client, WRITE_LOCK, &rights, &anyrights))) {
5101         goto Bad_ExtendLock;
5102     }
5103
5104     /* set volume synchronization information */
5105     SetVolumeSync(Sync, volptr);
5106
5107     /* Handle the actual lock extension */
5108     errorCode = HandleLocking(targetptr, rights, LockExtend);
5109
5110 Bad_ExtendLock: 
5111     /* Put back file's vnode and volume */
5112     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
5113                             volptr);
5114
5115     if ((errorCode == VREADONLY))  /* presumably, we already granted this lock */
5116        errorCode = 0;              /* under our generous policy re RO vols */
5117
5118     ViceLog(2,("SAFS_ExtendLock returns %d\n", errorCode));
5119     return(errorCode);
5120
5121 } /*SAFSS_ExtendLock*/
5122
5123
5124 afs_int32 SRXAFS_OldExtendLock (struct rx_call *acall,
5125                                 struct AFSFid *Fid,
5126                                 struct AFSVolSync *Sync)
5127 {
5128     return SRXAFS_ExtendLock(acall, Fid, Sync);
5129
5130 } /*SRXAFS_OldExtendLock*/
5131
5132
5133 afs_int32 SRXAFS_ExtendLock (struct rx_call *acall,
5134                              struct AFSFid *Fid,
5135                              struct AFSVolSync *Sync)
5136 {
5137     afs_int32 code;
5138     struct rx_connection *tcon;
5139 #if FS_STATS_DETAILED
5140     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5141     struct timeval opStartTime,
5142                    opStopTime;              /* Start/stop times for RPC op*/
5143     struct timeval elapsedTime;             /* Transfer time */
5144
5145     /*
5146      * Set our stats pointer, remember when the RPC operation started, and
5147      * tally the operation.
5148      */
5149     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_EXTENDLOCK]);
5150     FS_LOCK
5151     (opP->numOps)++;
5152     FS_UNLOCK
5153     TM_GetTimeOfDay(&opStartTime, 0);
5154 #endif /* FS_STATS_DETAILED */
5155
5156     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
5157         goto Bad_ExtendLock;
5158
5159     code = SAFSS_ExtendLock (acall, Fid, Sync);
5160
5161 Bad_ExtendLock:
5162     code = CallPostamble(tcon, code);
5163
5164 #if FS_STATS_DETAILED
5165     TM_GetTimeOfDay(&opStopTime, 0);
5166     if (code == 0) {
5167       FS_LOCK
5168       (opP->numSuccesses)++;
5169       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5170       fs_stats_AddTo((opP->sumTime), elapsedTime);
5171       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5172       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5173         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5174       }
5175       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5176         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5177       }
5178       FS_UNLOCK
5179     }
5180
5181 #endif /* FS_STATS_DETAILED */
5182
5183     osi_auditU (acall, ExtendLockEvent, code, AUD_FID, Fid , AUD_END);
5184     return code;
5185
5186 } /*SRXAFS_ExtendLock*/
5187
5188
5189 /*
5190  * This routine is called exclusively by SRXAFS_ReleaseLock(), and should be
5191  * merged into it when possible.
5192  */
5193 static afs_int32 
5194 SAFSS_ReleaseLock (struct rx_call *acall,
5195                    struct AFSFid *Fid,
5196                    struct AFSVolSync *Sync)
5197
5198 {
5199     Vnode * targetptr = 0;              /* vnode of input file */
5200     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
5201     int     errorCode = 0;              /* error code */
5202     Volume * volptr = 0;                /* pointer to the volume header */
5203     struct client * client;             /* pointer to client structure */
5204     afs_int32 rights, anyrights;                /* rights for this and any user */
5205     struct client *t_client;            /* tmp ptr to client data */
5206     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
5207     struct rx_connection *tcon = rx_ConnectionOf(acall);
5208
5209     /* Get ptr to client data for user Id for logging */
5210     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
5211     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
5212     ViceLog(1,("SAFS_ReleaseLock Fid = %u.%d.%d, Host %s, Id %d\n",
5213             Fid->Volume, Fid->Vnode, Fid->Unique,
5214             inet_ntoa(logHostAddr), t_client->ViceId));
5215     FS_LOCK
5216     AFSCallStats.ReleaseLock++, AFSCallStats.TotalCalls++;
5217     FS_UNLOCK
5218     /*
5219      * Get the vnode and volume for the desired file along with the caller's
5220      * rights to it
5221      */
5222     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
5223                                      DONTCHECK, &parentwhentargetnotdir,
5224                                      &client, WRITE_LOCK, &rights, &anyrights))) {
5225         goto Bad_ReleaseLock;
5226     }
5227
5228     /* set volume synchronization information */
5229     SetVolumeSync(Sync, volptr);
5230
5231     /* Handle the actual lock release */
5232     if ((errorCode = HandleLocking(targetptr, rights, LockRelease)))
5233         goto Bad_ReleaseLock;
5234
5235     /* if no more locks left, a callback would be triggered here */
5236     if (targetptr->disk.lock.lockCount <= 0) {
5237         /* convert the write lock to a read lock before breaking callbacks */
5238         VVnodeWriteToRead(&errorCode, targetptr);
5239         assert(!errorCode || errorCode == VSALVAGE);
5240         BreakCallBack(client->host, Fid, 0);
5241     }
5242
5243 Bad_ReleaseLock: 
5244     /* Put back file's vnode and volume */
5245     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
5246                             volptr);
5247
5248     if ((errorCode == VREADONLY))  /* presumably, we already granted this lock */
5249        errorCode = 0;              /* under our generous policy re RO vols */
5250
5251     ViceLog(2,("SAFS_ReleaseLock returns %d\n", errorCode));
5252     return(errorCode);
5253
5254 } /*SAFSS_ReleaseLock*/
5255
5256
5257 afs_int32 SRXAFS_OldReleaseLock (struct rx_call *acall,
5258                                  struct AFSFid *Fid,
5259                                  struct AFSVolSync *Sync)
5260 {
5261     return SRXAFS_ReleaseLock(acall, Fid, Sync);
5262
5263 } /*SRXAFS_OldReleaseLock*/
5264
5265
5266 afs_int32 SRXAFS_ReleaseLock (struct rx_call *acall,
5267                               struct AFSFid *Fid,
5268                               struct AFSVolSync *Sync)
5269 {
5270     afs_int32 code;
5271     struct rx_connection *tcon;
5272 #if FS_STATS_DETAILED
5273     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5274     struct timeval opStartTime,
5275                    opStopTime;              /* Start/stop times for RPC op*/
5276     struct timeval elapsedTime;             /* Transfer time */
5277
5278     /*
5279      * Set our stats pointer, remember when the RPC operation started, and
5280      * tally the operation.
5281      */
5282     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RELEASELOCK]);
5283     FS_LOCK
5284     (opP->numOps)++;
5285     FS_UNLOCK
5286     TM_GetTimeOfDay(&opStartTime, 0);
5287 #endif /* FS_STATS_DETAILED */
5288
5289     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
5290         goto Bad_ReleaseLock;
5291
5292     code = SAFSS_ReleaseLock (acall, Fid, Sync);
5293     
5294 Bad_ReleaseLock:
5295     code = CallPostamble(tcon, code);
5296
5297 #if FS_STATS_DETAILED
5298     TM_GetTimeOfDay(&opStopTime, 0);
5299     if (code == 0) {
5300       FS_LOCK
5301       (opP->numSuccesses)++;
5302       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5303       fs_stats_AddTo((opP->sumTime), elapsedTime);
5304       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5305       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5306         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5307       }
5308       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5309         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5310       }
5311       FS_UNLOCK
5312     }
5313
5314 #endif /* FS_STATS_DETAILED */
5315
5316     osi_auditU (acall, ReleaseLockEvent, code, AUD_FID, Fid , AUD_END);
5317     return code;
5318
5319 } /*SRXAFS_ReleaseLock*/
5320
5321
5322 void SetSystemStats(struct AFSStatistics *stats)
5323 {
5324   /* Fix this sometime soon.. */
5325   /* Because hey, it's not like we have a network monitoring protocol... */
5326     struct      timeval time;
5327
5328     /* this works on all system types */
5329     TM_GetTimeOfDay(&time, 0);
5330     stats->CurrentTime = time.tv_sec;
5331 } /*SetSystemStats*/
5332
5333 void SetAFSStats(struct AFSStatistics *stats)
5334 {
5335     extern afs_int32 StartTime, CurrentConnections;
5336     int seconds;
5337
5338     FS_LOCK
5339     stats->CurrentMsgNumber = 0;
5340     stats->OldestMsgNumber = 0;
5341     stats->StartTime = StartTime;
5342     stats->CurrentConnections = CurrentConnections;
5343     stats->TotalAFSCalls = AFSCallStats.TotalCalls;
5344     stats->TotalFetchs = AFSCallStats.FetchData+AFSCallStats.FetchACL+AFSCallStats.FetchStatus;
5345     stats->FetchDatas = AFSCallStats.FetchData;
5346     stats->FetchedBytes = AFSCallStats.TotalFetchedBytes;
5347     seconds = AFSCallStats.AccumFetchTime/1000;
5348     if (seconds <= 0) seconds = 1;
5349     stats->FetchDataRate = AFSCallStats.TotalFetchedBytes/seconds;
5350     stats->TotalStores = AFSCallStats.StoreData+AFSCallStats.StoreACL+AFSCallStats.StoreStatus;
5351     stats->StoreDatas = AFSCallStats.StoreData;
5352     stats->StoredBytes = AFSCallStats.TotalStoredBytes;
5353     seconds = AFSCallStats.AccumStoreTime/1000;
5354     if (seconds <= 0) seconds = 1;
5355     stats->StoreDataRate = AFSCallStats.TotalStoredBytes/seconds;
5356 #ifdef AFS_NT40_ENV
5357     stats->ProcessSize = -1; /* TODO: */
5358 #else
5359     stats->ProcessSize = (afs_int32)((long) sbrk(0) >> 10);
5360 #endif
5361     FS_UNLOCK
5362     h_GetWorkStats((int *)&(stats->WorkStations),(int *)&(stats->ActiveWorkStations),
5363             (int *)0, (afs_int32)(FT_ApproxTime())-(15*60));
5364
5365 } /*SetAFSStats*/
5366
5367 /* Get disk related information from all AFS partitions. */
5368
5369 void SetVolumeStats(struct AFSStatistics *stats)
5370 {
5371     struct DiskPartition * part;
5372     int i = 0;
5373
5374     for (part = DiskPartitionList; part && i < AFS_MSTATDISKS; part = part->next) {
5375         stats->Disks[i].TotalBlocks = part->totalUsable;
5376         stats->Disks[i].BlocksAvailable = part->free;
5377         memset(stats->Disks[i].Name, 0, AFS_DISKNAMESIZE);
5378         strncpy(stats->Disks[i].Name, part->name, AFS_DISKNAMESIZE);
5379         i++;
5380     }
5381     while (i < AFS_MSTATDISKS) {
5382         stats->Disks[i].TotalBlocks = -1;
5383         i++;
5384     }
5385 } /*SetVolumeStats*/
5386
5387 afs_int32 SRXAFS_GetStatistics (struct rx_call *acall,
5388                                 struct ViceStatistics *Statistics)
5389 {
5390     afs_int32 code;
5391     struct rx_connection *tcon;
5392 #if FS_STATS_DETAILED
5393     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5394     struct timeval opStartTime,
5395                    opStopTime;              /* Start/stop times for RPC op*/
5396     struct timeval elapsedTime;             /* Transfer time */
5397
5398     /*
5399      * Set our stats pointer, remember when the RPC operation started, and
5400      * tally the operation.
5401      */
5402     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5403     FS_LOCK
5404     (opP->numOps)++;
5405     FS_UNLOCK
5406     TM_GetTimeOfDay(&opStartTime, 0);
5407 #endif /* FS_STATS_DETAILED */
5408
5409     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon)))
5410         goto Bad_GetStatistics;
5411
5412     ViceLog(1, ("SAFS_GetStatistics Received\n"));
5413     FS_LOCK
5414     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5415     FS_UNLOCK
5416     memset(Statistics, 0, sizeof(*Statistics));
5417     SetAFSStats((struct AFSStatistics *)Statistics);
5418     SetVolumeStats((struct AFSStatistics *)Statistics);
5419     SetSystemStats((struct AFSStatistics *)Statistics);
5420     
5421 Bad_GetStatistics:
5422     code = CallPostamble(tcon, code);
5423
5424 #if FS_STATS_DETAILED
5425     TM_GetTimeOfDay(&opStopTime, 0);
5426     if (code == 0) {
5427       FS_LOCK
5428       (opP->numSuccesses)++;
5429       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5430       fs_stats_AddTo((opP->sumTime), elapsedTime);
5431       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5432       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5433         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5434       }
5435       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5436         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5437       }
5438       FS_UNLOCK
5439     }
5440 #endif /* FS_STATS_DETAILED */
5441
5442     return code;
5443
5444 } /*SRXAFS_GetStatistics*/
5445
5446
5447 /*------------------------------------------------------------------------
5448  * EXPORTED SRXAFS_XStatsVersion
5449  *
5450  * Description:
5451  *      Routine called by the server-side RPC interface to implement
5452  *      pulling out the xstat version number for the File Server.
5453  *
5454  * Arguments:
5455  *      a_versionP : Ptr to the version number variable to set.
5456  *
5457  * Returns:
5458  *      0 (always)
5459  *
5460  * Environment:
5461  *      Nothing interesting.
5462  *
5463  * Side Effects:
5464  *      As advertised.
5465  *------------------------------------------------------------------------*/
5466
5467 afs_int32 SRXAFS_XStatsVersion(struct rx_call *a_call, afs_int32 *a_versionP)
5468 { /*SRXAFS_XStatsVersion*/
5469
5470 #if FS_STATS_DETAILED
5471     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5472     struct timeval opStartTime,
5473                    opStopTime;              /* Start/stop times for RPC op*/
5474     struct timeval elapsedTime;             /* Transfer time */
5475
5476     /*
5477      * Set our stats pointer, remember when the RPC operation started, and
5478      * tally the operation.
5479      */
5480     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_XSTATSVERSION]);
5481     FS_LOCK
5482     (opP->numOps)++;
5483     FS_UNLOCK
5484     TM_GetTimeOfDay(&opStartTime, 0);
5485 #endif /* FS_STATS_DETAILED */
5486
5487     *a_versionP = AFS_XSTAT_VERSION;
5488
5489 #if FS_STATS_DETAILED
5490     TM_GetTimeOfDay(&opStopTime, 0);
5491     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5492     fs_stats_AddTo((opP->sumTime), elapsedTime);
5493     fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5494     if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5495         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5496     }
5497     if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5498         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5499     }
5500     FS_LOCK
5501     (opP->numSuccesses)++;
5502     FS_UNLOCK
5503 #endif /* FS_STATS_DETAILED */
5504
5505     return(0);
5506
5507 }  /*SRXAFS_XStatsVersion*/
5508
5509
5510 /*------------------------------------------------------------------------
5511  * PRIVATE FillPerfValues
5512  *
5513  * Description:
5514  *      Routine called to fill a regular performance data structure.
5515  *
5516  * Arguments:
5517  *      a_perfP : Ptr to perf structure to fill
5518  *
5519  * Returns:
5520  *      Nothing.
5521  *
5522  * Environment:
5523  *      Various collections need this info, so the guts were put in
5524  *      this separate routine.
5525  *
5526  * Side Effects:
5527  *      As advertised.
5528  *------------------------------------------------------------------------*/
5529
5530 static void FillPerfValues(struct afs_PerfStats *a_perfP)
5531 { /*FillPerfValues*/
5532
5533     int dir_Buffers;            /*# buffers in use by dir package*/
5534     int dir_Calls;              /*# read calls in dir package*/
5535     int dir_IOs;                /*# I/O ops in dir package*/
5536
5537     /*
5538      * Vnode cache section.
5539      */
5540     a_perfP->vcache_L_Entries = VnodeClassInfo[vLarge].cacheSize;
5541     a_perfP->vcache_L_Allocs = VnodeClassInfo[vLarge].allocs;
5542     a_perfP->vcache_L_Gets = VnodeClassInfo[vLarge].gets;
5543     a_perfP->vcache_L_Reads = VnodeClassInfo[vLarge].reads;
5544     a_perfP->vcache_L_Writes = VnodeClassInfo[vLarge].writes;
5545     a_perfP->vcache_S_Entries = VnodeClassInfo[vSmall].cacheSize;
5546     a_perfP->vcache_S_Allocs = VnodeClassInfo[vSmall].allocs;
5547     a_perfP->vcache_S_Gets = VnodeClassInfo[vSmall].gets;
5548     a_perfP->vcache_S_Reads = VnodeClassInfo[vSmall].reads;
5549     a_perfP->vcache_S_Writes = VnodeClassInfo[vSmall].writes;
5550     a_perfP->vcache_H_Entries = VolumeCacheSize;
5551     a_perfP->vcache_H_Gets = VolumeGets;
5552     a_perfP->vcache_H_Replacements = VolumeReplacements;
5553     
5554     /*
5555      * Directory section.
5556      */
5557     DStat(&dir_Buffers, &dir_Calls, &dir_IOs);
5558     a_perfP->dir_Buffers = (afs_int32) dir_Buffers;
5559     a_perfP->dir_Calls = (afs_int32 )dir_Calls;
5560     a_perfP->dir_IOs = (afs_int32) dir_IOs;
5561     
5562     /*
5563      * Rx section.
5564      */
5565     a_perfP->rx_packetRequests =
5566         (afs_int32) rx_stats.packetRequests;
5567     a_perfP->rx_noPackets_RcvClass =
5568         (afs_int32) rx_stats.receivePktAllocFailures;
5569     a_perfP->rx_noPackets_SendClass =
5570         (afs_int32) rx_stats.sendPktAllocFailures;
5571     a_perfP->rx_noPackets_SpecialClass =
5572         (afs_int32) rx_stats.specialPktAllocFailures;
5573     a_perfP->rx_socketGreedy =
5574         (afs_int32) rx_stats.socketGreedy;
5575     a_perfP->rx_bogusPacketOnRead =
5576         (afs_int32) rx_stats.bogusPacketOnRead;
5577     a_perfP->rx_bogusHost =
5578         (afs_int32) rx_stats.bogusHost;
5579     a_perfP->rx_noPacketOnRead =
5580         (afs_int32) rx_stats.noPacketOnRead;
5581     a_perfP->rx_noPacketBuffersOnRead =
5582         (afs_int32) rx_stats.noPacketBuffersOnRead;
5583     a_perfP->rx_selects =
5584         (afs_int32) rx_stats.selects;
5585     a_perfP->rx_sendSelects =
5586         (afs_int32) rx_stats.sendSelects;
5587     a_perfP->rx_packetsRead_RcvClass =
5588         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_RECEIVE];
5589     a_perfP->rx_packetsRead_SendClass =
5590         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SEND];
5591     a_perfP->rx_packetsRead_SpecialClass =
5592         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SPECIAL];
5593     a_perfP->rx_dataPacketsRead =
5594         (afs_int32) rx_stats.dataPacketsRead;
5595     a_perfP->rx_ackPacketsRead =
5596         (afs_int32) rx_stats.ackPacketsRead;
5597     a_perfP->rx_dupPacketsRead =
5598         (afs_int32) rx_stats.dupPacketsRead;
5599     a_perfP->rx_spuriousPacketsRead =
5600         (afs_int32) rx_stats.spuriousPacketsRead;
5601     a_perfP->rx_packetsSent_RcvClass =
5602         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_RECEIVE];
5603     a_perfP->rx_packetsSent_SendClass =
5604         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SEND];
5605     a_perfP->rx_packetsSent_SpecialClass =
5606         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SPECIAL];
5607     a_perfP->rx_ackPacketsSent =
5608         (afs_int32) rx_stats.ackPacketsSent;
5609     a_perfP->rx_pingPacketsSent =
5610         (afs_int32) rx_stats.pingPacketsSent;
5611     a_perfP->rx_abortPacketsSent =
5612         (afs_int32) rx_stats.abortPacketsSent;
5613     a_perfP->rx_busyPacketsSent =
5614         (afs_int32) rx_stats.busyPacketsSent;
5615     a_perfP->rx_dataPacketsSent =
5616         (afs_int32) rx_stats.dataPacketsSent;
5617     a_perfP->rx_dataPacketsReSent =
5618         (afs_int32) rx_stats.dataPacketsReSent;
5619     a_perfP->rx_dataPacketsPushed =
5620         (afs_int32) rx_stats.dataPacketsPushed;
5621     a_perfP->rx_ignoreAckedPacket =
5622         (afs_int32) rx_stats.ignoreAckedPacket;
5623     a_perfP->rx_totalRtt_Sec =
5624         (afs_int32) rx_stats.totalRtt.sec;
5625     a_perfP->rx_totalRtt_Usec =
5626         (afs_int32) rx_stats.totalRtt.usec;
5627     a_perfP->rx_minRtt_Sec =
5628         (afs_int32) rx_stats.minRtt.sec;
5629     a_perfP->rx_minRtt_Usec =
5630         (afs_int32) rx_stats.minRtt.usec;
5631     a_perfP->rx_maxRtt_Sec =
5632         (afs_int32) rx_stats.maxRtt.sec;
5633     a_perfP->rx_maxRtt_Usec =
5634         (afs_int32) rx_stats.maxRtt.usec;
5635     a_perfP->rx_nRttSamples =
5636         (afs_int32) rx_stats.nRttSamples;
5637     a_perfP->rx_nServerConns =
5638         (afs_int32) rx_stats.nServerConns;
5639     a_perfP->rx_nClientConns =
5640         (afs_int32) rx_stats.nClientConns;
5641     a_perfP->rx_nPeerStructs =
5642         (afs_int32) rx_stats.nPeerStructs;
5643     a_perfP->rx_nCallStructs =
5644         (afs_int32) rx_stats.nCallStructs;
5645     a_perfP->rx_nFreeCallStructs =
5646         (afs_int32) rx_stats.nFreeCallStructs;
5647     
5648     a_perfP->host_NumHostEntries = HTs;
5649     a_perfP->host_HostBlocks = HTBlocks;
5650     h_GetHostNetStats(&(a_perfP->host_NonDeletedHosts),
5651                       &(a_perfP->host_HostsInSameNetOrSubnet),
5652                       &(a_perfP->host_HostsInDiffSubnet),
5653                       &(a_perfP->host_HostsInDiffNetwork));
5654     a_perfP->host_NumClients = CEs;
5655     a_perfP->host_ClientBlocks = CEBlocks;
5656     
5657     a_perfP->sysname_ID = afs_perfstats.sysname_ID;
5658
5659 } /*FillPerfValues*/
5660
5661
5662 /*------------------------------------------------------------------------
5663  * EXPORTED SRXAFS_GetXStats
5664  *
5665  * Description:
5666  *      Routine called by the server-side callback RPC interface to
5667  *      implement getting the given data collection from the extended
5668  *      File Server statistics.
5669  *
5670  * Arguments:
5671  *      a_call              : Ptr to Rx call on which this request came in.
5672  *      a_clientVersionNum  : Client version number.
5673  *      a_opCode            : Desired operation.
5674  *      a_serverVersionNumP : Ptr to version number to set.
5675  *      a_timeP             : Ptr to time value (seconds) to set.
5676  *      a_dataP             : Ptr to variable array structure to return
5677  *                            stuff in.
5678  *
5679  * Returns:
5680  *      0 (always).
5681  *
5682  * Environment:
5683  *      Nothing interesting.
5684  *
5685  * Side Effects:
5686  *      As advertised.
5687  *------------------------------------------------------------------------*/
5688
5689 afs_int32 SRXAFS_GetXStats(struct rx_call *a_call,
5690                            afs_int32 a_clientVersionNum,
5691                            afs_int32 a_collectionNumber,
5692                            afs_int32 *a_srvVersionNumP,
5693                            afs_int32 *a_timeP,
5694                            AFS_CollData *a_dataP)
5695 { /*SRXAFS_GetXStats*/
5696
5697     register int code;          /*Return value*/
5698     afs_int32 *dataBuffP;               /*Ptr to data to be returned*/
5699     afs_int32 dataBytes;                /*Bytes in data buffer*/
5700 #if FS_STATS_DETAILED
5701     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5702     struct timeval opStartTime,
5703                    opStopTime;              /* Start/stop times for RPC op*/
5704     struct timeval elapsedTime;             /* Transfer time */
5705
5706     /*
5707      * Set our stats pointer, remember when the RPC operation started, and
5708      * tally the operation.
5709      */
5710     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETXSTATS]);
5711     FS_LOCK
5712     (opP->numOps)++;
5713     FS_UNLOCK
5714     TM_GetTimeOfDay(&opStartTime, 0);
5715 #endif /* FS_STATS_DETAILED */
5716
5717     /*
5718      * Record the time of day and the server version number.
5719      */
5720     *a_srvVersionNumP = AFS_XSTAT_VERSION;
5721     *a_timeP = FT_ApproxTime();
5722
5723     /*
5724      * Stuff the appropriate data in there (assume victory)
5725      */
5726     code = 0;
5727
5728     ViceLog(1, ("Received GetXStats call for collection %d\n",  a_collectionNumber));
5729
5730 #if 0
5731     /*
5732      * We're not keeping stats, so just return successfully with
5733      * no data.
5734      */
5735     a_dataP->AFS_CollData_len = 0;
5736     a_dataP->AFS_CollData_val = NULL;
5737 #endif /* 0 */
5738
5739     switch(a_collectionNumber) {
5740       case AFS_XSTATSCOLL_CALL_INFO:
5741         /*
5742          * Pass back all the call-count-related data.
5743          *
5744          * >>> We are forced to allocate a separate area in which to
5745          * >>> put this stuff in by the RPC stub generator, since it
5746          * >>> will be freed at the tail end of the server stub code.
5747          */
5748 #if 0
5749         /*
5750          * I don't think call-level stats are being collected yet
5751          * for the File Server.
5752          */
5753         dataBytes = sizeof(struct afs_Stats);
5754         dataBuffP = (afs_int32 *)malloc(dataBytes);
5755         memcpy(dataBuffP, &afs_cmstats, dataBytes);
5756         a_dataP->AFS_CollData_len = dataBytes>>2;
5757         a_dataP->AFS_CollData_val = dataBuffP;
5758 #else
5759         a_dataP->AFS_CollData_len = 0;
5760         a_dataP->AFS_CollData_val = NULL;
5761 #endif /* 0 */
5762         break;
5763
5764       case AFS_XSTATSCOLL_PERF_INFO:
5765         /*
5766          * Pass back all the regular performance-related data.
5767          *
5768          * >>> We are forced to allocate a separate area in which to
5769          * >>> put this stuff in by the RPC stub generator, since it
5770          * >>> will be freed at the tail end of the server stub code.
5771          */
5772
5773         afs_perfstats.numPerfCalls++;
5774         FillPerfValues(&afs_perfstats);
5775
5776         /*
5777          * Don't overwrite the spares at the end.
5778          */
5779
5780         dataBytes = sizeof(struct afs_PerfStats);
5781         dataBuffP = (afs_int32 *)malloc(dataBytes);
5782         memcpy(dataBuffP, &afs_perfstats, dataBytes);
5783         a_dataP->AFS_CollData_len = dataBytes>>2;
5784         a_dataP->AFS_CollData_val = dataBuffP;
5785         break;
5786
5787       case AFS_XSTATSCOLL_FULL_PERF_INFO:
5788         /*
5789          * Pass back the full collection of performance-related data.
5790          * We have to stuff the basic, overall numbers in, but the
5791          * detailed numbers are kept in the structure already.
5792          *
5793          * >>> We are forced to allocate a separate area in which to
5794          * >>> put this stuff in by the RPC stub generator, since it
5795          * >>> will be freed at the tail end of the server stub code.
5796          */
5797
5798         afs_perfstats.numPerfCalls++;
5799 #if FS_STATS_DETAILED
5800         afs_FullPerfStats.overall.numPerfCalls = afs_perfstats.numPerfCalls;
5801         FillPerfValues(&afs_FullPerfStats.overall);
5802
5803         /*
5804          * Don't overwrite the spares at the end.
5805          */
5806
5807         dataBytes = sizeof(struct fs_stats_FullPerfStats);
5808         dataBuffP = (afs_int32 *)malloc(dataBytes);
5809         memcpy(dataBuffP, &afs_FullPerfStats, dataBytes);
5810         a_dataP->AFS_CollData_len = dataBytes>>2;
5811         a_dataP->AFS_CollData_val = dataBuffP;
5812 #endif
5813         break;
5814
5815       default:
5816         /*
5817          * Illegal collection number.
5818          */
5819         a_dataP->AFS_CollData_len = 0;
5820         a_dataP->AFS_CollData_val = NULL;
5821         code = 1;
5822     } /*Switch on collection number*/
5823
5824 #if FS_STATS_DETAILED
5825     TM_GetTimeOfDay(&opStopTime, 0);
5826     if (code == 0) {
5827       FS_LOCK
5828       (opP->numSuccesses)++;
5829       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5830       fs_stats_AddTo((opP->sumTime), elapsedTime);
5831       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5832       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5833         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5834       }
5835       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5836         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5837       }
5838       FS_UNLOCK
5839     }
5840
5841 #endif /* FS_STATS_DETAILED */
5842
5843     return(code);
5844
5845 } /*SRXAFS_GetXStats*/
5846
5847
5848 static afs_int32 common_GiveUpCallBacks (struct rx_call *acall,
5849                                          struct AFSCBFids *FidArray,
5850                                          struct AFSCBs *CallBackArray)
5851 {
5852     afs_int32 errorCode = 0;
5853     register int i;
5854     struct client *client;
5855     struct rx_connection *tcon;
5856 #if FS_STATS_DETAILED
5857     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
5858     struct timeval opStartTime,
5859                    opStopTime;              /* Start/stop times for RPC op*/
5860     struct timeval elapsedTime;             /* Transfer time */
5861
5862     /*
5863      * Set our stats pointer, remember when the RPC operation started, and
5864      * tally the operation.
5865      */
5866     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GIVEUPCALLBACKS]);
5867     FS_LOCK
5868     (opP->numOps)++;
5869     FS_UNLOCK
5870     TM_GetTimeOfDay(&opStartTime, 0);
5871 #endif /* FS_STATS_DETAILED */
5872
5873     if (FidArray)
5874         ViceLog(1, ("SAFS_GiveUpCallBacks (Noffids=%d)\n", FidArray->AFSCBFids_len));
5875
5876     FS_LOCK
5877     AFSCallStats.GiveUpCallBacks++, AFSCallStats.TotalCalls++;
5878     FS_UNLOCK
5879     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
5880         goto Bad_GiveUpCallBacks;
5881
5882     if (!FidArray && !CallBackArray) {
5883         ViceLog(1, ("SAFS_GiveUpAllCallBacks: host=%x\n", 
5884                 (tcon->peer ? tcon->peer->host : 0)));
5885         errorCode = GetClient(tcon, &client);
5886         if (!errorCode) 
5887             DeleteAllCallBacks_r(client->host, 1);
5888     } else {
5889         if (FidArray->AFSCBFids_len < CallBackArray->AFSCBs_len) {
5890             ViceLog(0, ("GiveUpCallBacks: #Fids %d < #CallBacks %d, host=%x\n", 
5891                         FidArray->AFSCBFids_len, CallBackArray->AFSCBs_len, 
5892                         (tcon->peer ? tcon->peer->host : 0)));
5893             errorCode = EINVAL;
5894             goto Bad_GiveUpCallBacks;
5895         }
5896
5897         errorCode = GetClient(tcon, &client);
5898         if (!errorCode) {
5899             for (i=0; i < FidArray->AFSCBFids_len; i++) {
5900                 register struct AFSFid *fid = &(FidArray->AFSCBFids_val[i]);
5901                 DeleteCallBack(client->host, fid);
5902             }
5903         }
5904     }
5905
5906 Bad_GiveUpCallBacks:
5907     errorCode = CallPostamble(tcon, errorCode);
5908
5909 #if FS_STATS_DETAILED
5910     TM_GetTimeOfDay(&opStopTime, 0);
5911     if (errorCode == 0) {
5912       FS_LOCK
5913       (opP->numSuccesses)++;
5914       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5915       fs_stats_AddTo((opP->sumTime), elapsedTime);
5916       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5917       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5918         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5919       }
5920       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5921         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5922       }
5923       FS_UNLOCK
5924     }
5925 #endif /* FS_STATS_DETAILED */
5926 out:
5927     return errorCode;
5928
5929 } /*common_GiveUpCallBacks*/
5930
5931
5932 afs_int32 SRXAFS_GiveUpCallBacks (struct rx_call *acall,
5933                                   struct AFSCBFids *FidArray,
5934                                   struct AFSCBs *CallBackArray)
5935 {
5936     return common_GiveUpCallBacks(acall, FidArray, CallBackArray);
5937 } /*SRXAFS_GiveUpCallBacks*/
5938
5939 afs_int32 SRXAFS_GiveUpAllCallBacks (struct rx_call *acall)
5940 {
5941     return common_GiveUpCallBacks(acall, 0, 0);
5942 } /*SRXAFS_GiveUpAllCallBacks*/
5943
5944
5945 afs_int32 SRXAFS_NGetVolumeInfo (struct rx_call *acall,
5946                                  char *avolid,
5947                                  struct AFSVolumeInfo *avolinfo)
5948 {
5949     return(VNOVOL);             /* XXX Obsolete routine XXX */
5950
5951 } /*SRXAFS_NGetVolumeInfo*/
5952
5953
5954 /*
5955  * Dummy routine. Should never be called (the cache manager should only 
5956  * invoke this interface when communicating with a AFS/DFS Protocol
5957  * Translator).
5958  */
5959 afs_int32 SRXAFS_Lookup(struct rx_call *call_p,
5960                         struct AFSFid *afs_dfid_p,
5961                         char *afs_name_p,
5962                         struct AFSFid *afs_fid_p,
5963                         struct AFSFetchStatus *afs_status_p,
5964                         struct AFSFetchStatus *afs_dir_status_p,
5965                         struct AFSCallBack *afs_callback_p,
5966                         struct AFSVolSync *afs_sync_p)
5967 {
5968     return EINVAL;
5969 }
5970
5971
5972 afs_int32 SRXAFS_GetCapabilities(struct rx_call *acall,
5973                                  Capabilities *capabilities)
5974 {
5975     afs_int32 *dataBuffP;               
5976     afs_int32 *dataP;
5977     afs_int32 dataBytes;   
5978
5979     dataBytes = 1 * sizeof(afs_int32);
5980     dataBuffP = (afs_int32 *)malloc(dataBytes);
5981     dataBuffP[0] = CAPABILITY_ERRORTRANS;
5982     capabilities->Capabilities_len = dataBytes/sizeof(afs_int32);
5983     capabilities->Capabilities_val = dataBuffP;
5984
5985     return 0;
5986
5987
5988 afs_int32 SRXAFS_FlushCPS(struct rx_call *acall,
5989                           struct ViceIds *vids,
5990                           struct IPAddrs *addrs,
5991                           afs_int32 spare1,
5992                           afs_int32 *spare2, 
5993                           afs_int32 *spare3)
5994 {
5995     int i;
5996     afs_int32 nids, naddrs;
5997     afs_int32 *vd, *addr;
5998     int     errorCode = 0;              /* return code to caller */
5999     struct client *client;
6000     struct rx_connection *tcon = rx_ConnectionOf(acall);
6001
6002     ViceLog(1, ("SRXAFS_FlushCPS\n"));
6003     FS_LOCK
6004     AFSCallStats.TotalCalls++;
6005     FS_UNLOCK
6006     nids = vids->ViceIds_len;   /* # of users in here */
6007     naddrs = addrs->IPAddrs_len;        /* # of hosts in here */
6008     if (nids < 0 || naddrs < 0) {
6009         errorCode = EINVAL;
6010         goto Bad_FlushCPS;
6011     }
6012
6013     vd = vids->ViceIds_val;
6014     for (i=0; i<nids; i++, vd++) {
6015       if (!*vd)
6016         continue;
6017       client = h_ID2Client(*vd);  /* returns client locked, or NULL */
6018       if (!client)
6019         continue;
6020
6021       BoostSharedLock(&client->lock);
6022       client->prfail = 2;       /* Means re-eval client's cps */
6023 #ifdef  notdef
6024       if (client->tcon) {
6025         rx_SetRock(((struct rx_connection *) client->tcon), 0);
6026       }
6027 #endif
6028       if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
6029         free(client->CPS.prlist_val);
6030         client->CPS.prlist_val = NULL;
6031         client->CPS.prlist_len = 0;
6032       }
6033       ReleaseWriteLock(&client->lock);
6034     }
6035
6036     addr = addrs->IPAddrs_val;
6037     for (i=0; i<naddrs; i++, addr++) {
6038       if (*addr)
6039         h_flushhostcps(*addr, htons(7001));
6040     }
6041
6042 Bad_FlushCPS:
6043     ViceLog(2, ("SAFS_FlushCPS  returns %d\n", errorCode)); 
6044     return errorCode;
6045 } /*SRXAFS_FlushCPS */
6046
6047 /* worthless hack to let CS keep running ancient software */
6048 static int afs_vtoi(register char *aname)
6049 {
6050     register afs_int32 temp;
6051     register int tc;
6052
6053     temp = 0;
6054     while((tc = *aname++)) {
6055         if (tc > '9' || tc < '0') return 0; /* invalid name */
6056         temp *= 10;
6057         temp += tc - '0';
6058     }
6059     return temp;
6060 }
6061
6062 /*
6063  * may get name or #, but must handle all weird cases (recognize readonly
6064  * or backup volumes by name or #
6065  */
6066 static afs_int32 CopyVolumeEntry(char *aname,register struct vldbentry *ave,
6067                                  register struct VolumeInfo *av)
6068 {
6069     register int i, j, vol;
6070     afs_int32 mask, whichType;
6071     afs_uint32 *serverHost, *typePtr;
6072     
6073     /* figure out what type we want if by name */
6074     i = strlen(aname);
6075     if (i >= 8 && strcmp(aname+i-7, ".backup") == 0)
6076         whichType = BACKVOL;
6077     else if (i >= 10 && strcmp(aname+i-9, ".readonly")==0)
6078         whichType = ROVOL;
6079     else whichType = RWVOL;
6080     
6081     vol = afs_vtoi(aname);
6082     if (vol == 0) vol = ave->volumeId[whichType];
6083     
6084     /*
6085      * Now vol has volume # we're interested in.  Next, figure out the type
6086      * of the volume by looking finding it in the vldb entry
6087      */
6088     if ((ave->flags&VLF_RWEXISTS) && vol == ave->volumeId[RWVOL]) {
6089         mask = VLSF_RWVOL;
6090         whichType = RWVOL;
6091     }
6092     else if ((ave->flags&VLF_ROEXISTS) && vol == ave->volumeId[ROVOL]) {
6093         mask = VLSF_ROVOL;
6094         whichType = ROVOL;
6095     }
6096     else if ((ave->flags&VLF_BACKEXISTS) && vol == ave->volumeId[BACKVOL]) {
6097         mask = VLSF_RWVOL;  /* backup always is on the same volume as parent */
6098         whichType = BACKVOL;
6099     }
6100     else
6101         return  EINVAL;     /* error: can't find volume in vldb entry */
6102     
6103     typePtr = &av->Type0;
6104     serverHost = &av->Server0;
6105     av->Vid = vol;
6106     av->Type = whichType;
6107     av->Type0 = av->Type1 = av->Type2 = av->Type3 = av->Type4 = 0;
6108     if (ave->flags & VLF_RWEXISTS) typePtr[RWVOL] = ave->volumeId[RWVOL];
6109     if (ave->flags & VLF_ROEXISTS) typePtr[ROVOL] = ave->volumeId[ROVOL];
6110     if (ave->flags & VLF_BACKEXISTS) typePtr[BACKVOL] = ave->volumeId[BACKVOL];
6111
6112     for(i=0,j=0; i<ave->nServers; i++) {
6113         if ((ave->serverFlags[i] & mask) == 0) continue;    /* wrong volume */
6114         serverHost[j] = ave->serverNumber[i];
6115         j++;
6116     }
6117     av->ServerCount = j;
6118     if (j < 8) serverHost[j++] = 0; /* bogus 8, but compat only now */
6119     return 0;
6120 }
6121
6122 static afs_int32 TryLocalVLServer(char *avolid, struct VolumeInfo *avolinfo)
6123 {
6124     static struct rx_connection *vlConn = 0;
6125     static int down = 0;
6126     static afs_int32 lastDownTime = 0;
6127     struct vldbentry tve;
6128     struct rx_securityClass *vlSec;
6129     register afs_int32 code;
6130
6131     if (!vlConn) {
6132         vlSec = rxnull_NewClientSecurityObject();
6133         vlConn = rx_NewConnection(htonl(0x7f000001), htons(7003), 52, vlSec, 0);
6134         rx_SetConnDeadTime(vlConn, 15); /* don't wait long */
6135     }
6136     if (down && (FT_ApproxTime() < lastDownTime + 180)) {
6137         return 1;   /* failure */
6138     }
6139
6140     code = VL_GetEntryByNameO(vlConn, avolid, &tve);
6141     if (code >= 0) down = 0;    /* call worked */
6142     if (code) {
6143         if (code < 0) {
6144             lastDownTime = FT_ApproxTime(); /* last time we tried an RPC */
6145             down = 1;
6146         }
6147         return code;
6148     }
6149
6150     /* otherwise convert to old format vldb entry */
6151     code = CopyVolumeEntry(avolid, &tve, avolinfo);
6152     return code;
6153 }
6154
6155
6156
6157
6158
6159
6160 afs_int32 SRXAFS_GetVolumeInfo (struct rx_call *acall,
6161                                 char *avolid,
6162                                 struct VolumeInfo *avolinfo)
6163 {
6164     afs_int32 code;
6165     struct rx_connection *tcon;
6166 #if FS_STATS_DETAILED
6167     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
6168     struct timeval opStartTime,
6169                    opStopTime;              /* Start/stop times for RPC op*/
6170     struct timeval elapsedTime;             /* Transfer time */
6171
6172     /*
6173      * Set our stats pointer, remember when the RPC operation started, and
6174      * tally the operation.
6175      */
6176     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMEINFO]);
6177     FS_LOCK
6178     (opP->numOps)++;
6179     FS_UNLOCK
6180     TM_GetTimeOfDay(&opStartTime, 0);
6181 #endif /* FS_STATS_DETAILED */
6182     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
6183         goto Bad_GetVolumeInfo;
6184
6185     FS_LOCK
6186     AFSCallStats.GetVolumeInfo++, AFSCallStats.TotalCalls++;
6187     FS_UNLOCK
6188
6189     code = TryLocalVLServer(avolid, avolinfo);
6190     ViceLog(1, ("SAFS_GetVolumeInfo returns %d, Volume %u, type %x, servers %x %x %x %x...\n",
6191                 code, avolinfo->Vid, avolinfo->Type,
6192                 avolinfo->Server0, avolinfo->Server1, avolinfo->Server2,
6193                 avolinfo->Server3));
6194     avolinfo->Type4     = 0xabcd9999;   /* tell us to try new vldb */
6195
6196 Bad_GetVolumeInfo:
6197     code = CallPostamble(tcon, code);
6198
6199 #if FS_STATS_DETAILED
6200     TM_GetTimeOfDay(&opStopTime, 0);
6201     if (code == 0) {
6202       FS_LOCK
6203       (opP->numSuccesses)++;
6204       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6205       fs_stats_AddTo((opP->sumTime), elapsedTime);
6206       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6207       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6208         fs_stats_TimeAssign((opP->minTime), elapsedTime);
6209       }
6210       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6211         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6212       }
6213       FS_UNLOCK
6214     }
6215
6216 #endif /* FS_STATS_DETAILED */
6217
6218     return code;
6219
6220 } /*SRXAFS_GetVolumeInfo*/
6221
6222
6223 afs_int32 SRXAFS_GetVolumeStatus(struct rx_call *acall,
6224                                  afs_int32 avolid,
6225                                  AFSFetchVolumeStatus *FetchVolStatus,
6226                                  char **Name,
6227                                  char **OfflineMsg,
6228                                  char **Motd)
6229 {
6230     Vnode * targetptr = 0;              /* vnode of the new file */
6231     Vnode * parentwhentargetnotdir = 0; /* vnode of parent */
6232     int     errorCode = 0;              /* error code */
6233     Volume * volptr = 0;                /* pointer to the volume header */
6234     struct client * client;             /* pointer to client entry */
6235     afs_int32 rights, anyrights;                /* rights for this and any user */
6236     AFSFid  dummyFid;
6237     struct rx_connection *tcon;
6238 #if FS_STATS_DETAILED
6239     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
6240     struct timeval opStartTime,
6241                    opStopTime;              /* Start/stop times for RPC op*/
6242     struct timeval elapsedTime;             /* Transfer time */
6243
6244     /*
6245      * Set our stats pointer, remember when the RPC operation started, and
6246      * tally the operation.
6247      */
6248     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMESTATUS]);
6249     FS_LOCK
6250     (opP->numOps)++;
6251     FS_UNLOCK
6252     TM_GetTimeOfDay(&opStartTime, 0);
6253 #endif /* FS_STATS_DETAILED */
6254
6255     ViceLog(1,("SAFS_GetVolumeStatus for volume %u\n", avolid));
6256     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
6257         goto Bad_GetVolumeStatus;
6258
6259     FS_LOCK
6260     AFSCallStats.GetVolumeStatus++, AFSCallStats.TotalCalls++;
6261     FS_UNLOCK
6262
6263     if (avolid == 0) {
6264         errorCode = EINVAL;
6265         goto Bad_GetVolumeStatus;
6266     }
6267     dummyFid.Volume = avolid, dummyFid.Vnode = (afs_int32)ROOTVNODE, dummyFid.Unique = 1;
6268
6269     if ((errorCode = GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr,
6270                                      MustBeDIR, &parentwhentargetnotdir,
6271                                      &client, READ_LOCK, &rights, &anyrights)))
6272         goto Bad_GetVolumeStatus;
6273
6274     if ((VanillaUser(client)) && (!(rights & PRSFS_READ))) {
6275         errorCode = EACCES;
6276         goto Bad_GetVolumeStatus;
6277     }
6278     (void) RXGetVolumeStatus(FetchVolStatus, Name, OfflineMsg, Motd,
6279                              volptr);
6280
6281 Bad_GetVolumeStatus:
6282     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
6283                             volptr);
6284     ViceLog(2,("SAFS_GetVolumeStatus returns %d\n",errorCode));
6285     /* next is to guarantee out strings exist for stub */
6286     if (*Name == 0) {*Name = (char *) malloc(1); **Name = 0;}
6287     if (*Motd == 0) {*Motd = (char *) malloc(1); **Motd = 0;}
6288     if (*OfflineMsg == 0) {*OfflineMsg = (char *) malloc(1); **OfflineMsg = 0;}
6289     errorCode = CallPostamble(tcon, errorCode);
6290
6291 #if FS_STATS_DETAILED
6292     TM_GetTimeOfDay(&opStopTime, 0);
6293     if (errorCode == 0) {
6294       FS_LOCK
6295       (opP->numSuccesses)++;
6296       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6297       fs_stats_AddTo((opP->sumTime), elapsedTime);
6298       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6299       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6300         fs_stats_TimeAssign((opP->minTime), elapsedTime);
6301       }
6302       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6303         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6304       }
6305       FS_UNLOCK
6306     }
6307
6308 #endif /* FS_STATS_DETAILED */
6309     return(errorCode);
6310
6311 } /*SRXAFS_GetVolumeStatus*/
6312
6313
6314 afs_int32 SRXAFS_SetVolumeStatus (struct rx_call *acall,
6315                                   afs_int32 avolid,
6316                                   AFSStoreVolumeStatus *StoreVolStatus,
6317                                   char *Name,
6318                                   char *OfflineMsg,
6319                                   char *Motd)
6320 {
6321     Vnode * targetptr = 0;              /* vnode of the new file */
6322     Vnode * parentwhentargetnotdir = 0; /* vnode of parent */
6323     int     errorCode = 0;              /* error code */
6324     Volume * volptr = 0;                /* pointer to the volume header */
6325     struct client * client;             /* pointer to client entry */
6326     afs_int32 rights, anyrights;                /* rights for this and any user */
6327     AFSFid  dummyFid;
6328     struct rx_connection *tcon = rx_ConnectionOf(acall);
6329 #if FS_STATS_DETAILED
6330     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
6331     struct timeval opStartTime,
6332                    opStopTime;              /* Start/stop times for RPC op*/
6333     struct timeval elapsedTime;             /* Transfer time */
6334
6335     /*
6336      * Set our stats pointer, remember when the RPC operation started, and
6337      * tally the operation.
6338      */
6339     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETVOLUMESTATUS]);
6340     FS_LOCK
6341     (opP->numOps)++;
6342     FS_UNLOCK
6343     TM_GetTimeOfDay(&opStartTime, 0);
6344 #endif /* FS_STATS_DETAILED */
6345
6346     ViceLog(1,("SAFS_SetVolumeStatus for volume %u\n", avolid));
6347     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
6348         goto Bad_SetVolumeStatus;
6349
6350     FS_LOCK
6351     AFSCallStats.SetVolumeStatus++, AFSCallStats.TotalCalls++;
6352     FS_UNLOCK
6353
6354     if (avolid == 0) {
6355         errorCode = EINVAL;
6356         goto Bad_SetVolumeStatus;
6357     }
6358     dummyFid.Volume = avolid, dummyFid.Vnode = (afs_int32)ROOTVNODE, dummyFid.Unique = 1;
6359
6360     if ((errorCode = GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr,
6361                                      MustBeDIR, &parentwhentargetnotdir,
6362                                      &client, READ_LOCK, &rights, &anyrights)))
6363         goto Bad_SetVolumeStatus;
6364
6365     if (readonlyServer) {
6366         errorCode = VREADONLY;
6367         goto Bad_SetVolumeStatus;
6368     }
6369     if (VanillaUser(client)) {
6370         errorCode = EACCES;
6371         goto Bad_SetVolumeStatus;
6372     }
6373
6374     errorCode = RXUpdate_VolumeStatus(volptr, StoreVolStatus, Name,
6375                                       OfflineMsg, Motd);
6376
6377  Bad_SetVolumeStatus:
6378     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
6379     ViceLog(2,("SAFS_SetVolumeStatus returns %d\n",errorCode));
6380     errorCode = CallPostamble(tcon, errorCode);
6381
6382 #if FS_STATS_DETAILED
6383     TM_GetTimeOfDay(&opStopTime, 0);
6384     if (errorCode == 0) {
6385       FS_LOCK
6386       (opP->numSuccesses)++;
6387       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6388       fs_stats_AddTo((opP->sumTime), elapsedTime);
6389       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6390       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6391         fs_stats_TimeAssign((opP->minTime), elapsedTime);
6392       }
6393       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6394         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6395       }
6396       FS_UNLOCK
6397     }
6398
6399 #endif /* FS_STATS_DETAILED */
6400
6401     osi_auditU (acall, SetVolumeStatusEvent, errorCode, AUD_LONG, avolid, AUD_STR, Name, AUD_END);
6402     return(errorCode);
6403
6404 } /*SRXAFS_SetVolumeStatus*/
6405
6406 #define DEFAULTVOLUME   "root.afs"
6407
6408 afs_int32 SRXAFS_GetRootVolume (struct rx_call *acall, char **VolumeName)
6409 {
6410     int fd;
6411     int len;
6412     char *temp;
6413     int errorCode = 0;          /* error code */
6414     struct rx_connection *tcon;
6415 #if FS_STATS_DETAILED
6416     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
6417     struct timeval opStartTime,
6418                    opStopTime;              /* Start/stop times for RPC op*/
6419     struct timeval elapsedTime;             /* Transfer time */
6420
6421     /*
6422      * Set our stats pointer, remember when the RPC operation started, and
6423      * tally the operation.
6424      */
6425     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETROOTVOLUME]);
6426     FS_LOCK
6427     (opP->numOps)++;
6428     FS_UNLOCK
6429     TM_GetTimeOfDay(&opStartTime, 0);
6430 #endif /* FS_STATS_DETAILED */
6431
6432     return FSERR_EOPNOTSUPP;
6433
6434 #ifdef  notdef
6435     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon))
6436         goto Bad_GetRootVolume;
6437     FS_LOCK
6438     AFSCallStats.GetRootVolume++, AFSCallStats.TotalCalls++;
6439     FS_UNLOCK
6440
6441     temp = malloc(256);
6442     fd = open(AFSDIR_SERVER_ROOTVOL_FILEPATH, O_RDONLY, 0666);
6443     if (fd <= 0)
6444         strcpy(temp, DEFAULTVOLUME);
6445     else {
6446 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6447         lockf(fd, F_LOCK, 0);
6448 #else
6449         flock(fd, LOCK_EX);
6450 #endif
6451         len = read(fd, temp, 256);
6452 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6453         lockf(fd, F_ULOCK, 0);
6454 #else
6455         flock(fd, LOCK_UN);
6456 #endif
6457         close(fd);
6458         if (temp[len-1] == '\n') len--;
6459         temp[len] = '\0';
6460     }
6461     *VolumeName = temp;     /* freed by rx server-side stub */
6462
6463 Bad_GetRootVolume:
6464     errorCode = CallPostamble(tcon, errorCode);
6465
6466 #if FS_STATS_DETAILED
6467     TM_GetTimeOfDay(&opStopTime, 0);
6468     if (errorCode == 0) {
6469       FS_LOCK
6470       (opP->numSuccesses)++;
6471       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6472       fs_stats_AddTo((opP->sumTime), elapsedTime);
6473       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6474       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6475         fs_stats_TimeAssign((opP->minTime), elapsedTime);
6476       }
6477       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6478         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6479       }
6480       FS_UNLOCK
6481     }
6482 #endif /* FS_STATS_DETAILED */
6483
6484     return(errorCode);
6485 #endif  /* notdef */
6486
6487 } /*SRXAFS_GetRootVolume*/
6488
6489
6490 /* still works because a struct CBS is the same as a struct AFSOpaque */
6491 afs_int32 SRXAFS_CheckToken (struct rx_call *acall,
6492                              afs_int32 AfsId,
6493                              struct AFSOpaque *Token)
6494 {
6495     afs_int32 code;
6496     struct rx_connection *tcon;
6497 #if FS_STATS_DETAILED
6498     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
6499     struct timeval opStartTime,
6500                    opStopTime;              /* Start/stop times for RPC op*/
6501     struct timeval elapsedTime;             /* Transfer time */
6502
6503     /*
6504      * Set our stats pointer, remember when the RPC operation started, and
6505      * tally the operation.
6506      */
6507     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CHECKTOKEN]);
6508     FS_LOCK
6509     (opP->numOps)++;
6510     FS_UNLOCK
6511     TM_GetTimeOfDay(&opStartTime, 0);
6512 #endif /* FS_STATS_DETAILED */
6513
6514     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
6515         goto Bad_CheckToken;
6516
6517     code = FSERR_ECONNREFUSED;
6518     
6519 Bad_CheckToken:
6520     code = CallPostamble(tcon, code);
6521
6522 #if FS_STATS_DETAILED
6523     TM_GetTimeOfDay(&opStopTime, 0);
6524     if (code == 0) {
6525       FS_LOCK
6526       (opP->numSuccesses)++;
6527       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6528       fs_stats_AddTo((opP->sumTime), elapsedTime);
6529       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6530       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6531         fs_stats_TimeAssign((opP->minTime), elapsedTime);
6532       }
6533       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6534         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6535       }
6536       FS_UNLOCK
6537     }
6538
6539 #endif /* FS_STATS_DETAILED */
6540
6541     return code;
6542
6543 } /*SRXAFS_CheckToken*/
6544
6545 afs_int32 SRXAFS_GetTime (struct rx_call *acall,
6546                           afs_uint32 *Seconds,
6547                           afs_uint32 *USeconds)
6548 {
6549     afs_int32 code;
6550     struct rx_connection *tcon;
6551     struct timeval tpl;
6552 #if FS_STATS_DETAILED
6553     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
6554     struct timeval opStartTime,
6555                    opStopTime;              /* Start/stop times for RPC op*/
6556     struct timeval elapsedTime;             /* Transfer time */
6557
6558     /*
6559      * Set our stats pointer, remember when the RPC operation started, and
6560      * tally the operation.
6561      */
6562     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETTIME]);
6563     FS_LOCK
6564     (opP->numOps)++;
6565     FS_UNLOCK
6566     TM_GetTimeOfDay(&opStartTime, 0);
6567 #endif /* FS_STATS_DETAILED */
6568
6569     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon)))
6570         goto Bad_GetTime;
6571
6572     FS_LOCK
6573     AFSCallStats.GetTime++, AFSCallStats.TotalCalls++;
6574     FS_UNLOCK
6575
6576     TM_GetTimeOfDay(&tpl, 0);
6577     *Seconds = tpl.tv_sec;
6578     *USeconds = tpl.tv_usec;
6579
6580     ViceLog(2, ("SAFS_GetTime returns %d, %d\n", *Seconds, *USeconds));
6581     
6582 Bad_GetTime:
6583     code = CallPostamble(tcon, code);
6584
6585 #if FS_STATS_DETAILED
6586     TM_GetTimeOfDay(&opStopTime, 0);
6587     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6588     if (code == 0) {
6589       FS_LOCK
6590       (opP->numSuccesses)++;
6591       fs_stats_AddTo((opP->sumTime), elapsedTime);
6592       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6593       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6594         fs_stats_TimeAssign((opP->minTime), elapsedTime);
6595       }
6596       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6597         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6598       }
6599       FS_UNLOCK
6600     }
6601
6602 #endif /* FS_STATS_DETAILED */
6603
6604     return code;
6605
6606 } /*SRXAFS_GetTime*/
6607
6608
6609 /*
6610  * FetchData_RXStyle
6611  *
6612  * Purpose:
6613  *      Implement a client's data fetch using Rx.
6614  *
6615  * Arguments:
6616  *      volptr          : Ptr to the given volume's info.
6617  *      targetptr       : Pointer to the vnode involved.
6618  *      Call            : Ptr to the Rx call involved.
6619  *      Pos             : Offset within the file.
6620  *      Len             : Length in bytes to read; this value is bogus!
6621  * if FS_STATS_DETAILED
6622  *      a_bytesToFetchP : Set to the number of bytes to be fetched from
6623  *                        the File Server.
6624  *      a_bytesFetchedP : Set to the actual number of bytes fetched from
6625  *                        the File Server.
6626  * endif
6627  */
6628
6629 afs_int32
6630 FetchData_RXStyle(Volume *volptr, 
6631                   Vnode *targetptr, 
6632                   register struct rx_call *Call,
6633                   afs_int32 Pos,
6634                   afs_int32 Len,
6635                   afs_int32 Int64Mode,
6636 #if FS_STATS_DETAILED
6637                   afs_int32 *a_bytesToFetchP,
6638                   afs_int32 *a_bytesFetchedP
6639 #endif /* FS_STATS_DETAILED */
6640                   )
6641 {
6642     struct timeval StartTime, StopTime; /* used to calculate file  transfer rates */
6643     int errorCode = 0;                  /* Returned error code to caller */
6644     int code;
6645     IHandle_t *ihP;
6646     FdHandle_t *fdP;
6647 #ifdef AFS_NT40_ENV
6648     register char *tbuffer;
6649 #else /* AFS_NT40_ENV */
6650     struct iovec tiov[RX_MAXIOVECS];
6651     int tnio;
6652 #endif /* AFS_NT40_ENV */
6653     afs_int32 tlen;
6654     afs_int32 optSize;
6655     struct stat tstat;
6656 #ifdef  AFS_AIX_ENV
6657     struct statfs tstatfs;
6658 #endif
6659
6660 #if FS_STATS_DETAILED
6661     /*
6662      * Initialize the byte count arguments.
6663      */
6664     (*a_bytesToFetchP) = 0;
6665     (*a_bytesFetchedP) = 0;
6666 #endif /* FS_STATS_DETAILED */
6667
6668     if (!VN_GET_INO(targetptr)) {
6669         /*
6670          * This is used for newly created files; we simply send 0 bytes
6671          * back to make the cache manager happy...
6672          */
6673         tlen = htonl(0);
6674         if (Int64Mode)
6675             rx_Write(Call, (char *)&tlen, sizeof(afs_int32));   /* send 0-length  */
6676         rx_Write(Call, (char *)&tlen, sizeof(afs_int32));       /* send 0-length  */
6677         return (0);
6678     }
6679     TM_GetTimeOfDay(&StartTime, 0);
6680     ihP = targetptr->handle;
6681     fdP = IH_OPEN(ihP);
6682     if (fdP == NULL) return EIO;
6683     optSize = sendBufSize;
6684     tlen = FDH_SIZE(fdP);
6685     if (tlen < 0) {
6686         FDH_CLOSE(fdP);
6687         return EIO;
6688     }
6689
6690     if (Pos + Len > tlen) Len = tlen - Pos;     /* get length we should send */
6691     (void) FDH_SEEK(fdP, Pos, 0);
6692     tlen = htonl(Len);
6693     if (Int64Mode) {
6694         afs_int32 zero = 0;
6695         rx_Write(Call, (char *)&zero, sizeof(afs_int32)); /* High order bits */
6696     }
6697     rx_Write(Call, (char *)&tlen, sizeof(afs_int32));   /* send length on fetch */
6698 #if FS_STATS_DETAILED
6699     (*a_bytesToFetchP) = Len;
6700 #endif /* FS_STATS_DETAILED */
6701 #ifdef AFS_NT40_ENV
6702     tbuffer = AllocSendBuffer();
6703 #endif /* AFS_NT40_ENV */
6704     while (Len > 0) {
6705         if (Len > optSize) tlen = optSize;
6706         else tlen = Len;
6707 #ifdef AFS_NT40_ENV
6708         errorCode = FDH_READ(fdP, tbuffer, tlen);
6709         if (errorCode != tlen) {
6710             FDH_CLOSE(fdP);
6711             FreeSendBuffer((struct afs_buffer *) tbuffer);
6712             return EIO;
6713         }
6714         errorCode = rx_Write(Call, tbuffer, tlen);
6715 #else /* AFS_NT40_ENV */
6716         errorCode = rx_WritevAlloc(Call, tiov, &tnio, RX_MAXIOVECS, tlen);
6717         if (errorCode <= 0) {
6718             FDH_CLOSE(fdP);
6719             return EIO;
6720         }
6721         tlen = errorCode;
6722         errorCode = FDH_READV(fdP, tiov, tnio);
6723         if (errorCode != tlen) {
6724             FDH_CLOSE(fdP);
6725             return EIO;
6726         }
6727         errorCode = rx_Writev(Call, tiov, tnio, tlen);
6728 #endif /* AFS_NT40_ENV */
6729 #if FS_STATS_DETAILED
6730         /*
6731           * Bump the number of bytes actually sent by the number from this
6732           * latest iteration
6733           */
6734         (*a_bytesFetchedP) += errorCode;
6735 #endif /* FS_STATS_DETAILED */
6736         if (errorCode != tlen) {
6737             FDH_CLOSE(fdP);
6738 #ifdef AFS_NT40_ENV
6739             FreeSendBuffer((struct afs_buffer *) tbuffer);
6740 #endif /* AFS_NT40_ENV */
6741             return -31;
6742         }
6743         Len -= tlen;
6744     }
6745 #ifdef AFS_NT40_ENV
6746     FreeSendBuffer((struct afs_buffer *) tbuffer);
6747 #endif /* AFS_NT40_ENV */
6748     FDH_CLOSE(fdP);
6749     TM_GetTimeOfDay(&StopTime, 0);
6750
6751     /* Adjust all Fetch Data related stats */
6752     FS_LOCK
6753     if (AFSCallStats.TotalFetchedBytes > 2000000000) /* Reset if over 2 billion */
6754         AFSCallStats.TotalFetchedBytes = AFSCallStats.AccumFetchTime = 0;
6755     AFSCallStats.AccumFetchTime += ((StopTime.tv_sec - StartTime.tv_sec) * 1000) +
6756       ((StopTime.tv_usec - StartTime.tv_usec) / 1000);
6757     {
6758         afs_fsize_t     targLen;
6759         VN_GET_LEN(targLen, targetptr);
6760         AFSCallStats.TotalFetchedBytes += targLen;
6761         AFSCallStats.FetchSize1++;
6762         if (targLen < SIZE2)
6763             AFSCallStats.FetchSize2++;  
6764         else if (targLen < SIZE3)
6765             AFSCallStats.FetchSize3++;
6766         else if (targLen < SIZE4)
6767             AFSCallStats.FetchSize4++;  
6768         else
6769             AFSCallStats.FetchSize5++;
6770     }
6771     FS_UNLOCK
6772     return (0);
6773
6774 } /*FetchData_RXStyle*/
6775
6776 static int GetLinkCountAndSize(Volume *vp, FdHandle_t *fdP, int *lc, int *size)
6777 {
6778 #ifdef AFS_NAMEI_ENV
6779     FdHandle_t *lhp;
6780     lhp = IH_OPEN(V_linkHandle(vp));
6781     if (!lhp)
6782         return EIO;
6783 #ifdef AFS_NT40_ENV
6784     *lc = nt_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
6785 #else
6786     *lc = namei_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
6787 #endif
6788     FDH_CLOSE(lhp);
6789     if (*lc < 0 )
6790         return -1;
6791     *size = OS_SIZE(fdP->fd_fd);
6792     return (*size == -1) ? -1 : 0;
6793 #else
6794     struct stat status;
6795
6796     if (fstat(fdP->fd_fd, &status)<0) {
6797         return -1;
6798     }
6799
6800     *lc = GetLinkCount(vp, &status);
6801     *size = status.st_size;
6802     return 0;
6803 #endif   
6804 }
6805
6806 /*
6807  * StoreData_RXStyle
6808  *
6809  * Purpose:
6810  *      Implement a client's data store using Rx.
6811  *
6812  * Arguments:
6813  *      volptr          : Ptr to the given volume's info.
6814  *      targetptr       : Pointer to the vnode involved.
6815  *      Call            : Ptr to the Rx call involved.
6816  *      Pos             : Offset within the file.
6817  *      Len             : Length in bytes to store; this value is bogus!
6818  * if FS_STATS_DETAILED
6819  *      a_bytesToStoreP : Set to the number of bytes to be stored to
6820  *                        the File Server.
6821  *      a_bytesStoredP  : Set to the actual number of bytes stored to
6822  *                        the File Server.
6823  * endif
6824  */
6825 afs_int32
6826 StoreData_RXStyle(Volume *volptr,
6827                   Vnode *targetptr,
6828                   struct AFSFid *Fid,
6829                   struct client *client,
6830                   register struct rx_call *Call,
6831                   afs_uint32 Pos,
6832                   afs_uint32 Length,
6833                   afs_uint32 FileLength,
6834                   int sync,
6835 #if FS_STATS_DETAILED
6836                   afs_int32 *a_bytesToStoreP,
6837                   afs_int32 *a_bytesStoredP
6838 #endif /* FS_STATS_DETAILED */
6839                   )
6840 {
6841     int     bytesTransfered;            /* number of bytes actually transfered */
6842     struct timeval StartTime, StopTime; /* Used to measure how long the store takes */
6843     int errorCode = 0;                  /* Returned error code to caller */
6844 #ifdef AFS_NT40_ENV
6845     register char *tbuffer;             /* data copying buffer */
6846 #else /* AFS_NT40_ENV */
6847     struct iovec tiov[RX_MAXIOVECS];    /* no data copying with iovec */
6848     int tnio;                           /* temp for iovec size */
6849 #endif /* AFS_NT40_ENV */
6850     int tlen;                           /* temp for xfr length */
6851     Inode tinode;                       /* inode for I/O */
6852     afs_int32 optSize;                  /* optimal transfer size */
6853     int DataLength;                     /* size of inode */
6854     afs_int32 TruncatedLength;          /* size after ftruncate */
6855     afs_uint32 NewLength;               /* size after this store completes */
6856     afs_int32 adjustSize;               /* bytes to call VAdjust... with */
6857     int linkCount;                      /* link count on inode */
6858     int code;
6859     FdHandle_t *fdP;
6860     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
6861
6862 #if FS_STATS_DETAILED
6863     /*
6864      * Initialize the byte count arguments.
6865      */
6866     (*a_bytesToStoreP) = 0;
6867     (*a_bytesStoredP)  = 0;
6868 #endif /* FS_STATS_DETAILED */
6869
6870     /*
6871      * We break the callbacks here so that the following signal will not
6872      * leave a window.
6873      */
6874     BreakCallBack(client->host, Fid, 0);
6875
6876     if (Pos == -1 || VN_GET_INO(targetptr) == 0) {
6877         /* the inode should have been created in Alloc_NewVnode */
6878         logHostAddr.s_addr = rx_HostOf(rx_PeerOf(rx_ConnectionOf(Call)));
6879         ViceLog(0, ("StoreData_RXStyle : Inode non-existent Fid = %u.%d.%d, inode = %d, Pos %d Host %s\n",
6880                 Fid->Volume, Fid->Vnode, Fid->Unique, 
6881                 VN_GET_INO(targetptr), Pos, inet_ntoa(logHostAddr) ));
6882         return ENOENT;  /* is this proper error code? */
6883     }
6884     else {
6885         /*
6886          * See if the file has several links (from other volumes).  If it
6887          * does, then we have to make a copy before changing it to avoid
6888          *changing read-only clones of this dude
6889          */
6890         ViceLog(25, ("StoreData_RXStyle : Opening inode %s\n",
6891                      PrintInode(NULL, VN_GET_INO(targetptr))));
6892         fdP = IH_OPEN(targetptr->handle);
6893         if (fdP == NULL) 
6894             return ENOENT;
6895         if (GetLinkCountAndSize(volptr, fdP, &linkCount,
6896                                 &DataLength)<0) {
6897             FDH_CLOSE(fdP);
6898             return EIO;
6899         }
6900         
6901         if (linkCount != 1) {
6902             afs_fsize_t size;
6903             ViceLog(25, ("StoreData_RXStyle : inode %s has more than onelink\n",
6904                          PrintInode(NULL, VN_GET_INO(targetptr))));
6905             /* other volumes share this data, better copy it first */
6906
6907             /* Adjust the disk block count by the creation of the new inode.
6908              * We call the special VDiskUsage so we don't adjust the volume's
6909              * quota since we don't want to penalyze the user for afs's internal
6910              * mechanisms (i.e. copy on write overhead.) Also the right size
6911              * of the disk will be recorded...
6912              */
6913             FDH_CLOSE(fdP);
6914             VN_GET_LEN(size, targetptr);
6915             volptr->partition->flags &= ~PART_DONTUPDATE;
6916             VSetPartitionDiskUsage(volptr->partition);
6917             volptr->partition->flags |= PART_DONTUPDATE;
6918             if ((errorCode = VDiskUsage(volptr, nBlocks(size)))) {
6919                 volptr->partition->flags &= ~PART_DONTUPDATE;
6920                 return(errorCode);
6921             }
6922
6923             ViceLog(25, ("StoreData : calling CopyOnWrite on  target dir\n"));
6924             if ((errorCode = CopyOnWrite(targetptr, volptr)))
6925             {
6926                 ViceLog(25, ("StoreData : CopyOnWrite failed\n"));
6927                 volptr->partition->flags &= ~PART_DONTUPDATE;
6928                 return (errorCode);
6929             }
6930             volptr->partition->flags &= ~PART_DONTUPDATE;
6931             VSetPartitionDiskUsage(volptr->partition);
6932             fdP = IH_OPEN(targetptr->handle);
6933             if (fdP == NULL)  {
6934                 ViceLog(25, ("StoreData : Reopen after CopyOnWrite failed\n"));
6935                 return ENOENT;
6936             }
6937         }
6938         tinode = VN_GET_INO(targetptr);
6939     }
6940     assert(VALID_INO(tinode));
6941
6942     /* compute new file length */
6943     NewLength = DataLength;
6944     if (FileLength < NewLength)
6945         /* simulate truncate */
6946         NewLength = FileLength; 
6947     TruncatedLength = NewLength; /* remember length after possible ftruncate */
6948     if (Pos + Length > NewLength)
6949         NewLength = Pos+Length;   /* and write */
6950
6951     /* adjust the disk block count by the difference in the files */
6952     {
6953         afs_fsize_t     targSize;
6954         VN_GET_LEN(targSize, targetptr);
6955         adjustSize = nBlocks(NewLength) - nBlocks(targSize);
6956     }
6957     if((errorCode = AdjustDiskUsage(volptr, adjustSize,
6958                                    adjustSize - SpareComp(volptr)))) {
6959         FDH_CLOSE(fdP);
6960         return(errorCode);
6961     }
6962
6963     /* can signal cache manager to proceed from close now */
6964     /* this bit means that the locks are set and protections are OK */
6965     rx_SetLocalStatus(Call, 1);
6966
6967     TM_GetTimeOfDay(&StartTime, 0);
6968
6969     optSize = sendBufSize;
6970
6971     /* truncate the file iff it needs it (ftruncate is slow even when its a noop) */
6972     if (FileLength < DataLength) FDH_TRUNC(fdP, FileLength);
6973     if (Pos > 0) FDH_SEEK(fdP, Pos, 0);
6974     bytesTransfered = 0;
6975 #ifdef AFS_NT40_ENV
6976     tbuffer = AllocSendBuffer();
6977 #endif /* AFS_NT40_ENV */
6978     /* if length == 0, the loop below isn't going to do anything, including
6979      * extend the length of the inode, which it must do, since the file system
6980      * assumes that the inode length == vnode's file length.  So, we extend
6981      * the file length manually if need be.  Note that if file is bigger than
6982      * Pos+(Length==0), we dont' have to do anything, and certainly shouldn't
6983      * do what we're going to do below.
6984      */
6985     if (Length == 0 && Pos > TruncatedLength) {
6986         /* Set the file's length; we've already done an lseek to the right
6987          * spot above.
6988          */
6989         errorCode = FDH_WRITE(fdP, &tlen, 1);
6990         if (errorCode != 1) goto done;
6991         errorCode = FDH_TRUNC(fdP, Pos);
6992     }
6993     else {
6994         /* have some data to copy */
6995 #if FS_STATS_DETAILED
6996         (*a_bytesToStoreP) = Length;
6997 #endif /* FS_STATS_DETAILED */
6998         while (1) {
6999             if (bytesTransfered >= Length) {
7000                 errorCode = 0;
7001                 break;
7002             }
7003             tlen = Length -     bytesTransfered;    /* how much more to do */
7004             if (tlen > optSize) tlen = optSize; /* bound by buffer size */
7005 #ifdef AFS_NT40_ENV
7006             errorCode = rx_Read(Call, tbuffer, tlen);
7007 #else /* AFS_NT40_ENV */
7008             errorCode = rx_Readv(Call, tiov, &tnio, RX_MAXIOVECS, tlen);
7009 #endif /* AFS_NT40_ENV */
7010 #if FS_STATS_DETAILED
7011             (*a_bytesStoredP) += errorCode;
7012 #endif /* FS_STATS_DETAILED */
7013             if (errorCode <= 0) {
7014                 errorCode = -32;
7015                 break;
7016             }
7017             tlen = errorCode;
7018 #ifdef AFS_NT40_ENV
7019             errorCode = FDH_WRITE(fdP, tbuffer, tlen);
7020 #else /* AFS_NT40_ENV */
7021             errorCode = FDH_WRITEV(fdP, tiov, tnio);
7022 #endif /* AFS_NT40_ENV */
7023             if (errorCode != tlen) {
7024                 errorCode = VDISKFULL;
7025                 break;
7026             }
7027             bytesTransfered += tlen;
7028         }
7029     }
7030   done:
7031 #ifdef AFS_NT40_ENV
7032     FreeSendBuffer((struct afs_buffer *) tbuffer);
7033 #endif /* AFS_NT40_ENV */
7034     if (sync) {
7035       FDH_SYNC(fdP);
7036     }
7037     if (errorCode) {
7038         afs_fsize_t     nfSize = FDH_SIZE(fdP);
7039         /* something went wrong: adjust size and return */
7040         VN_SET_LEN(targetptr, nfSize); /* set new file size. */
7041         /* changed_newTime is tested in StoreData to detemine if we
7042          * need to update the target vnode.
7043          */
7044         targetptr->changed_newTime = 1;
7045         FDH_CLOSE(fdP);
7046         /* set disk usage to be correct */
7047         VAdjustDiskUsage(&errorCode, volptr,
7048                          (int)(nBlocks(nfSize) - nBlocks(NewLength)), 0);
7049         return errorCode;
7050     }
7051     FDH_CLOSE(fdP);
7052
7053     TM_GetTimeOfDay(&StopTime, 0);
7054
7055     VN_SET_LEN(targetptr, NewLength);
7056
7057     /* Update all StoreData related stats */
7058     FS_LOCK
7059     if (AFSCallStats.TotalStoredBytes > 2000000000)     /* reset if over 2 billion */
7060         AFSCallStats.TotalStoredBytes = AFSCallStats.AccumStoreTime = 0;
7061     AFSCallStats.StoreSize1++;                  /* Piggybacked data */
7062     {
7063         afs_fsize_t     targLen;
7064         VN_GET_LEN(targLen, targetptr);
7065         if (targLen < SIZE2)
7066             AFSCallStats.StoreSize2++;
7067         else if (targLen < SIZE3)
7068             AFSCallStats.StoreSize3++;
7069         else if (targLen < SIZE4)
7070             AFSCallStats.StoreSize4++;
7071         else
7072             AFSCallStats.StoreSize5++;
7073     }
7074     FS_UNLOCK
7075     return(errorCode);
7076
7077 } /*StoreData_RXStyle*/
7078
7079 static int sys2et[512];
7080
7081 void init_sys_error_to_et(void) {
7082     memset(&sys2et, 0, sizeof(sys2et));
7083     sys2et[EPERM] = UAEPERM;
7084     sys2et[ENOENT] = UAENOENT;
7085     sys2et[ESRCH] = UAESRCH;
7086     sys2et[EINTR] = UAEINTR;
7087     sys2et[EIO] = UAEIO;
7088     sys2et[ENXIO] = UAENXIO;
7089     sys2et[E2BIG] = UAE2BIG;
7090     sys2et[ENOEXEC] = UAENOEXEC;
7091     sys2et[EBADF] = UAEBADF;
7092     sys2et[ECHILD] = UAECHILD;
7093     sys2et[EAGAIN] = UAEAGAIN;
7094     sys2et[ENOMEM] = UAENOMEM;
7095     sys2et[EACCES] = UAEACCES;
7096     sys2et[EFAULT] = UAEFAULT;
7097     sys2et[ENOTBLK] = UAENOTBLK;
7098     sys2et[EBUSY] = UAEBUSY;
7099     sys2et[EEXIST] = UAEEXIST;
7100     sys2et[EXDEV] = UAEXDEV;
7101     sys2et[ENODEV] = UAENODEV;
7102     sys2et[ENOTDIR] = UAENOTDIR;
7103     sys2et[EISDIR] = UAEISDIR;
7104     sys2et[EINVAL] = UAEINVAL;
7105     sys2et[ENFILE] = UAENFILE;
7106     sys2et[EMFILE] = UAEMFILE;
7107     sys2et[ENOTTY] = UAENOTTY;
7108     sys2et[ETXTBSY] = UAETXTBSY;
7109     sys2et[EFBIG] = UAEFBIG;
7110     sys2et[ENOSPC] = UAENOSPC;
7111     sys2et[ESPIPE] = UAESPIPE;
7112     sys2et[EROFS] = UAEROFS;
7113     sys2et[EMLINK] = UAEMLINK;
7114     sys2et[EPIPE] = UAEPIPE;
7115     sys2et[EDOM] = UAEDOM;
7116     sys2et[ERANGE] = UAERANGE;
7117     sys2et[EDEADLK] = UAEDEADLK;
7118     sys2et[ENAMETOOLONG] = UAENAMETOOLONG;
7119     sys2et[ENOLCK] = UAENOLCK;
7120     sys2et[ENOSYS] = UAENOSYS;
7121     sys2et[ENOTEMPTY] = UAENOTEMPTY;
7122     sys2et[ELOOP] = UAELOOP;
7123     sys2et[EWOULDBLOCK] = UAEWOULDBLOCK;
7124     sys2et[ENOMSG] = UAENOMSG;
7125     sys2et[EIDRM] = UAEIDRM;
7126     sys2et[ECHRNG] = UAECHRNG;
7127     sys2et[EL2NSYNC] = UAEL2NSYNC;
7128     sys2et[EL3HLT] = UAEL3HLT;
7129     sys2et[EL3RST] = UAEL3RST;
7130     sys2et[ELNRNG] = UAELNRNG;
7131     sys2et[EUNATCH] = UAEUNATCH;
7132     sys2et[ENOCSI] = UAENOCSI;
7133     sys2et[EL2HLT] = UAEL2HLT;
7134     sys2et[EBADE] = UAEBADE;
7135     sys2et[EBADR] = UAEBADR;
7136     sys2et[EXFULL] = UAEXFULL;
7137     sys2et[ENOANO] = UAENOANO;
7138     sys2et[EBADRQC] = UAEBADRQC;
7139     sys2et[EBADSLT] = UAEBADSLT;
7140     sys2et[EDEADLK] = UAEDEADLK;
7141     sys2et[EBFONT] = UAEBFONT;
7142     sys2et[ENOSTR] = UAENOSTR;
7143     sys2et[ENODATA] = UAENODATA;
7144     sys2et[ETIME] = UAETIME;
7145     sys2et[ENOSR] = UAENOSR;
7146     sys2et[ENONET] = UAENONET;
7147     sys2et[ENOPKG] = UAENOPKG;
7148     sys2et[EREMOTE] = UAEREMOTE;
7149     sys2et[ENOLINK] = UAENOLINK;
7150     sys2et[EADV] = UAEADV;
7151     sys2et[ESRMNT] = UAESRMNT;
7152     sys2et[ECOMM] = UAECOMM;
7153     sys2et[EPROTO] = UAEPROTO;
7154     sys2et[EMULTIHOP] = UAEMULTIHOP;
7155     sys2et[EDOTDOT] = UAEDOTDOT;
7156     sys2et[EBADMSG] = UAEBADMSG;
7157     sys2et[EOVERFLOW] = UAEOVERFLOW;
7158     sys2et[ENOTUNIQ] = UAENOTUNIQ;
7159     sys2et[EBADFD] = UAEBADFD;
7160     sys2et[EREMCHG] = UAEREMCHG;
7161     sys2et[ELIBACC] = UAELIBACC;
7162     sys2et[ELIBBAD] = UAELIBBAD;
7163     sys2et[ELIBSCN] = UAELIBSCN;
7164     sys2et[ELIBMAX] = UAELIBMAX;
7165     sys2et[ELIBEXEC] = UAELIBEXEC;
7166     sys2et[EILSEQ] = UAEILSEQ;
7167     sys2et[ERESTART] = UAERESTART;
7168     sys2et[ESTRPIPE] = UAESTRPIPE;
7169     sys2et[EUSERS] = UAEUSERS;
7170     sys2et[ENOTSOCK] = UAENOTSOCK;
7171     sys2et[EDESTADDRREQ] = UAEDESTADDRREQ;
7172     sys2et[EMSGSIZE] = UAEMSGSIZE;
7173     sys2et[EPROTOTYPE] = UAEPROTOTYPE;
7174     sys2et[ENOPROTOOPT] = UAENOPROTOOPT;
7175     sys2et[EPROTONOSUPPORT] = UAEPROTONOSUPPORT;
7176     sys2et[ESOCKTNOSUPPORT] = UAESOCKTNOSUPPORT;
7177     sys2et[EOPNOTSUPP] = UAEOPNOTSUPP;
7178     sys2et[EPFNOSUPPORT] = UAEPFNOSUPPORT;
7179     sys2et[EAFNOSUPPORT] = UAEAFNOSUPPORT;
7180     sys2et[EADDRINUSE] = UAEADDRINUSE;
7181     sys2et[EADDRNOTAVAIL] = UAEADDRNOTAVAIL;
7182     sys2et[ENETDOWN] = UAENETDOWN;
7183     sys2et[ENETUNREACH] = UAENETUNREACH;
7184     sys2et[ENETRESET] = UAENETRESET;
7185     sys2et[ECONNABORTED] = UAECONNABORTED;
7186     sys2et[ECONNRESET] = UAECONNRESET;
7187     sys2et[ENOBUFS] = UAENOBUFS;
7188     sys2et[EISCONN] = UAEISCONN;
7189     sys2et[ENOTCONN] = UAENOTCONN;
7190     sys2et[ESHUTDOWN] = UAESHUTDOWN;
7191     sys2et[ETOOMANYREFS] = UAETOOMANYREFS;
7192     sys2et[ETIMEDOUT] = UAETIMEDOUT;
7193     sys2et[ECONNREFUSED] = UAECONNREFUSED;
7194     sys2et[EHOSTDOWN] = UAEHOSTDOWN;
7195     sys2et[EHOSTUNREACH] = UAEHOSTUNREACH;
7196     sys2et[EALREADY] = UAEALREADY;
7197     sys2et[EINPROGRESS] = UAEINPROGRESS;
7198     sys2et[ESTALE] = UAESTALE;
7199     sys2et[EUCLEAN] = UAEUCLEAN;
7200     sys2et[ENOTNAM] = UAENOTNAM;
7201     sys2et[ENAVAIL] = UAENAVAIL;
7202     sys2et[EISNAM] = UAEISNAM;
7203     sys2et[EREMOTEIO] = UAEREMOTEIO;
7204     sys2et[EDQUOT] = UAEDQUOT;
7205     sys2et[ENOMEDIUM] = UAENOMEDIUM;
7206     sys2et[EMEDIUMTYPE] = UAEMEDIUMTYPE;
7207 }
7208
7209 afs_int32 sys_error_to_et(afs_int32 in) {
7210     if (in == 0) return 0;
7211     if (in < 0 || in > 511) return in;
7212     if (sys2et[in] != 0) return sys2et[in];
7213     return in;
7214 }