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