splint-fileserver-volserver-cleanup-20030602
[openafs.git] / src / viced / afsfileprocs.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*  afs_fileprocs.c - Complete File Server request routines              */
11 /*                                                                       */
12 /*  Information Technology Center                                        */
13 /*  Carnegie Mellon University                                           */
14 /*                                                                       */
15 /*  Date: 8/10/88                                                        */
16 /*                                                                       */
17 /*  Function    - A set of routines to handle the various file Server    */
18 /*                  requests; these routines are invoked by rxgen.       */
19 /*                                                                       */
20 /* ********************************************************************** */
21
22 /* 
23  * in Check_PermissionRights, certain privileges are afforded to the owner 
24  * of the volume, or the owner of a file.  Are these considered "use of 
25  * privilege"? 
26  */
27
28 #include <afsconfig.h>
29 #include <afs/param.h>
30
31 RCSID("$Header$");
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <errno.h>
36 #ifdef  AFS_SGI_ENV
37 #undef SHARED           /* XXX */
38 #endif
39 #ifdef AFS_NT40_ENV
40 #include <fcntl.h>
41 #else
42 #include <sys/param.h>
43 #include <sys/file.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48
49 #ifdef HAVE_STRING_H
50 #include <string.h>
51 #else
52 #ifdef HAVE_STRINGS_H
53 #include <strings.h>
54 #endif
55 #endif
56
57 #ifndef AFS_LINUX20_ENV
58 #include <net/if.h>
59 #include <netinet/if_ether.h>
60 #endif
61 #endif
62 #ifdef AFS_HPUX_ENV
63 /* included early because of name conflict on IOPEN */
64 #include <sys/inode.h>
65 #ifdef IOPEN
66 #undef IOPEN
67 #endif
68 #endif /* AFS_HPUX_ENV */
69 #include <afs/stds.h>
70 #include <rx/xdr.h>
71 #include <afs/nfs.h>
72 #include <afs/assert.h>
73 #include <lwp.h>
74 #include <lock.h>
75 #include <afs/afsint.h>
76 #include <afs/vldbint.h>
77 #include <afs/errors.h>
78 #include <afs/ihandle.h>
79 #include <afs/vnode.h>
80 #include <afs/volume.h>
81 #include <afs/acl.h>
82 #include <afs/ptclient.h>
83 #include <afs/prs_fs.h>
84 #include <rx/rx.h>
85 #include <rx/rx_globals.h>
86 #include <sys/stat.h>
87 #if ! defined(AFS_SGI_ENV) && ! defined(AFS_AIX32_ENV) && ! defined(AFS_NT40_ENV) && ! defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
88 #include <sys/map.h>
89 #endif
90 #if !defined(AFS_NT40_ENV)
91 #include <unistd.h>
92 #endif
93 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
94 #ifdef  AFS_AIX_ENV
95 #include <sys/statfs.h>
96 #include <sys/lockf.h>
97 #else
98 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
99 #include <sys/dk.h>
100 #endif
101 #endif
102 #endif
103 #include <afs/cellconfig.h>
104 #include <afs/keys.h>
105
106 #include <afs/auth.h>
107 #include <signal.h>
108 #include <afs/partition.h>
109 #include "viced_prototypes.h"
110 #include "viced.h"
111 #include "host.h"
112 #include <afs/unified_afs.h>
113 #include <afs/audit.h>
114 #include <afs/afsutil.h>
115
116 #ifdef AFS_PTHREAD_ENV
117 pthread_mutex_t fileproc_glock_mutex;
118 #endif /* AFS_PTHREAD_ENV */
119
120
121 /* Useful local defines used by this module */
122
123 #define DONTCHECK       0
124 #define MustNOTBeDIR    1
125 #define MustBeDIR       2
126
127 #define TVS_SDATA       1
128 #define TVS_SSTATUS     2
129 #define TVS_CFILE       4
130 #define TVS_SLINK       8
131 #define TVS_MKDIR       0x10
132
133 #define CHK_FETCH       0x10
134 #define CHK_FETCHDATA   0x10
135 #define CHK_FETCHACL    0x11
136 #define CHK_FETCHSTATUS 0x12
137 #define CHK_STOREDATA   0x00
138 #define CHK_STOREACL    0x01
139 #define CHK_STORESTATUS 0x02
140
141 #define OWNERREAD       0400
142 #define OWNERWRITE      0200
143 #define OWNEREXEC       0100
144 #ifdef USE_GROUP_PERMS
145 #define GROUPREAD       0040
146 #define GROUPWRITE      0020
147 #define GROUPREXEC      0010
148 #endif
149
150 /* The following errors were not defined in NT. They are given unique
151  * names here to avoid any potential collision.
152  */
153 #define FSERR_ELOOP              90
154 #define FSERR_EOPNOTSUPP        122
155 #define FSERR_ECONNREFUSED      130
156
157 #define NOTACTIVECALL   0
158 #define ACTIVECALL      1
159
160 #define CREATE_SGUID_ADMIN_ONLY 1
161
162 extern struct afsconf_dir *confDir;
163 extern afs_int32 dataVersionHigh;
164
165 extern  int         SystemId;
166 static struct AFSCallStatistics AFSCallStats;
167 #if FS_STATS_DETAILED
168 struct fs_stats_FullPerfStats afs_FullPerfStats;
169 extern int AnonymousID;
170 #endif /* FS_STATS_DETAILED */
171 #if OPENAFS_VOL_STATS
172 static const char nullString[] = "";
173 #endif /* OPENAFS_VOL_STATS */
174
175 struct afs_FSStats {
176     afs_int32 NothingYet;
177 };
178
179 struct afs_FSStats afs_fsstats;
180
181 void    ResetDebug(), SetDebug(), Terminate();
182
183 int     LogLevel = 0;
184 int     supported = 1;
185 int     Console = 0;
186 afs_int32 BlocksSpare = 1024;   /* allow 1 MB overruns */
187 afs_int32 PctSpare;
188 extern afs_int32 implicitAdminRights;
189 extern afs_int32 readonlyServer;
190
191 /*
192  * Externals used by the xstat code.
193  */
194 extern int VolumeCacheSize, VolumeGets, VolumeReplacements;
195 extern int CEs, CEBlocks;
196
197 extern int HTs, HTBlocks;
198
199 afs_int32
200 FetchData_RXStyle(Volume *volptr, 
201                   Vnode *targetptr, 
202                   register struct rx_call *Call,
203                   afs_int32 Pos,
204                   afs_int32 Len,
205                   afs_int32 Int64Mode,
206 #if FS_STATS_DETAILED
207                   afs_int32 *a_bytesToFetchP,
208                   afs_int32 *a_bytesFetchedP
209 #endif /* FS_STATS_DETAILED */
210                   );
211
212 afs_int32
213 StoreData_RXStyle(Volume *volptr,
214                   Vnode *targetptr,
215                   struct AFSFid *Fid,
216                   struct client *client,
217                   register struct rx_call *Call,
218                   afs_uint32 Pos,
219                   afs_uint32 Length,
220                   afs_uint32 FileLength,
221                   int sync,
222 #if FS_STATS_DETAILED
223                   afs_int32 *a_bytesToStoreP,
224                   afs_int32 *a_bytesStoredP
225 #endif /* FS_STATS_DETAILED */
226                   );
227
228 #ifdef AFS_SGI_XFS_IOPS_ENV
229 #include <afs/xfsattrs.h>
230 static int GetLinkCount(Volume *avp, struct stat *astat)
231 {
232     if (!strcmp("xfs", astat->st_fstype)) {
233         return (astat->st_mode & AFS_XFS_MODE_LINK_MASK);
234     }
235     else
236         return astat->st_nlink;
237 }
238 #else
239 #define GetLinkCount(V, S) (S)->st_nlink
240 #endif
241
242 afs_int32 SpareComp(Volume *avolp)
243 {
244     register afs_int32 temp;
245
246     FS_LOCK
247     if (PctSpare) {
248         temp = V_maxquota(avolp);
249         if (temp == 0) {
250             /* no matter; doesn't check in this case */
251             FS_UNLOCK
252             return 0;
253         }
254         temp = (temp * PctSpare) / 100;
255         FS_UNLOCK
256         return temp;
257     }
258     else {
259         FS_UNLOCK
260         return BlocksSpare;
261     }
262
263 } /*SpareComp*/
264
265 /*
266  * Set the volume synchronization parameter for this volume.  If it changes,
267  * the Cache Manager knows that the volume must be purged from the stat cache.
268  */
269 static void SetVolumeSync(register struct AFSVolSync *async, 
270                           register Volume *avol)
271 {
272     FS_LOCK
273     /* date volume instance was created */
274     if (async) {
275         if (avol)
276             async->spare1 = avol->header->diskstuff.creationDate;
277         else
278             async->spare1 = 0;
279         async->spare2 = 0;
280         async->spare3 = 0;
281         async->spare4 = 0;
282         async->spare5 = 0;
283         async->spare6 = 0;
284     }
285     FS_UNLOCK
286 } /*SetVolumeSync*/
287
288 /*
289  * Note that this function always returns a held host, so
290  * that CallPostamble can block without the host's disappearing.
291  * Call returns rx connection in passed in *tconn
292  */
293 static int CallPreamble(register struct rx_call *acall, int activecall,
294                         struct rx_connection **tconn)
295 {
296     struct host *thost;
297     struct client *tclient;
298     int retry_flag=1;
299     int code = 0;
300     char hoststr[16];
301     if (!tconn) {
302         ViceLog (0, ("CallPreamble: unexpected null tconn!\n"));
303         return -1;
304     }
305     *tconn = rx_ConnectionOf(acall);
306
307     H_LOCK
308 retry:
309     tclient = h_FindClient_r(*tconn);
310     if (tclient->prfail == 1) { /* couldn't get the CPS */
311        if (!retry_flag) {
312           h_ReleaseClient_r(tclient);
313           ViceLog(0, ("CallPreamble: Couldn't get CPS. Fail\n"));
314           H_UNLOCK
315           return -1001;
316        }
317        retry_flag=0;    /* Retry once */
318
319        /* Take down the old connection and re-read the key file */
320        ViceLog(0, ("CallPreamble: Couldn't get CPS. Reconnect to ptserver\n"));
321        H_UNLOCK
322        code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
323        H_LOCK
324        if (code) {
325           h_ReleaseClient_r(tclient);
326           H_UNLOCK
327           ViceLog(0,("CallPreamble: couldn't reconnect to ptserver\n"));
328           return -1001;
329        }
330
331        tclient->prfail = 2;      /* Means re-eval client's cps */
332        h_ReleaseClient_r(tclient);
333        goto retry;
334     }
335
336     thost = tclient->host;
337     tclient->LastCall = thost->LastCall = FT_ApproxTime();
338     if (activecall) /* For all but "GetTime" calls */
339         thost->ActiveCall = thost->LastCall;
340
341     h_Lock_r(thost);
342     if (thost->hostFlags & HOSTDELETED) {
343       ViceLog(3,("Discarded a packet for deleted host %s\n",afs_inet_ntoa_r(thost->host,hoststr)));
344       code = VBUSY; /* raced, so retry */
345     }
346     else if ((thost->hostFlags & VENUSDOWN) || (thost->hostFlags & HFE_LATER)){
347       if (BreakDelayedCallBacks_r(thost)) {
348         ViceLog(0,("BreakDelayedCallbacks FAILED for host %s which IS UP.  Possible network or routing failure.\n",
349                 afs_inet_ntoa_r(thost->host, hoststr)));
350         if ( MultiProbeAlternateAddress_r (thost) ) {
351             ViceLog(0, ("MultiProbe failed to find new address for host %s:%d\n",
352                         afs_inet_ntoa_r(thost->host, hoststr), 
353                         ntohs(thost->port)));
354             code = -1;
355         } else {
356             ViceLog(0, ("MultiProbe found new address for host %s:%d\n",
357                         afs_inet_ntoa_r(thost->host, hoststr), 
358                         ntohs(thost->port)));
359             if (BreakDelayedCallBacks_r(thost)) {
360                 ViceLog(0,("BreakDelayedCallbacks FAILED AGAIN for host %s which IS UP.  Possible network or routing failure.\n",
361                         afs_inet_ntoa_r(thost->host, hoststr)));
362                 code = -1;
363             }
364         }
365       }
366     } else {
367        code =  0;
368     }
369
370     h_ReleaseClient_r(tclient);
371     h_Unlock_r(thost);
372     H_UNLOCK
373     return code;      
374
375 } /*CallPreamble*/
376
377
378 static afs_int32 CallPostamble(register struct rx_connection *aconn,
379                                afs_int32 ret)
380 {
381     struct host *thost;
382     struct client *tclient;
383     int translate = 0;
384
385     H_LOCK
386     tclient = h_FindClient_r(aconn);
387     thost = tclient->host;
388     if (thost->hostFlags & HERRORTRANS) translate = 1;
389     h_ReleaseClient_r(tclient);
390     h_Release_r(thost);
391     H_UNLOCK
392
393     return (translate ? sys_error_to_et(ret) : ret);
394 } /*CallPostamble*/
395
396 /*
397  * Returns the volume and vnode pointers associated with file Fid; the lock
398  * type on the vnode is set to lock. Note that both volume/vnode's ref counts
399  * are incremented and they must be eventualy released.
400  */
401 static afs_int32
402 CheckVnode(AFSFid *fid, Volume **volptr, Vnode **vptr, int lock)
403 {
404     int fileCode = 0;
405     int errorCode = -1;
406     static struct timeval restartedat = {0,0};
407
408     if (fid->Volume == 0 || fid->Vnode == 0) /* not: || fid->Unique == 0) */
409         return(EINVAL);
410     if ((*volptr) == 0) {
411       extern int VInit;
412
413       while(1) {
414         errorCode = 0;
415         *volptr = VGetVolume(&errorCode, (afs_int32)fid->Volume);
416         if (!errorCode) {
417           assert (*volptr);
418           break;
419         }
420         if ((errorCode == VOFFLINE) && (VInit < 2)) {
421             /* The volume we want may not be attached yet because
422              * the volume initialization is not yet complete.
423              * We can do several things: 
424              *     1.  return -1, which will cause users to see
425              *         "connection timed out".  This is more or
426              *         less the same as always, except that the servers
427              *         may appear to bounce up and down while they
428              *         are actually restarting.
429              *     2.  return VBUSY which will cause clients to 
430              *         sleep and retry for 6.5 - 15 minutes, depending
431              *         on what version of the CM they are running.  If
432              *         the file server takes longer than that interval 
433              *         to attach the desired volume, then the application
434              *         will see an ENODEV or EIO.  This approach has 
435              *         the advantage that volumes which have been attached
436              *         are immediately available, it keeps the server's
437              *         immediate backlog low, and the call is interruptible
438              *         by the user.  Users see "waiting for busy volume."
439              *     3.  sleep here and retry.  Some people like this approach
440              *         because there is no danger of seeing errors.  However, 
441              *         this approach only works with a bounded number of 
442              *         clients, since the pending queues will grow without
443              *         stopping.  It might be better to find a way to take
444              *         this call and stick it back on a queue in order to
445              *         recycle this thread for a different request.    
446              *     4.  Return a new error code, which new cache managers will
447              *         know enough to interpret as "sleep and retry", without
448              *         the upper bound of 6-15 minutes that is imposed by the
449              *         VBUSY handling.  Users will see "waiting for
450              *         busy volume," so they know that something is
451              *         happening.  Old cache managers must be able to do  
452              *         something reasonable with this, for instance, mark the
453              *         server down.  Fortunately, any error code < 0
454              *         will elicit that behavior. See #1.
455              *     5.  Some combination of the above.  I like doing #2 for 10
456              *         minutes, followed by #4.  3.1b and 3.2 cache managers
457              *         will be fine as long as the restart period is
458              *         not longer than 6.5 minutes, otherwise they may
459              *         return ENODEV to users.  3.3 cache managers will be
460              *         fine for 10 minutes, then will return
461              *         ETIMEDOUT.  3.4 cache managers will just wait
462              *         until the call works or fails definitively.
463              *  NB. The problem with 2,3,4,5 is that old clients won't
464              *  fail over to an alternate read-only replica while this
465              *  server is restarting.  3.4 clients will fail over right away.
466              */
467           if (restartedat.tv_sec == 0) {
468             /* I'm not really worried about when we restarted, I'm   */
469             /* just worried about when the first VBUSY was returned. */
470             TM_GetTimeOfDay(&restartedat, 0);
471             return(busyonrst?VBUSY:VRESTARTING);
472           }
473           else {
474             struct timeval now;
475             TM_GetTimeOfDay(&now, 0);
476             if ((now.tv_sec - restartedat.tv_sec) < (11*60)) {
477               return(busyonrst?VBUSY:VRESTARTING);
478             }
479             else {
480               return (VRESTARTING);
481             }
482           }
483         }
484           /* allow read operations on busy volume */
485         else if(errorCode==VBUSY && lock==READ_LOCK) {
486           errorCode=0;
487           break;
488         }
489         else if (errorCode)
490           return(errorCode);
491       }
492     }
493     assert (*volptr);
494
495     /* get the vnode  */
496     *vptr = VGetVnode(&errorCode, *volptr, fid->Vnode, lock);
497     if (errorCode)
498         return(errorCode);
499     if ((*vptr)->disk.uniquifier != fid->Unique) {
500         VPutVnode(&fileCode, *vptr);
501         assert(fileCode == 0);
502         *vptr = 0;
503         return(VNOVNODE);   /* return the right error code, at least */
504     }
505     return(0);
506 } /*CheckVnode*/
507
508 /*
509  * This routine returns the ACL associated with the targetptr. If the
510  * targetptr isn't a directory, we access its parent dir and get the ACL
511  * thru the parent; in such case the parent's vnode is returned in
512  * READ_LOCK mode.
513  */
514 static afs_int32
515 SetAccessList(Vnode **targetptr,
516               Volume **volume,
517               struct acl_accessList **ACL,
518               int * ACLSize,
519               Vnode **parent,
520               AFSFid *Fid,
521               int Lock)
522 {
523     if ((*targetptr)->disk.type == vDirectory) {
524         *parent = 0;
525         *ACL = VVnodeACL(*targetptr);
526         *ACLSize = VAclSize(*targetptr);
527         return(0);
528     }
529     else {
530         assert(Fid != 0);
531         while(1) {
532             VnodeId parentvnode;
533             int errorCode = 0;
534             
535             parentvnode = (*targetptr)->disk.parent;
536             VPutVnode(&errorCode,*targetptr);
537             *targetptr = 0;
538             if (errorCode) return(errorCode);
539             *parent = VGetVnode(&errorCode, *volume, parentvnode, READ_LOCK);
540             if (errorCode) return(errorCode);
541             *ACL = VVnodeACL(*parent);
542             *ACLSize = VAclSize(*parent);
543             if ((errorCode = CheckVnode(Fid, volume, targetptr, Lock)) != 0)
544                 return(errorCode);
545             if ((*targetptr)->disk.parent != parentvnode) {
546                 VPutVnode(&errorCode, *parent);
547                 *parent = 0;
548                 if (errorCode) return(errorCode);
549             } else
550                 return(0);
551         }
552     }
553
554 } /*SetAccessList*/
555
556 /*
557  * Compare the directory's ACL with the user's access rights in the client
558  * connection and return the user's and everybody else's access permissions
559  * in rights and anyrights, respectively
560  */
561 static afs_int32
562 GetRights (struct client *client,
563            struct acl_accessList *ACL,
564            afs_int32 *rights,
565            afs_int32 *anyrights)
566 {
567     extern prlist SystemAnyUserCPS;
568     afs_int32 hrights = 0;
569     int code;
570
571     if (acl_CheckRights(ACL, &SystemAnyUserCPS, anyrights) != 0) {
572
573         ViceLog(0,("CheckRights failed\n"));
574         *anyrights = 0;
575     }
576     *rights = 0;
577     acl_CheckRights(ACL, &client->CPS, rights);
578
579         /* wait if somebody else is already doing the getCPS call */
580     H_LOCK
581     while ( client->host->hostFlags & HCPS_INPROGRESS )
582     {
583         client->host->hostFlags |= HCPS_WAITING;  /* I am waiting */
584 #ifdef AFS_PTHREAD_ENV
585         pthread_cond_wait(&client->host->cond, &host_glock_mutex);
586 #else /* AFS_PTHREAD_ENV */
587         if ((code=LWP_WaitProcess( &(client->host->hostFlags))) !=LWP_SUCCESS)
588                 ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
589 #endif /* AFS_PTHREAD_ENV */
590     }
591
592     if (client->host->hcps.prlist_len && !client->host->hcps.prlist_val) {
593         ViceLog(0,("CheckRights: len=%d, for host=0x%x\n", client->host->hcps.prlist_len, client->host->host));
594     } else
595         acl_CheckRights(ACL, &client->host->hcps, &hrights);
596     H_UNLOCK
597     /* Allow system:admin the rights given with the -implicit option */
598     if (acl_IsAMember(SystemId, &client->CPS))
599         *rights |= implicitAdminRights;
600     *rights |= hrights;
601     *anyrights |= hrights;
602
603     return(0);
604
605 } /*GetRights*/
606
607 /*
608  * VanillaUser returns 1 (true) if the user is a vanilla user (i.e., not
609  * a System:Administrator)
610  */
611 static afs_int32
612 VanillaUser(struct client *client)
613 {
614     if (acl_IsAMember(SystemId, &client->CPS))
615         return(0);  /* not a system administrator, then you're "vanilla" */
616     return(1);
617
618 } /*VanillaUser*/
619
620
621 /*
622  * This unusual afs_int32-parameter routine encapsulates all volume package related
623  * operations together in a single function; it's called by almost all AFS
624  * interface calls.
625  */
626 static afs_int32
627 GetVolumePackage(struct rx_connection *tcon,
628                  AFSFid *Fid,
629                  Volume **volptr,
630                  Vnode **targetptr,
631                  int chkforDir,
632                  Vnode **parent,
633                  struct client **client,
634                  int locktype,
635                  afs_int32 *rights, 
636                  afs_int32 *anyrights)
637 {
638     struct acl_accessList * aCL;    /* Internal access List */
639     int aCLSize;            /* size of the access list */
640     int errorCode = 0;      /* return code to caller */
641
642     if ((errorCode = CheckVnode(Fid, volptr, targetptr, locktype)))
643         return(errorCode);
644     if (chkforDir) {
645         if (chkforDir == MustNOTBeDIR && ((*targetptr)->disk.type == vDirectory))
646             return(EISDIR);
647         else if (chkforDir == MustBeDIR && ((*targetptr)->disk.type != vDirectory))
648             return(ENOTDIR);
649     }
650     if ((errorCode = SetAccessList(targetptr, volptr, &aCL, &aCLSize, parent, (chkforDir == MustBeDIR ? (AFSFid *)0 : Fid), (chkforDir == MustBeDIR ? 0 : locktype))) != 0)
651         return(errorCode);
652     if (chkforDir == MustBeDIR) assert((*parent) == 0);
653     if ((errorCode = GetClient(tcon, client)) != 0)
654         return(errorCode);
655     if (!(*client))
656         return(EINVAL);
657     assert(GetRights(*client, aCL, rights, anyrights) == 0);
658     /* ok, if this is not a dir, set the PRSFS_ADMINISTER bit iff we're the owner */
659     if ((*targetptr)->disk.type != vDirectory) {
660         /* anyuser can't be owner, so only have to worry about rights, not anyrights */
661         if ((*targetptr)->disk.owner == (*client)->ViceId)
662             (*rights) |= PRSFS_ADMINISTER;
663         else
664             (*rights) &= ~PRSFS_ADMINISTER;
665     }
666 #ifdef ADMIN_IMPLICIT_LOOKUP
667     /* admins get automatic lookup on everything */
668     if (!VanillaUser(*client)) (*rights) |= PRSFS_LOOKUP;
669 #endif /* ADMIN_IMPLICIT_LOOKUP */
670     return errorCode;
671
672 } /*GetVolumePackage*/
673
674
675 /*
676  * This is the opposite of GetVolumePackage(), and is always used at the end of
677  * AFS calls to put back all used vnodes and the volume in the proper order!
678  */
679 static afs_int32
680 PutVolumePackage(Vnode *parentwhentargetnotdir, 
681                  Vnode *targetptr,
682                  Vnode *parentptr,
683                  Volume *volptr)
684 {
685     int fileCode = 0;   /* Error code returned by the volume package */
686
687     if (parentwhentargetnotdir) {
688         VPutVnode(&fileCode, parentwhentargetnotdir);
689         assert(!fileCode || (fileCode == VSALVAGE));
690     }
691     if (targetptr) {
692         VPutVnode(&fileCode, targetptr);
693         assert(!fileCode || (fileCode == VSALVAGE));
694     }
695     if (parentptr) {
696         VPutVnode(&fileCode, parentptr);
697         assert(!fileCode || (fileCode == VSALVAGE));
698     }
699     if (volptr) {
700         VPutVolume(volptr);
701     }
702 } /*PutVolumePackage*/
703
704 static int VolumeOwner (register struct client *client, 
705                         register Vnode *targetptr)
706 {
707     afs_int32 owner = V_owner(targetptr->volumePtr);    /* get volume owner */
708
709     if (owner >= 0)
710         return (client->ViceId == owner);
711     else {
712         /* 
713          * We don't have to check for host's cps since only regular
714          * viceid are volume owners.
715          */
716         return (acl_IsAMember(owner, &client->CPS));
717     }
718
719 } /*VolumeOwner*/
720
721 static int VolumeRootVnode (Vnode *targetptr)
722 {
723     return ((targetptr->vnodeNumber == ROOTVNODE) &&
724             (targetptr->disk.uniquifier == 1));
725
726 } /*VolumeRootVnode*/
727
728 /*
729  * Check if target file has the proper access permissions for the Fetch
730  * (FetchData, FetchACL, FetchStatus) and Store (StoreData, StoreACL,
731  * StoreStatus) related calls
732  */
733 /* this code should probably just set a "priv" flag where all the audit events
734  * are now, and only generate the audit event once at the end of the routine, 
735  * thus only generating the event if all the checks succeed, but only because
736  * of the privilege       XXX
737  */
738 static afs_int32
739 Check_PermissionRights(Vnode *targetptr,
740                        struct client *client,
741                        afs_int32 rights,
742                        int CallingRoutine,
743                        AFSStoreStatus *InStatus)
744 {
745     int errorCode = 0;
746 #define OWNSp(client, target) ((client)->ViceId == (target)->disk.owner)
747 #define CHOWN(i,t) (((i)->Mask & AFS_SETOWNER) &&((i)->Owner != (t)->disk.owner))
748 #define CHGRP(i,t) (((i)->Mask & AFS_SETGROUP) &&((i)->Group != (t)->disk.group))
749
750     if (CallingRoutine & CHK_FETCH) {
751         if (CallingRoutine == CHK_FETCHDATA || VanillaUser(client)) 
752           {
753             if (targetptr->disk.type == vDirectory || targetptr->disk.type == vSymlink) {
754                 if (   !(rights & PRSFS_LOOKUP)
755 #ifdef ADMIN_IMPLICIT_LOOKUP  
756                     /* grant admins fetch on all directories */
757                     && VanillaUser(client)
758 #endif /* ADMIN_IMPLICIT_LOOKUP */
759                     && !VolumeOwner(client, targetptr))
760                     return(EACCES);
761             } else {    /* file */
762                 /* must have read access, or be owner and have insert access */
763                 if (!(rights & PRSFS_READ) &&
764                     !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)))
765                     return(EACCES);
766             }
767             if (CallingRoutine == CHK_FETCHDATA && targetptr->disk.type == vFile)
768 #ifdef USE_GROUP_PERMS
769                 if (!OWNSp(client, targetptr) &&
770                     !acl_IsAMember(targetptr->disk.owner, &client->CPS)) {
771                     errorCode = (((GROUPREAD|GROUPEXEC) & targetptr->disk.modeBits)
772                                  ? 0: EACCES);
773                 } else {
774                     errorCode =(((OWNERREAD|OWNEREXEC) & targetptr->disk.modeBits)
775                                 ? 0: EACCES);
776                 }
777 #else
778                 /*
779                  * The check with the ownership below is a kludge to allow
780                  * reading of files created with no read permission. The owner
781                  * of the file is always allowed to read it.
782                  */
783                 if ((client->ViceId != targetptr->disk.owner) && VanillaUser(client))
784                     errorCode =(((OWNERREAD|OWNEREXEC) & targetptr->disk.modeBits) ? 0: EACCES);
785 #endif
786         }
787         else /*  !VanillaUser(client) && !FetchData */ {
788           osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0), 
789                                         AUD_INT, CallingRoutine, AUD_END);
790         }
791     }
792     else { /* a store operation */
793       if ( (rights & PRSFS_INSERT) && OWNSp(client, targetptr)
794           && (CallingRoutine != CHK_STOREACL)
795           && (targetptr->disk.type == vFile))
796         {
797           /* bypass protection checks on first store after a create
798            * for the creator; also prevent chowns during this time
799            * unless you are a system administrator */
800           /******  InStatus->Owner && UnixModeBits better be SET!! */
801           if ( CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
802             if (readonlyServer) 
803               return(VREADONLY);
804             else if (VanillaUser (client)) 
805               return(EPERM);      /* Was EACCES */
806             else
807               osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0), 
808                                             AUD_INT, CallingRoutine, AUD_END);
809           }
810         } else {
811           if (CallingRoutine != CHK_STOREDATA && !VanillaUser(client)) {
812             osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0),
813                                           AUD_INT, CallingRoutine, AUD_END);
814           }
815           else {
816             if (readonlyServer) {
817                 return(VREADONLY);
818             }
819             if (CallingRoutine == CHK_STOREACL) {
820               if (!(rights & PRSFS_ADMINISTER) &&
821                   !VolumeOwner(client, targetptr)) return(EACCES);
822             }
823             else {      /* store data or status */
824               /* watch for chowns and chgrps */
825               if (CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
826                 if (readonlyServer) 
827                   return(VREADONLY);
828                 else if (VanillaUser (client)) 
829                   return(EPERM);        /* Was EACCES */
830                 else
831                   osi_audit(PrivilegeEvent, 0,
832                             AUD_INT, (client ? client->ViceId : 0), 
833                             AUD_INT, CallingRoutine, AUD_END);
834               }
835               /* must be sysadmin to set suid/sgid bits */
836               if ((InStatus->Mask & AFS_SETMODE) &&
837 #ifdef AFS_NT40_ENV
838                   (InStatus->UnixModeBits & 0xc00) != 0) {
839 #else
840                   (InStatus->UnixModeBits & (S_ISUID|S_ISGID)) != 0) {
841 #endif
842                 if (readonlyServer)
843                   return(VREADONLY);
844                 if (VanillaUser(client))
845                   return(EACCES);
846                 else osi_audit( PrivSetID, 0, AUD_INT, (client ? client->ViceId : 0),
847                                               AUD_INT, CallingRoutine, AUD_END);
848               }
849               if (CallingRoutine == CHK_STOREDATA) {
850                 if (readonlyServer)
851                   return(VREADONLY);
852                 if (!(rights & PRSFS_WRITE))
853                   return(EACCES);
854                 /* Next thing is tricky.  We want to prevent people
855                  * from writing files sans 0200 bit, but we want
856                  * creating new files with 0444 mode to work.  We
857                  * don't check the 0200 bit in the "you are the owner"
858                  * path above, but here we check the bit.  However, if
859                  * you're a system administrator, we ignore the 0200
860                  * bit anyway, since you may have fchowned the file,
861                  * too */
862 #ifdef USE_GROUP_PERMS
863                         if ((targetptr->disk.type == vFile)
864                             && VanillaUser(client)) {
865                             if (!OWNSp(client, targetptr) &&
866                                 !acl_IsAMember(targetptr->disk.owner,
867                                                &client->CPS)) {
868                                 errorCode = ((GROUPWRITE & targetptr->disk.modeBits)
869                                              ? 0: EACCES);
870                             } else {
871                                 errorCode = ((OWNERWRITE & targetptr->disk.modeBits)
872                                              ? 0 : EACCES);
873                             }
874                         } else
875 #endif
876                 if ((targetptr->disk.type != vDirectory)
877                     && (!(targetptr->disk.modeBits & OWNERWRITE))) {
878                   if (readonlyServer)
879                     return(VREADONLY);
880                   if (VanillaUser(client))
881                     return(EACCES);
882                   else osi_audit( PrivilegeEvent, 0, AUD_INT, (client ? client->ViceId : 0),
883                                                      AUD_INT, CallingRoutine, AUD_END);
884                 }
885               }
886               else {  /* a status store */
887                 if (readonlyServer)
888                   return(VREADONLY);
889                 if (targetptr->disk.type == vDirectory) {
890                   if (!(rights & PRSFS_DELETE) && !(rights & PRSFS_INSERT))
891                     return(EACCES);
892                 }
893                 else {  /* a file  or symlink */
894                   if (!(rights & PRSFS_WRITE)) return(EACCES);
895                 }
896               }
897             }
898           }
899         }
900     }
901     return(errorCode);
902
903 } /*Check_PermissionRights*/
904
905
906 /*
907  * The Access List information is converted from its internal form in the
908  * target's vnode buffer (or its parent vnode buffer if not a dir), to an
909  * external form and returned back to the caller, via the AccessList
910  * structure
911  */
912 static afs_int32
913 RXFetch_AccessList(Vnode *targetptr,
914                    Vnode *parentwhentargetnotdir,
915                    struct AFSOpaque *AccessList)
916 {
917     char * eACL;        /* External access list placeholder */
918
919     if (acl_Externalize((targetptr->disk.type == vDirectory ?
920                          VVnodeACL(targetptr) :
921                          VVnodeACL(parentwhentargetnotdir)), &eACL) != 0) {
922         return EIO;
923     }
924     if ((strlen(eACL)+1) > AFSOPAQUEMAX) {
925         acl_FreeExternalACL(&eACL);
926         return(E2BIG);
927     } else {
928         strcpy((char *)(AccessList->AFSOpaque_val), (char *)eACL);
929         AccessList->AFSOpaque_len = strlen(eACL) +1;
930     }
931     acl_FreeExternalACL(&eACL);
932     return(0);
933
934 } /*RXFetch_AccessList*/
935
936
937 /*
938  * The Access List information is converted from its external form in the
939  * input AccessList structure to the internal representation and copied into
940  * the target dir's vnode storage.
941  */
942 static afs_int32
943 RXStore_AccessList(Vnode *targetptr, struct AFSOpaque *AccessList)
944 {
945     struct acl_accessList * newACL;     /* PlaceHolder for new access list */
946
947     if (acl_Internalize(AccessList->AFSOpaque_val, &newACL) != 0)
948         return(EINVAL);
949     if ((newACL->size + 4) > VAclSize(targetptr))
950         return(E2BIG);
951     memcpy((char *) VVnodeACL(targetptr), (char *) newACL, (int)(newACL->size));
952     acl_FreeACL(&newACL);
953     return(0);
954
955 } /*RXStore_AccessList*/
956
957
958 static afs_int32
959 Fetch_AccessList(Vnode *targetptr, Vnode *parentwhentargetnotdir,
960                  struct AFSAccessList *AccessList)
961 {
962     char * eACL;        /* External access list placeholder */
963
964     assert(acl_Externalize((targetptr->disk.type == vDirectory ?
965                             VVnodeACL(targetptr) :
966                             VVnodeACL(parentwhentargetnotdir)), &eACL) == 0);
967     if ((strlen(eACL)+1) > AccessList->MaxSeqLen) {
968         acl_FreeExternalACL(&eACL);
969         return(E2BIG);
970     } else {
971         strcpy((char *)(AccessList->SeqBody), (char *)eACL);
972         AccessList->SeqLen = strlen(eACL) +1;
973     }
974     acl_FreeExternalACL(&eACL);
975     return(0);
976
977 } /*Fetch_AccessList*/
978
979 /*
980  * The Access List information is converted from its external form in the
981  * input AccessList structure to the internal representation and copied into
982  * the target dir's vnode storage.
983  */
984 static afs_int32
985 Store_AccessList(Vnode *targetptr, struct AFSAccessList *AccessList)
986 {
987     struct acl_accessList * newACL;     /* PlaceHolder for new access list */
988
989     if (acl_Internalize(AccessList->SeqBody, &newACL) != 0)
990         return(EINVAL);
991     if ((newACL->size + 4) > VAclSize(targetptr))
992         return(E2BIG);
993     memcpy((char *) VVnodeACL(targetptr), (char *) newACL, (int)(newACL->size));
994     acl_FreeACL(&newACL);
995     return(0);
996
997 } /*Store_AccessList*/
998
999
1000 /* In our current implementation, each successive data store (new file
1001  * data version) creates a new inode. This function creates the new
1002  * inode, copies the old inode's contents to the new one, remove the old
1003  * inode (i.e. decrement inode count -- if it's currently used the delete
1004  * will be delayed), and modify some fields (i.e. vnode's
1005  * disk.inodeNumber and cloned)
1006  */
1007 #define COPYBUFFSIZE    8192
1008 static int CopyOnWrite(Vnode *targetptr, Volume *volptr)
1009 {
1010     Inode       ino, nearInode;
1011     int         rdlen;
1012     int         wrlen;
1013     register int size, length;
1014     int ifd, ofd;
1015     char        *buff;
1016     int         rc;             /* return code */
1017     IHandle_t   *newH;  /* Use until finished copying, then cp to vnode.*/
1018     FdHandle_t  *targFdP;  /* Source Inode file handle */
1019     FdHandle_t  *newFdP; /* Dest Inode file handle */
1020
1021     if (targetptr->disk.type == vDirectory) DFlush();   /* just in case? */
1022
1023     VN_GET_LEN(size, targetptr);
1024     buff = (char *)malloc(COPYBUFFSIZE);
1025     if (buff == NULL) {
1026         return EIO;
1027     }
1028
1029     ino = VN_GET_INO(targetptr);
1030     assert(VALID_INO(ino));
1031     targFdP = IH_OPEN(targetptr->handle);
1032     if (targFdP == NULL) {
1033         rc = errno;
1034         ViceLog(0, ("CopyOnWrite failed: Failed to open target vnode %u in volume %u (errno = %d)\n", targetptr->vnodeNumber, V_id(volptr), rc));
1035         free(buff);
1036         VTakeOffline (volptr);
1037         return rc;
1038     }
1039
1040     nearInode = VN_GET_INO(targetptr);
1041     ino = IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1042                     VPartitionPath(V_partition(volptr)),nearInode, V_id(volptr),
1043                     targetptr->vnodeNumber, targetptr->disk.uniquifier,
1044                     (int)targetptr->disk.dataVersion);
1045     if (!VALID_INO(ino))
1046     {
1047         ViceLog(0,("CopyOnWrite failed: Partition %s that contains volume %u may be out of free inodes(errno = %d)\n", volptr->partition->name, V_id(volptr), errno));
1048         FDH_CLOSE(targFdP);
1049         free(buff);
1050         return ENOSPC;
1051     }
1052     IH_INIT(newH, V_device(volptr), V_id(volptr), ino);
1053     newFdP = IH_OPEN(newH);
1054     assert(newFdP != NULL);
1055
1056     while(size > 0) {
1057         if (size > COPYBUFFSIZE) { /* more than a buffer */
1058             length = COPYBUFFSIZE;
1059             size -= COPYBUFFSIZE;
1060         } else {
1061             length = size;
1062             size = 0;
1063         }
1064         rdlen = FDH_READ(targFdP, buff, length); 
1065         if (rdlen == length)
1066             wrlen = FDH_WRITE(newFdP, buff, length);
1067         else
1068             wrlen = 0;
1069         /*  Callers of this function are not prepared to recover
1070          *  from error that put the filesystem in an inconsistent
1071          *  state. Make sure that we force the volume off-line if
1072          *  we some error other than ENOSPC - 4.29.99)
1073          *
1074          *  In case we are unable to write the required bytes, and the
1075          *  error code indicates that the disk is full, we roll-back to
1076          *  the initial state.
1077          */
1078         if((rdlen != length) || (wrlen != length))
1079                 if ( (wrlen < 0) && (errno == ENOSPC) ) /* disk full */
1080                 {
1081                         ViceLog(0,("CopyOnWrite failed: Partition %s containing volume %u is full\n",
1082                                         volptr->partition->name, V_id(volptr)));
1083                         /* remove destination inode which was partially copied till now*/
1084                         FDH_REALLYCLOSE(newFdP);
1085                         IH_RELEASE(newH);
1086                         FDH_REALLYCLOSE(targFdP);
1087                         rc = IH_DEC(V_linkHandle(volptr), ino,
1088                                   V_parentId(volptr));
1089                         if (!rc ) {
1090                             ViceLog(0,("CopyOnWrite failed: error %u after i_dec on disk full, volume %u in partition %s needs salvage\n",
1091                                        rc, V_id(volptr), 
1092                                        volptr->partition->name));
1093                             VTakeOffline (volptr);
1094                         }
1095                         free(buff);
1096                         return ENOSPC;
1097                 }
1098                 else {
1099                     ViceLog(0,("CopyOnWrite failed: volume %u in partition %s  (tried reading %u, read %u, wrote %u, errno %u) volume needs salvage\n",
1100                                V_id(volptr), volptr->partition->name, length,
1101                                rdlen, wrlen, errno));
1102 #ifdef FAST_RESTART /* if running in no-salvage, don't core the server */
1103                     ViceLog(0,("CopyOnWrite failed: taking volume offline\n"));
1104 #else /* Avoid further corruption and try to get a core. */
1105                     assert(0); 
1106 #endif
1107                     /* Decrement this inode so salvager doesn't find it. */
1108                     FDH_REALLYCLOSE(newFdP);
1109                     IH_RELEASE(newH);
1110                     FDH_REALLYCLOSE(targFdP);
1111                     rc = IH_DEC(V_linkHandle(volptr), ino,
1112                                 V_parentId(volptr));
1113                     free(buff);
1114                     VTakeOffline (volptr);
1115                     return EIO;
1116                 }
1117 #ifndef AFS_PTHREAD_ENV
1118         IOMGR_Poll();
1119 #endif /* !AFS_PTHREAD_ENV */
1120     }
1121     FDH_REALLYCLOSE(targFdP);
1122     rc = IH_DEC(V_linkHandle(volptr), VN_GET_INO(targetptr),
1123               V_parentId(volptr)) ;
1124     assert(!rc);
1125     IH_RELEASE(targetptr->handle);
1126
1127     rc = FDH_SYNC(newFdP);
1128     assert(rc == 0);
1129     FDH_CLOSE(newFdP);
1130     targetptr->handle = newH;
1131     VN_SET_INO(targetptr, ino);
1132     targetptr->disk.cloned = 0;
1133     /* Internal change to vnode, no user level change to volume - def 5445 */
1134     targetptr->changed_oldTime = 1;
1135     free(buff);
1136     return 0;                           /* success */
1137 } /*CopyOnWrite*/
1138
1139
1140 /*
1141  * Common code to handle with removing the Name (file when it's called from
1142  * SAFS_RemoveFile() or an empty dir when called from SAFS_rmdir()) from a
1143  * given directory, parentptr.
1144  */
1145 int DT1=0, DT0=0;
1146 static afs_int32
1147 DeleteTarget(Vnode *parentptr,
1148              Volume *volptr,
1149              Vnode **targetptr,
1150              DirHandle *dir,
1151              AFSFid *fileFid,
1152              char *Name,
1153              int ChkForDir)
1154 {
1155     DirHandle childdir;     /* Handle for dir package I/O */
1156     int errorCode = 0;
1157     int code;
1158
1159     /* watch for invalid names */
1160     if (!strcmp(Name, ".") || !strcmp(Name, ".."))
1161         return (EINVAL);
1162     if (parentptr->disk.cloned) 
1163     {
1164         ViceLog(25, ("DeleteTarget : CopyOnWrite called\n"));
1165         if ((errorCode = CopyOnWrite(parentptr, volptr)))
1166         {
1167                 ViceLog(20, ("DeleteTarget %s: CopyOnWrite failed %d\n",Name,errorCode));
1168                 return errorCode;
1169         }
1170     }
1171
1172     /* check that the file is in the directory */
1173     SetDirHandle(dir, parentptr);
1174     if (Lookup(dir, Name, fileFid))
1175         return(ENOENT);
1176     fileFid->Volume = V_id(volptr);
1177
1178     /* just-in-case check for something causing deadlock */
1179     if (fileFid->Vnode == parentptr->vnodeNumber)
1180         return(EINVAL);
1181
1182     *targetptr = VGetVnode(&errorCode, volptr, fileFid->Vnode, WRITE_LOCK);
1183     if (errorCode) {
1184         return (errorCode);
1185     }
1186     if (ChkForDir == MustBeDIR) {
1187         if ((*targetptr)->disk.type != vDirectory)
1188             return(ENOTDIR);
1189     } else if ((*targetptr)->disk.type == vDirectory)
1190         return(EISDIR);
1191     
1192     /*assert((*targetptr)->disk.uniquifier == fileFid->Unique);*/
1193     /**
1194       * If the uniquifiers dont match then instead of asserting
1195       * take the volume offline and return VSALVAGE
1196       */
1197     if ( (*targetptr)->disk.uniquifier != fileFid->Unique ) {
1198         VTakeOffline(volptr);
1199         errorCode = VSALVAGE;
1200         return errorCode;
1201     }
1202         
1203     if (ChkForDir == MustBeDIR) {
1204         SetDirHandle(&childdir, *targetptr);
1205         if (IsEmpty(&childdir) != 0)
1206             return(EEXIST);
1207         DZap(&childdir);
1208         (*targetptr)->delete = 1;
1209     } else if ((--(*targetptr)->disk.linkCount) == 0) 
1210         (*targetptr)->delete = 1;
1211     if ((*targetptr)->delete) {
1212         if (VN_GET_INO(*targetptr)) {
1213             DT0++;
1214             IH_REALLYCLOSE((*targetptr)->handle);
1215             errorCode = IH_DEC(V_linkHandle(volptr),
1216                              VN_GET_INO(*targetptr),
1217                              V_parentId(volptr));
1218             IH_RELEASE((*targetptr)->handle);
1219             if (errorCode == -1) {
1220                 ViceLog(0, ("DT: inode=%s, name=%s, errno=%d\n",
1221                             PrintInode(NULL, VN_GET_INO(*targetptr)),
1222                             Name, errno));
1223 #ifdef  AFS_DEC_ENV
1224                 if ((errno != ENOENT) && (errno != EIO) && (errno != ENXIO))
1225 #else
1226                 if (errno != ENOENT) 
1227 #endif
1228                     {
1229                     ViceLog(0, ("Volume %u now offline, must be salvaged.\n", 
1230                                 volptr->hashid));
1231                     VTakeOffline(volptr);
1232                     return (EIO);
1233                     }
1234                 DT1++;
1235                 errorCode = 0;
1236             }
1237         }
1238         VN_SET_INO(*targetptr, (Inode)0);
1239         {
1240             afs_fsize_t adjLength;
1241             VN_GET_LEN(adjLength, *targetptr);
1242             VAdjustDiskUsage(&errorCode, volptr,
1243                              -(int)nBlocks(adjLength), 0);
1244         }
1245     }
1246     
1247     (*targetptr)->changed_newTime = 1; /* Status change of deleted file/dir */
1248
1249     code = Delete(dir,(char *) Name);
1250     if (code) {
1251        ViceLog(0, ("Error %d deleting %s\n", code,
1252                    (((*targetptr)->disk.type== Directory)?"directory":"file")));
1253        ViceLog(0, ("Volume %u now offline, must be salvaged.\n", 
1254                   volptr->hashid));
1255        VTakeOffline(volptr);
1256        if (!errorCode) errorCode = code;
1257     }
1258
1259     DFlush();
1260     return(errorCode);
1261
1262 } /*DeleteTarget*/
1263
1264
1265 /*
1266  * This routine updates the parent directory's status block after the
1267  * specified operation (i.e. RemoveFile(), CreateFile(), Rename(),
1268  * SymLink(), Link(), MakeDir(), RemoveDir()) on one of its children has
1269  * been performed.
1270  */
1271 static void
1272 Update_ParentVnodeStatus(Vnode *parentptr,
1273                          Volume *volptr,
1274                          DirHandle *dir,
1275                          int author,
1276                          int linkcount,
1277 #if FS_STATS_DETAILED
1278                          char a_inSameNetwork
1279 #endif /* FS_STATS_DETAILED */
1280                          )
1281 {
1282     afs_fsize_t newlength;      /* Holds new directory length */
1283     afs_fsize_t parentLength;
1284     int errorCode;
1285 #if FS_STATS_DETAILED
1286     Date currDate;              /*Current date*/
1287     int writeIdx;               /*Write index to bump*/
1288     int timeIdx;                /*Authorship time index to bump*/
1289 #endif /* FS_STATS_DETAILED */
1290
1291     parentptr->disk.dataVersion++;
1292     newlength = Length(dir);
1293     /* 
1294      * This is a called on both dir removals (i.e. remove, removedir, rename) but also in dir additions
1295      * (create, symlink, link, makedir) so we need to check if we have enough space
1296      * XXX But we still don't check the error since we're dealing with dirs here and really the increase
1297      * of a new entry would be too tiny to worry about failures (since we have all the existing cushion)
1298      */
1299     VN_GET_LEN(parentLength, parentptr);
1300     if (nBlocks(newlength) != nBlocks(parentLength)) {
1301         VAdjustDiskUsage(&errorCode, volptr, 
1302                          (nBlocks(newlength) - nBlocks(parentLength)),
1303                          (nBlocks(newlength) - nBlocks(parentLength)));
1304     }
1305     VN_SET_LEN(parentptr, newlength);
1306
1307 #if FS_STATS_DETAILED
1308     /*
1309      * Update directory write stats for this volume.  Note that the auth
1310      * counter is located immediately after its associated ``distance''
1311      * counter.
1312      */
1313     if (a_inSameNetwork)
1314         writeIdx = VOL_STATS_SAME_NET;
1315     else
1316         writeIdx = VOL_STATS_DIFF_NET;
1317     V_stat_writes(volptr, writeIdx)++;
1318     if (author != AnonymousID) {
1319         V_stat_writes(volptr, writeIdx+1)++;
1320     }
1321
1322     /*
1323      * Update the volume's authorship information in response to this
1324      * directory operation.  Get the current time, decide to which time
1325      * slot this operation belongs, and bump the appropriate slot.
1326      */
1327     currDate = (FT_ApproxTime() - parentptr->disk.unixModifyTime);
1328     timeIdx = (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 :
1329                currDate < VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 :
1330                currDate < VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 :
1331                currDate < VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 :
1332                currDate < VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1333                VOL_STATS_TIME_IDX_5);
1334     if (parentptr->disk.author == author) {
1335         V_stat_dirSameAuthor(volptr, timeIdx)++;
1336     }
1337     else {
1338         V_stat_dirDiffAuthor(volptr, timeIdx)++;
1339     }
1340 #endif /* FS_STATS_DETAILED */
1341
1342     parentptr->disk.author = author;
1343     parentptr->disk.linkCount = linkcount;
1344     parentptr->disk.unixModifyTime = FT_ApproxTime();   /* This should be set from CLIENT!! */
1345     parentptr->disk.serverModifyTime = FT_ApproxTime();
1346     parentptr->changed_newTime = 1; /* vnode changed, write it back. */
1347 }
1348
1349
1350 /*
1351  * Update the target file's (or dir's) status block after the specified
1352  * operation is complete. Note that some other fields maybe updated by
1353  * the individual module.
1354  */
1355
1356 /* XXX INCOMPLETE - More attention is needed here! */
1357 static void
1358 Update_TargetVnodeStatus(Vnode *targetptr,
1359                          afs_uint32 Caller,
1360                          struct client *client,
1361                          AFSStoreStatus *InStatus,
1362                          Vnode *parentptr,
1363                          Volume *volptr,
1364                          afs_fsize_t length)
1365 {
1366 #if FS_STATS_DETAILED
1367     Date currDate;              /*Current date*/
1368     int writeIdx;               /*Write index to bump*/
1369     int timeIdx;                /*Authorship time index to bump*/
1370 #endif /* FS_STATS_DETAILED */
1371
1372     if (Caller & (TVS_CFILE|TVS_SLINK|TVS_MKDIR))       {   /* initialize new file */
1373         targetptr->disk.parent = parentptr->vnodeNumber;
1374         VN_SET_LEN(targetptr, length);
1375         /* targetptr->disk.group =      0;  save some cycles */
1376         targetptr->disk.modeBits = 0777;
1377         targetptr->disk.owner = client->ViceId;
1378         targetptr->disk.dataVersion =  0 ; /* consistent with the client */
1379         targetptr->disk.linkCount = (Caller & TVS_MKDIR ? 2 : 1);
1380         /* the inode was created in Alloc_NewVnode() */
1381     }
1382
1383 #if FS_STATS_DETAILED
1384     /*
1385      * Update file write stats for this volume.  Note that the auth
1386      * counter is located immediately after its associated ``distance''
1387      * counter.
1388      */
1389     if (client->InSameNetwork)
1390         writeIdx = VOL_STATS_SAME_NET;
1391     else
1392         writeIdx = VOL_STATS_DIFF_NET;
1393     V_stat_writes(volptr, writeIdx)++;
1394     if (client->ViceId != AnonymousID) {
1395         V_stat_writes(volptr, writeIdx+1)++;
1396     }
1397
1398     /*
1399      * We only count operations that DON'T involve creating new objects
1400      * (files, symlinks, directories) or simply setting status as
1401      * authorship-change operations.
1402      */
1403     if (!(Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR | TVS_SSTATUS))) {
1404         /*
1405          * Update the volume's authorship information in response to this
1406          * file operation.  Get the current time, decide to which time
1407          * slot this operation belongs, and bump the appropriate slot.
1408          */
1409         currDate = (FT_ApproxTime() - targetptr->disk.unixModifyTime);
1410         timeIdx = (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 :
1411                    currDate < VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 :
1412                    currDate < VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 :
1413                    currDate < VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 :
1414                    currDate < VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1415                    VOL_STATS_TIME_IDX_5);
1416         if (targetptr->disk.author == client->ViceId) {
1417             V_stat_fileSameAuthor(volptr, timeIdx)++;
1418         } else {
1419             V_stat_fileDiffAuthor(volptr, timeIdx)++;
1420         }
1421       }
1422 #endif /* FS_STATS_DETAILED */
1423
1424     if (!(Caller & TVS_SSTATUS))
1425       targetptr->disk.author = client->ViceId;
1426     if (Caller & TVS_SDATA) {
1427       targetptr->disk.dataVersion++;
1428       if (VanillaUser(client))
1429         {
1430           targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1431 #ifdef CREATE_SGUID_ADMIN_ONLY
1432           targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1433 #endif
1434         }
1435     }
1436     if (Caller & TVS_SSTATUS) { /* update time on non-status change */
1437         /* store status, must explicitly request to change the date */
1438         if (InStatus->Mask & AFS_SETMODTIME)
1439             targetptr->disk.unixModifyTime = InStatus->ClientModTime;
1440     }
1441     else {/* other: date always changes, but perhaps to what is specified by caller */
1442         targetptr->disk.unixModifyTime = (InStatus->Mask & AFS_SETMODTIME ? InStatus->ClientModTime : FT_ApproxTime());
1443     }
1444     if (InStatus->Mask & AFS_SETOWNER) {
1445         /* admin is allowed to do chmod, chown as well as chown, chmod. */
1446         if (VanillaUser(client))
1447           {
1448             targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1449 #ifdef CREATE_SGUID_ADMIN_ONLY
1450             targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1451 #endif
1452           }
1453         targetptr->disk.owner = InStatus->Owner;
1454         if (VolumeRootVnode (targetptr)) {
1455             Error errorCode = 0;        /* what should be done with this? */
1456
1457             V_owner(targetptr->volumePtr) = InStatus->Owner;
1458             VUpdateVolume(&errorCode, targetptr->volumePtr);
1459         }
1460     }
1461     if (InStatus->Mask & AFS_SETMODE) {
1462         int modebits = InStatus->UnixModeBits;
1463 #define CREATE_SGUID_ADMIN_ONLY 1
1464 #ifdef CREATE_SGUID_ADMIN_ONLY
1465         if (VanillaUser(client)) 
1466             modebits = modebits & 0777;
1467 #endif
1468         if (VanillaUser(client)) {
1469           targetptr->disk.modeBits = modebits;
1470         }
1471         else {
1472           targetptr->disk.modeBits = modebits;
1473           switch ( Caller ) {
1474           case TVS_SDATA: osi_audit( PrivSetID, 0, AUD_INT, client->ViceId,
1475                                     AUD_INT, CHK_STOREDATA, AUD_END); break;
1476           case TVS_CFILE:
1477           case TVS_SSTATUS: osi_audit( PrivSetID, 0, AUD_INT, client->ViceId,
1478                                     AUD_INT, CHK_STORESTATUS, AUD_END); break;
1479           default: break;
1480           }
1481         }
1482       }
1483     targetptr->disk.serverModifyTime = FT_ApproxTime();
1484     if (InStatus->Mask & AFS_SETGROUP)
1485         targetptr->disk.group = InStatus->Group;
1486     /* vnode changed : to be written back by VPutVnode */
1487     targetptr->changed_newTime = 1;
1488
1489 } /*Update_TargetVnodeStatus*/
1490
1491
1492 /*
1493  * Fills the CallBack structure with the expiration time and type of callback
1494  * structure. Warning: this function is currently incomplete.
1495  */
1496 static void
1497 SetCallBackStruct(afs_uint32 CallBackTime, struct AFSCallBack *CallBack)
1498 {
1499     /* CallBackTime could not be 0 */
1500     if (CallBackTime == 0) {
1501         ViceLog(0, ("WARNING: CallBackTime == 0!\n"));
1502         CallBack->ExpirationTime = 0;
1503     } else
1504         CallBack->ExpirationTime = CallBackTime - FT_ApproxTime();      
1505     CallBack->CallBackVersion = CALLBACK_VERSION;
1506     CallBack->CallBackType = CB_SHARED;             /* The default for now */
1507
1508 } /*SetCallBackStruct*/
1509
1510
1511 /*
1512  * Adjusts (Subtract) "length" number of blocks from the volume's disk
1513  * allocation; if some error occured (exceeded volume quota or partition
1514  * was full, or whatever), it frees the space back and returns the code.
1515  * We usually pre-adjust the volume space to make sure that there's
1516  * enough space before consuming some.
1517  */
1518 static afs_int32
1519 AdjustDiskUsage(Volume *volptr, afs_int32 length, afs_int32 checkLength)
1520 {
1521     int rc;
1522     int nc;
1523
1524     VAdjustDiskUsage(&rc, volptr, length, checkLength);
1525     if (rc) {
1526         VAdjustDiskUsage(&nc, volptr, -length, 0);
1527         if (rc == VOVERQUOTA) {
1528             ViceLog(2,("Volume %u (%s) is full\n",
1529                     V_id(volptr), V_name(volptr)));
1530             return(rc);
1531         }
1532         if (rc == VDISKFULL) {
1533             ViceLog(0,("Partition %s that contains volume %u is full\n",
1534                     volptr->partition->name, V_id(volptr)));
1535             return(rc);
1536         }
1537         ViceLog(0,("Got error return %d from VAdjustDiskUsage\n",rc));
1538         return(rc);
1539     }
1540     return(0);
1541
1542 } /*AdjustDiskUsage*/
1543
1544 /*
1545  * Common code that handles the creation of a new file (SAFS_CreateFile and
1546  * SAFS_Symlink) or a new dir (SAFS_MakeDir)
1547  */
1548 static afs_int32
1549 Alloc_NewVnode(Vnode *parentptr,
1550                DirHandle *dir,
1551                Volume *volptr,
1552                Vnode **targetptr,
1553                char *Name,
1554                struct AFSFid *OutFid,
1555                int FileType,
1556                int BlocksPreallocatedForVnode)
1557 {
1558     int errorCode = 0;          /* Error code returned back */
1559     int temp;
1560     Inode inode=0;
1561     Inode nearInode;            /* hint for inode allocation in solaris */
1562
1563     if ((errorCode = AdjustDiskUsage(volptr, BlocksPreallocatedForVnode,
1564                                     BlocksPreallocatedForVnode))) {
1565         ViceLog(25, ("Insufficient space to allocate %d blocks\n", 
1566                      BlocksPreallocatedForVnode));
1567         return(errorCode);
1568     }
1569
1570     *targetptr = VAllocVnode(&errorCode, volptr, FileType);
1571     if (errorCode != 0) {
1572         VAdjustDiskUsage(&temp, volptr, - BlocksPreallocatedForVnode, 0);
1573         return(errorCode);
1574     }
1575     OutFid->Volume = V_id(volptr);
1576     OutFid->Vnode = (*targetptr)->vnodeNumber;
1577     OutFid->Unique = (*targetptr)->disk.uniquifier;
1578
1579     nearInode = VN_GET_INO(parentptr);   /* parent is also in same vol */
1580
1581     /* create the inode now itself */
1582     inode = IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1583                       VPartitionPath(V_partition(volptr)), nearInode,
1584                       V_id(volptr), (*targetptr)->vnodeNumber,
1585                       (*targetptr)->disk.uniquifier, 1);
1586
1587     /* error in creating inode */
1588     if (!VALID_INO(inode)) 
1589     {
1590                ViceLog(0, ("Volume : %d vnode = %d Failed to create inode: errno = %d\n", 
1591                          (*targetptr)->volumePtr->header->diskstuff.id,
1592                          (*targetptr)->vnodeNumber, 
1593                          errno));
1594                 VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode,0);
1595                 (*targetptr)->delete = 1; /* delete vnode */
1596                 return ENOSPC;
1597     }
1598     VN_SET_INO(*targetptr, inode);
1599     IH_INIT(((*targetptr)->handle), V_device(volptr), V_id(volptr), inode);
1600
1601     /* copy group from parent dir */
1602     (*targetptr)->disk.group = parentptr->disk.group;
1603
1604     if (parentptr->disk.cloned) 
1605     {
1606         ViceLog(25, ("Alloc_NewVnode : CopyOnWrite called\n"));
1607         if ((errorCode = CopyOnWrite(parentptr, volptr)))  /* disk full */
1608         {
1609                 ViceLog(25, ("Alloc_NewVnode : CopyOnWrite failed\n"));
1610                 /* delete the vnode previously allocated */
1611                 (*targetptr)->delete = 1;
1612                 VAdjustDiskUsage(&temp, volptr,
1613                                  -BlocksPreallocatedForVnode, 0);
1614                 IH_REALLYCLOSE((*targetptr)->handle);
1615                 if ( IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)) )
1616                     ViceLog(0,("Alloc_NewVnode: partition %s idec %s failed\n",
1617                                 volptr->partition->name,
1618                                PrintInode(NULL, inode)));
1619                 IH_RELEASE((*targetptr)->handle);
1620                         
1621                 return errorCode;
1622         }
1623     }
1624     
1625     /* add the name to the directory */
1626     SetDirHandle(dir, parentptr);
1627     if ((errorCode = Create(dir,(char *)Name, OutFid))) {
1628         (*targetptr)->delete = 1;
1629         VAdjustDiskUsage(&temp, volptr, - BlocksPreallocatedForVnode, 0);
1630         IH_REALLYCLOSE((*targetptr)->handle);
1631         if ( IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1632             ViceLog(0,("Alloc_NewVnode: partition %s idec %s failed\n",
1633                        volptr->partition->name,
1634                        PrintInode(NULL, inode)));
1635         IH_RELEASE((*targetptr)->handle);
1636         return(errorCode);
1637     }
1638     DFlush();
1639     return(0);
1640
1641 } /*Alloc_NewVnode*/
1642
1643
1644 /*
1645  * Handle all the lock-related code (SAFS_SetLock, SAFS_ExtendLock and
1646  * SAFS_ReleaseLock)
1647  */
1648 static afs_int32
1649 HandleLocking(Vnode *targetptr, afs_int32 rights, ViceLockType LockingType)
1650 {
1651     int Time;           /* Used for time */
1652     int writeVnode = targetptr->changed_oldTime; /* save original status */
1653
1654     /* Does the caller has Lock priviledges; root extends locks, however */
1655     if (LockingType != LockExtend && !(rights & PRSFS_LOCK))
1656         return(EACCES);
1657     targetptr->changed_oldTime = 1; /* locking doesn't affect any time stamp */
1658     Time = FT_ApproxTime();
1659     switch (LockingType) {
1660         case LockRead:
1661         case LockWrite:
1662             if (Time > targetptr->disk.lock.lockTime)
1663                 targetptr->disk.lock.lockTime = targetptr->disk.lock.lockCount = 0;
1664             Time += AFS_LOCKWAIT;
1665             if (LockingType == LockRead) {
1666                 if (targetptr->disk.lock.lockCount >= 0) {
1667                     ++(targetptr->disk.lock.lockCount);
1668                     targetptr->disk.lock.lockTime = Time;
1669                 } else return(EAGAIN);
1670             } else {
1671                 if (targetptr->disk.lock.lockCount == 0) {
1672                     targetptr->disk.lock.lockCount = -1;
1673                     targetptr->disk.lock.lockTime = Time;
1674                 } else return(EAGAIN);
1675             }
1676             break;
1677         case LockExtend:
1678             Time += AFS_LOCKWAIT;
1679             if (targetptr->disk.lock.lockCount != 0)
1680                 targetptr->disk.lock.lockTime = Time;
1681             else return(EINVAL);            
1682             break;
1683         case LockRelease:
1684             if ((--targetptr->disk.lock.lockCount) <= 0)
1685                 targetptr->disk.lock.lockCount = targetptr->disk.lock.lockTime = 0;
1686             break;
1687         default:
1688             targetptr->changed_oldTime = writeVnode; /* restore old status */
1689             ViceLog(0, ("Illegal Locking type %d\n", LockingType));
1690     }
1691     return(0);
1692 } /*HandleLocking*/
1693
1694 /* Checks if caller has the proper AFS and Unix (WRITE) access permission to the target directory; Prfs_Mode refers to the AFS Mode operation while rights contains the caller's access permissions to the directory. */
1695
1696 static afs_int32
1697 CheckWriteMode(Vnode *targetptr, afs_int32 rights, int Prfs_Mode)
1698 {
1699     if (readonlyServer)
1700         return(VREADONLY);
1701     if (!(rights & Prfs_Mode))
1702         return(EACCES);
1703     if ((targetptr->disk.type != vDirectory) && (!(targetptr->disk.modeBits & OWNERWRITE)))
1704         return(EACCES);
1705     return(0);
1706 }
1707
1708 /*
1709  * If some flags (i.e. min or max quota) are set, the volume's in disk
1710  * label is updated; Name, OfflineMsg, and Motd are also reflected in the
1711  * update, if applicable.
1712  */
1713 static afs_int32
1714 RXUpdate_VolumeStatus(Volume *volptr, AFSStoreVolumeStatus* StoreVolStatus,
1715                       char *Name, char *OfflineMsg, char *Motd)
1716 {
1717     Error errorCode = 0;
1718
1719     if (StoreVolStatus->Mask & AFS_SETMINQUOTA)
1720         V_minquota(volptr) = StoreVolStatus->MinQuota;
1721     if (StoreVolStatus->Mask & AFS_SETMAXQUOTA)
1722         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
1723     if (strlen(OfflineMsg) > 0) {
1724         strcpy(V_offlineMessage(volptr), OfflineMsg);
1725     }
1726     if (strlen(Name) > 0) {
1727         strcpy(V_name(volptr), Name);
1728     }
1729 #if OPENAFS_VOL_STATS
1730     /*
1731      * We don't overwrite the motd field, since it's now being used
1732      * for stats
1733      */
1734 #else
1735     if (strlen(Motd) > 0) {
1736         strcpy(V_motd(volptr), Motd);
1737     }
1738 #endif /* FS_STATS_DETAILED */
1739     VUpdateVolume(&errorCode, volptr);
1740     return(errorCode);
1741
1742 } /*RXUpdate_VolumeStatus*/
1743
1744
1745 /* old interface */
1746 static afs_int32
1747 Update_VolumeStatus(Volume *volptr, VolumeStatus *StoreVolStatus,
1748                     struct BBS *Name, struct BBS *OfflineMsg,
1749                     struct BBS *Motd)
1750 {
1751     Error errorCode = 0;
1752
1753     if (StoreVolStatus->MinQuota > -1)
1754         V_minquota(volptr) = StoreVolStatus->MinQuota;
1755     if (StoreVolStatus->MaxQuota > -1)
1756         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
1757     if (OfflineMsg->SeqLen > 1)
1758         strcpy(V_offlineMessage(volptr), OfflineMsg->SeqBody);
1759     if (Name->SeqLen > 1)
1760         strcpy(V_name(volptr), Name->SeqBody);
1761 #if OPENAFS_VOL_STATS
1762     /*
1763      * We don't overwrite the motd field, since it's now being used
1764      * for stats
1765      */
1766 #else
1767     if (Motd->SeqLen > 1)
1768         strcpy(V_motd(volptr), Motd->SeqBody);
1769 #endif /* FS_STATS_DETAILED */
1770     VUpdateVolume(&errorCode, volptr);
1771     return(errorCode);
1772
1773 } /*Update_VolumeStatus*/
1774
1775
1776 /*
1777  * Get internal volume-related statistics from the Volume disk label
1778  * structure and put it into the VolumeStatus structure, status; it's
1779  * used by both SAFS_GetVolumeStatus and SAFS_SetVolumeStatus to return
1780  * the volume status to the caller.
1781  */
1782 static afs_int32
1783 GetVolumeStatus(VolumeStatus *status, struct BBS *name, struct BBS *offMsg,
1784                 struct BBS *motd, Volume *volptr)
1785 {
1786     status->Vid = V_id(volptr);
1787     status->ParentId = V_parentId(volptr);
1788     status->Online = V_inUse(volptr);
1789     status->InService = V_inService(volptr);
1790     status->Blessed = V_blessed(volptr);
1791     status->NeedsSalvage = V_needsSalvaged(volptr);
1792     if (VolumeWriteable(volptr))
1793         status->Type = ReadWrite;
1794     else
1795         status->Type = ReadOnly;
1796     status->MinQuota = V_minquota(volptr);
1797     status->MaxQuota = V_maxquota(volptr);
1798     status->BlocksInUse = V_diskused(volptr);
1799     status->PartBlocksAvail = volptr->partition->free;
1800     status->PartMaxBlocks = volptr->partition->totalUsable;
1801     strncpy(name->SeqBody, V_name(volptr), (int)name->MaxSeqLen);
1802     name->SeqLen = strlen(V_name(volptr)) + 1;
1803     if (name->SeqLen > name->MaxSeqLen) name->SeqLen = name -> MaxSeqLen;
1804     strncpy(offMsg->SeqBody, V_offlineMessage(volptr), (int)name->MaxSeqLen);
1805     offMsg->SeqLen = strlen(V_offlineMessage(volptr)) + 1;
1806     if (offMsg->SeqLen > offMsg->MaxSeqLen)
1807         offMsg->SeqLen = offMsg -> MaxSeqLen;
1808 #ifdef notdef
1809     /*Don't do anything with the motd field*/
1810     strncpy(motd->SeqBody, nullString, (int)offMsg->MaxSeqLen);
1811     motd->SeqLen = strlen(nullString) + 1;
1812 #endif
1813     if (motd->SeqLen > motd->MaxSeqLen)
1814         motd->SeqLen = motd -> MaxSeqLen;
1815
1816 } /*GetVolumeStatus*/
1817
1818 static afs_int32
1819 RXGetVolumeStatus(AFSFetchVolumeStatus *status, char **name, char **offMsg,
1820                   char **motd, Volume *volptr)
1821 {
1822     int temp;
1823
1824     status->Vid = V_id(volptr);
1825     status->ParentId = V_parentId(volptr);
1826     status->Online = V_inUse(volptr);
1827     status->InService = V_inService(volptr);
1828     status->Blessed = V_blessed(volptr);
1829     status->NeedsSalvage = V_needsSalvaged(volptr);
1830     if (VolumeWriteable(volptr))
1831         status->Type = ReadWrite;
1832     else
1833         status->Type = ReadOnly;
1834     status->MinQuota = V_minquota(volptr);
1835     status->MaxQuota = V_maxquota(volptr);
1836     status->BlocksInUse = V_diskused(volptr);
1837     status->PartBlocksAvail = volptr->partition->free;
1838     status->PartMaxBlocks = volptr->partition->totalUsable;
1839
1840     /* now allocate and copy these things; they're freed by the RXGEN stub */
1841     temp = strlen(V_name(volptr)) + 1;
1842     *name = malloc(temp);
1843     if (!*name) {
1844         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1845         assert(0);
1846     }
1847     strcpy(*name, V_name(volptr));
1848     temp = strlen(V_offlineMessage(volptr)) + 1;
1849     *offMsg = malloc(temp);
1850     if (!*offMsg) {
1851         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1852         assert(0);
1853     }
1854     strcpy(*offMsg, V_offlineMessage(volptr));
1855 #if OPENAFS_VOL_STATS
1856     *motd = malloc(1);
1857     if (!*motd) {
1858         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1859         assert(0);
1860     }
1861     strcpy(*motd, nullString);
1862 #else
1863     temp = strlen(V_motd(volptr)) + 1;
1864     *motd = malloc(temp);
1865     if (!*motd) {
1866         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1867         assert(0);
1868     }
1869     strcpy(*motd, V_motd(volptr));
1870 #endif /* FS_STATS_DETAILED */
1871
1872 } /*RXGetVolumeStatus*/
1873
1874
1875 static afs_int32
1876 FileNameOK(register char *aname)
1877 {
1878     register afs_int32 i, tc;
1879     i = strlen(aname);
1880     if (i >= 4) {
1881         /* watch for @sys on the right */
1882         if (strcmp(aname+i-4, "@sys") == 0) return 0;
1883     }
1884     while ((tc = *aname++)) {
1885         if (tc == '/') return 0;    /* very bad character to encounter */
1886     }
1887     return 1;   /* file name is ok */
1888
1889 } /*FileNameOK*/
1890
1891
1892 /* Debugging tool to print Volume Statu's contents */
1893 static void
1894 PrintVolumeStatus(VolumeStatus *status)
1895 {
1896     ViceLog(5,("Volume header contains:\n"));
1897     ViceLog(5,("Vid = %u, Parent = %u, Online = %d, InService = %d, Blessed = %d, NeedsSalvage = %d\n",
1898             status->Vid, status->ParentId, status->Online, status->InService,
1899             status->Blessed, status->NeedsSalvage));
1900     ViceLog(5,("MinQuota = %d, MaxQuota = %d\n", status->MinQuota, status->MaxQuota));
1901     ViceLog(5,("Type = %d, BlocksInUse = %d, PartBlocksAvail = %d, PartMaxBlocks = %d\n",
1902             status->Type, status->BlocksInUse, status->PartBlocksAvail, status->PartMaxBlocks));
1903
1904 } /*PrintVolumeStatus*/
1905
1906
1907 /*
1908  * This variant of symlink is expressly to support the AFS/DFS translator
1909  * and is not supported by the AFS fileserver. We just return EINVAL.
1910  * The cache manager should not generate this call to an AFS cache manager.
1911  */
1912 afs_int32 SRXAFS_DFSSymlink (struct rx_call *acall,
1913                              struct AFSFid *DirFid,
1914                              char *Name,
1915                              char *LinkContents,
1916                              struct AFSStoreStatus *InStatus,
1917                              struct AFSFid *OutFid,
1918                              struct AFSFetchStatus *OutFidStatus,
1919                              struct AFSFetchStatus *OutDirStatus,
1920                              struct AFSCallBack *CallBack,
1921                              struct AFSVolSync *Sync)
1922 {
1923     return EINVAL;
1924 }
1925
1926 afs_int32 SRXAFS_ResidencyCmd (struct rx_call *acall, struct AFSFid *Fid,
1927                                struct ResidencyCmdInputs *Inputs,
1928                                struct ResidencyCmdOutputs *Outputs)
1929 {
1930     return EINVAL;
1931 }
1932
1933 static struct afs_buffer {
1934     struct afs_buffer *next;
1935 } *freeBufferList = 0;
1936 static int afs_buffersAlloced = 0;
1937
1938 static FreeSendBuffer(register struct afs_buffer *adata)
1939 {
1940     FS_LOCK
1941     afs_buffersAlloced--;
1942     adata->next = freeBufferList;
1943     freeBufferList = adata;
1944     FS_UNLOCK
1945     return 0;
1946
1947 } /*FreeSendBuffer*/
1948
1949 /* allocate space for sender */
1950 static char *AllocSendBuffer()
1951 {
1952     register struct afs_buffer *tp;
1953
1954     FS_LOCK
1955     afs_buffersAlloced++;
1956     if (!freeBufferList) {
1957         char *tmp;
1958         FS_UNLOCK
1959
1960         tmp = malloc(sendBufSize);
1961         if (!tmp) {
1962             ViceLog(0, ("Failed malloc in AllocSendBuffer\n"));
1963             assert(0);
1964         }
1965         return tmp;
1966     }
1967     tp = freeBufferList;
1968     freeBufferList = tp->next;
1969     FS_UNLOCK
1970     return (char *) tp;
1971
1972 } /*AllocSendBuffer*/
1973
1974 /*
1975  * This routine returns the status info associated with the targetptr vnode
1976  * in the AFSFetchStatus structure.  Some of the newer fields, such as
1977  * SegSize and Group are not yet implemented
1978  */
1979 static 
1980 void GetStatus(Vnode *targetptr,
1981                AFSFetchStatus *status,
1982                afs_int32 rights,
1983                afs_int32 anyrights,
1984                Vnode *parentptr)
1985 {
1986     /* initialize return status from a vnode  */
1987     status->InterfaceVersion = 1;
1988     status->SyncCounter = status->dataVersionHigh = status->lockCount =
1989     status->errorCode = 0;
1990     status->ResidencyMask = 1; /* means for MR-AFS: file in /vicepr-partition */
1991     if (targetptr->disk.type == vFile)
1992         status->FileType = File;
1993     else if (targetptr->disk.type == vDirectory)
1994         status->FileType = Directory;
1995     else if (targetptr->disk.type == vSymlink)
1996         status->FileType = SymbolicLink;
1997     else
1998         status->FileType = Invalid;                     /*invalid type field */
1999     status->LinkCount = targetptr->disk.linkCount;
2000     {
2001         afs_fsize_t targetLen;
2002         VN_GET_LEN(targetLen, targetptr);
2003         SplitOffsetOrSize(targetLen, status->Length_hi, status->Length);
2004     }
2005     status->DataVersion = targetptr->disk.dataVersion;
2006     status->Author = targetptr->disk.author;
2007     status->Owner = targetptr->disk.owner;
2008     status->CallerAccess = rights;
2009     status->AnonymousAccess = anyrights;
2010     status->UnixModeBits = targetptr->disk.modeBits;
2011     status->ClientModTime = targetptr->disk.unixModifyTime;     /* This might need rework */
2012     status->ParentVnode = (status->FileType == Directory ? targetptr->vnodeNumber : parentptr->vnodeNumber);
2013     status->ParentUnique = (status->FileType == Directory ? targetptr->disk.uniquifier : parentptr->disk.uniquifier);
2014     status->ServerModTime = targetptr->disk.serverModifyTime;                   
2015     status->Group = targetptr->disk.group;
2016     status->lockCount = targetptr->disk.lock.lockCount;
2017     status->errorCode = 0;
2018
2019 } /*GetStatus*/
2020
2021 static
2022 afs_int32 common_FetchData64 (struct rx_call *acall, 
2023                               struct AFSFid *Fid,    
2024                               afs_int32 Pos,         
2025                               afs_int32 Len,         
2026                               struct AFSFetchStatus *OutStatus,
2027                               struct AFSCallBack *CallBack,
2028                               struct AFSVolSync *Sync,
2029                               int type)              
2030
2031     Vnode * targetptr = 0;                  /* pointer to vnode to fetch */
2032     Vnode * parentwhentargetnotdir = 0;     /* parent vnode if vptr is a file */
2033     Vnode   tparentwhentargetnotdir;        /* parent vnode for GetStatus */
2034     int     errorCode = 0;                  /* return code to caller */
2035     int     fileCode =  0;                  /* return code from vol package */
2036     Volume * volptr = 0;                    /* pointer to the volume */
2037     struct client *client;                  /* pointer to the client data */
2038     struct rx_connection *tcon;             /* the connection we're part of */
2039     afs_int32 rights, anyrights;                    /* rights for this and any user */
2040     struct client *t_client;                /* tmp ptr to client data */
2041     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
2042 #if FS_STATS_DETAILED
2043     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2044     struct fs_stats_xferData *xferP;        /* Ptr to this op's byte size struct */
2045     struct timeval opStartTime,
2046                    opStopTime;              /* Start/stop times for RPC op*/
2047     struct timeval xferStartTime,
2048                    xferStopTime;            /* Start/stop times for xfer portion*/
2049     struct timeval elapsedTime;             /* Transfer time */
2050     afs_int32 bytesToXfer;                          /* # bytes to xfer*/
2051     afs_int32 bytesXferred;                         /* # bytes actually xferred*/
2052     int readIdx;                            /* Index of read stats array to bump*/
2053     static afs_int32 tot_bytesXferred; /* shared access protected by FS_LOCK */
2054
2055     /*
2056      * Set our stats pointers, remember when the RPC operation started, and
2057      * tally the operation.
2058      */
2059     opP   = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHDATA]);
2060     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_FETCHDATA]);
2061     FS_LOCK
2062     (opP->numOps)++;
2063     FS_UNLOCK
2064     TM_GetTimeOfDay(&opStartTime, 0);
2065 #endif /* FS_STATS_DETAILED */
2066
2067     ViceLog(1,("SRXAFS_FetchData, Fid = %u.%d.%d\n",
2068             Fid->Volume, Fid->Vnode, Fid->Unique));     
2069     FS_LOCK
2070     AFSCallStats.FetchData++, AFSCallStats.TotalCalls++;
2071     FS_UNLOCK
2072
2073     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon))
2074         goto Bad_FetchData;
2075
2076     /* Get ptr to client data for user Id for logging */
2077     t_client = (struct client *)  rx_GetSpecific(tcon, rxcon_client_key);
2078     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2079     ViceLog(5,("SRXAFS_FetchData, Fid = %u.%d.%d, Host %s, Id %d\n",
2080             Fid->Volume, Fid->Vnode, Fid->Unique,
2081             inet_ntoa(logHostAddr), t_client->ViceId)); 
2082     /*
2083      * Get volume/vnode for the fetched file; caller's access rights to
2084      * it are also returned
2085      */
2086     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2087                                      DONTCHECK, &parentwhentargetnotdir,
2088                                      &client, READ_LOCK, &rights, &anyrights)))
2089         goto Bad_FetchData;
2090
2091     SetVolumeSync(Sync, volptr);
2092
2093 #if FS_STATS_DETAILED
2094     /*
2095      * Remember that another read operation was performed.
2096      */
2097     FS_LOCK
2098     if (client->InSameNetwork)
2099         readIdx = VOL_STATS_SAME_NET;
2100     else
2101         readIdx = VOL_STATS_DIFF_NET;
2102     V_stat_reads(volptr, readIdx)++;
2103     if (client->ViceId != AnonymousID) {
2104         V_stat_reads(volptr, readIdx+1)++;
2105     }
2106     FS_UNLOCK
2107 #endif /* FS_STATS_DETAILED */
2108
2109     /* Check whether the caller has permission access to fetch the data */
2110     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2111                                            CHK_FETCHDATA, 0))) 
2112         goto Bad_FetchData;
2113
2114     /*
2115      * Drop the read lock on the parent directory after saving the parent
2116      * vnode information we need to pass to GetStatus
2117      */
2118     if (parentwhentargetnotdir != NULL) {
2119         tparentwhentargetnotdir = *parentwhentargetnotdir;
2120         VPutVnode(&fileCode, parentwhentargetnotdir);
2121         assert(!fileCode || (fileCode == VSALVAGE));
2122         parentwhentargetnotdir = NULL;
2123     }
2124
2125 #if FS_STATS_DETAILED
2126     /*
2127      * Remember when the data transfer started.
2128      */
2129     TM_GetTimeOfDay(&xferStartTime, 0);
2130 #endif /* FS_STATS_DETAILED */
2131
2132     /* actually do the data transfer */
2133 #if FS_STATS_DETAILED
2134     errorCode = FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type,
2135                                   &bytesToXfer, &bytesXferred);
2136 #else
2137     if ((errorCode = FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type)))
2138         goto Bad_FetchData;
2139 #endif /* FS_STATS_DETAILED */
2140
2141 #if FS_STATS_DETAILED
2142     /*
2143      * At this point, the data transfer is done, for good or ill.  Remember
2144      * when the transfer ended, bump the number of successes/failures, and
2145      * integrate the transfer size and elapsed time into the stats.  If the
2146      * operation failed, we jump to the appropriate point.
2147      */
2148     TM_GetTimeOfDay(&xferStopTime, 0);
2149     FS_LOCK
2150     (xferP->numXfers)++;
2151     if (!errorCode) {
2152         (xferP->numSuccesses)++;
2153
2154         /*
2155          * Bump the xfer sum by the number of bytes actually sent, NOT the
2156          * target number.
2157          */
2158         tot_bytesXferred += bytesXferred;
2159         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2160         tot_bytesXferred &= 0x3FF;
2161         if (bytesXferred < xferP->minBytes)
2162             xferP->minBytes = bytesXferred;
2163         if (bytesXferred > xferP->maxBytes)
2164             xferP->maxBytes = bytesXferred;
2165
2166         /*
2167          * Tally the size of the object.  Note: we tally the actual size,
2168          * NOT the number of bytes that made it out over the wire.
2169          */
2170         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2171             (xferP->count[0])++;
2172         else
2173             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2174                 (xferP->count[1])++;
2175         else
2176             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
2177                 (xferP->count[2])++;
2178         else
2179             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
2180                 (xferP->count[3])++;
2181         else
2182             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
2183                 (xferP->count[4])++;
2184         else
2185             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
2186                 (xferP->count[5])++;
2187         else
2188             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
2189                 (xferP->count[6])++;
2190         else
2191             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
2192                 (xferP->count[7])++;
2193         else
2194             (xferP->count[8])++;
2195
2196         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
2197         fs_stats_AddTo((xferP->sumTime), elapsedTime);
2198         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
2199         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
2200             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
2201         }
2202         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
2203             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
2204         }
2205       }
2206     FS_UNLOCK
2207     /*
2208      * Finally, go off to tell our caller the bad news in case the
2209      * fetch failed.
2210      */
2211     if (errorCode)
2212         goto Bad_FetchData;
2213 #endif /* FS_STATS_DETAILED */
2214
2215     /* write back  the OutStatus from the target vnode  */
2216     GetStatus(targetptr, OutStatus, rights, anyrights, &tparentwhentargetnotdir);
2217
2218     /* if a r/w volume, promise a callback to the caller */
2219     if (VolumeWriteable(volptr))
2220         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2221     else {
2222       struct AFSFid myFid;              
2223       memset(&myFid, 0, sizeof(struct AFSFid));
2224       myFid.Volume = Fid->Volume;
2225       SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2226       }
2227
2228 Bad_FetchData: 
2229     /* Update and store volume/vnode and parent vnodes back */
2230     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2231                             volptr);
2232     ViceLog(2, ("SRXAFS_FetchData returns %d\n", errorCode)); 
2233     errorCode = CallPostamble(tcon, errorCode);
2234
2235 #if FS_STATS_DETAILED
2236     TM_GetTimeOfDay(&opStopTime, 0);
2237     if (errorCode == 0) {
2238         FS_LOCK
2239         (opP->numSuccesses)++;
2240         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2241         fs_stats_AddTo((opP->sumTime), elapsedTime);
2242         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2243         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2244             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2245         }
2246         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2247             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2248         }
2249         FS_UNLOCK
2250       }
2251
2252 #endif /* FS_STATS_DETAILED */
2253
2254     osi_auditU (acall, FetchDataEvent, errorCode, AUD_FID, Fid, AUD_END);
2255     return(errorCode);
2256
2257 } /*SRXAFS_FetchData*/
2258
2259 afs_int32 SRXAFS_FetchData (struct rx_call *acall,   
2260                             struct AFSFid *Fid,      
2261                             afs_int32 Pos,           
2262                             afs_int32 Len,           
2263                             struct AFSFetchStatus *OutStatus,
2264                             struct AFSCallBack *CallBack, 
2265                             struct AFSVolSync *Sync) 
2266
2267 {
2268     int code;
2269
2270     code = common_FetchData64 (acall, Fid, Pos, Len, OutStatus,
2271                              CallBack, Sync, 0);
2272     return code;
2273 }
2274
2275 afs_int32 SRXAFS_FetchData64 (struct rx_call *acall, 
2276                               struct AFSFid *Fid,    
2277                               afs_int64 Pos,         
2278                               afs_int64 Len,         
2279                               struct AFSFetchStatus *OutStatus,
2280                               struct AFSCallBack *CallBack,
2281                               struct AFSVolSync *Sync)
2282 {
2283     int code;
2284     afs_int32 tPos, tLen;
2285
2286 #ifdef AFS_64BIT_ENV
2287     if (Pos + Len > 0x7fffffff)
2288         return E2BIG;
2289     tPos = Pos;
2290     tLen = Len;
2291 #else /* AFS_64BIT_ENV */
2292     if (Pos.high || Len.high)
2293         return E2BIG;
2294     tPos = Pos.low;
2295     tLen = Len.low;
2296 #endif /* AFS_64BIT_ENV */
2297
2298     code = common_FetchData64 (acall, Fid, tPos, tLen, OutStatus,
2299                              CallBack, Sync, 1);
2300     return code;
2301 }
2302
2303 afs_int32 SRXAFS_FetchACL (struct rx_call *acall,    
2304                            struct AFSFid *Fid,       
2305                            struct AFSOpaque *AccessList,     
2306                            struct AFSFetchStatus *OutStatus, 
2307                            struct AFSVolSync *Sync)
2308 {
2309     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2310     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2311     int     errorCode = 0;              /* return error code to caller */
2312     Volume * volptr = 0;                /* pointer to the volume */
2313     struct client *client;              /* pointer to the client data */
2314     afs_int32 rights, anyrights;                /* rights for this and any user */
2315     struct rx_connection *tcon = rx_ConnectionOf(acall);
2316     struct client *t_client;                /* tmp ptr to client data */
2317     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
2318 #if FS_STATS_DETAILED
2319     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2320     struct timeval opStartTime,
2321                    opStopTime;              /* Start/stop times for RPC op*/
2322     struct timeval elapsedTime;             /* Transfer time */
2323
2324     /*
2325      * Set our stats pointer, remember when the RPC operation started, and
2326      * tally the operation.
2327      */
2328     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHACL]);
2329     FS_LOCK
2330     (opP->numOps)++;
2331     FS_UNLOCK
2332     TM_GetTimeOfDay(&opStartTime, 0);
2333 #endif /* FS_STATS_DETAILED */
2334
2335     ViceLog(1, ("SAFS_FetchACL, Fid = %u.%d.%d\n",
2336             Fid->Volume, Fid->Vnode, Fid->Unique));
2337     FS_LOCK
2338     AFSCallStats.FetchACL++, AFSCallStats.TotalCalls++;
2339     FS_UNLOCK
2340     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
2341         goto Bad_FetchACL;
2342
2343     /* Get ptr to client data for user Id for logging */
2344     t_client = (struct client *)  rx_GetSpecific(tcon, rxcon_client_key);
2345     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2346     ViceLog(5, ("SAFS_FetchACL, Fid = %u.%d.%d, Host %s, Id %d\n",
2347             Fid->Volume, Fid->Vnode, Fid->Unique,
2348             inet_ntoa(logHostAddr), t_client->ViceId));
2349
2350     AccessList->AFSOpaque_len = 0;
2351     AccessList->AFSOpaque_val = malloc(AFSOPAQUEMAX);
2352     if (!AccessList->AFSOpaque_val) {
2353         ViceLog(0, ("Failed malloc in SRXAFS_FetchACL\n"));
2354         assert(0);
2355     }
2356
2357     /*
2358      * Get volume/vnode for the fetched file; caller's access rights to it
2359      * are also returned
2360      */
2361     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2362                                      DONTCHECK, &parentwhentargetnotdir,
2363                                      &client, READ_LOCK, &rights, &anyrights)))
2364         goto Bad_FetchACL;
2365
2366     SetVolumeSync(Sync, volptr);
2367
2368     /* Check whether we have permission to fetch the ACL */
2369     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2370                                            CHK_FETCHACL, 0)))
2371         goto Bad_FetchACL;
2372
2373     /* Get the Access List from the dir's vnode */
2374     if ((errorCode = RXFetch_AccessList(targetptr, parentwhentargetnotdir,
2375                                        AccessList)))
2376         goto Bad_FetchACL;
2377
2378     /* Get OutStatus back From the target Vnode  */
2379     GetStatus(targetptr, OutStatus, rights, anyrights, parentwhentargetnotdir);
2380
2381 Bad_FetchACL: 
2382     /* Update and store volume/vnode and parent vnodes back */
2383     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2384                             volptr);
2385     ViceLog(2, ("SAFS_FetchACL returns %d (ACL=%s)\n",
2386             errorCode, AccessList->AFSOpaque_val));
2387     errorCode = CallPostamble(tcon, errorCode);
2388
2389 #if FS_STATS_DETAILED
2390     TM_GetTimeOfDay(&opStopTime, 0);
2391     if (errorCode == 0) {
2392         FS_LOCK
2393         (opP->numSuccesses)++;
2394         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2395         fs_stats_AddTo((opP->sumTime), elapsedTime);
2396         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2397         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2398             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2399         }
2400         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2401             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2402         }
2403         FS_UNLOCK
2404       }
2405
2406 #endif /* FS_STATS_DETAILED */
2407
2408     osi_auditU (acall, FetchACLEvent, errorCode, AUD_FID, Fid, AUD_END);
2409     return errorCode;
2410 } /*SRXAFS_FetchACL*/
2411
2412
2413 /*
2414  * This routine is called exclusively by SRXAFS_FetchStatus(), and should be
2415  * merged into it when possible.
2416  */
2417 static 
2418 afs_int32 SAFSS_FetchStatus (struct rx_call *acall,
2419                              struct AFSFid *Fid,  
2420                              struct AFSFetchStatus *OutStatus,
2421                              struct AFSCallBack *CallBack,      
2422                              struct AFSVolSync *Sync)           
2423 {
2424     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2425     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2426     int     errorCode = 0;              /* return code to caller */
2427     Volume * volptr = 0;                /* pointer to the volume */
2428     struct client *client;              /* pointer to the client data */
2429     afs_int32 rights, anyrights;                /* rights for this and any user */
2430     struct client *t_client;            /* tmp ptr to client data */
2431     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
2432     struct rx_connection *tcon = rx_ConnectionOf(acall);
2433
2434     /* Get ptr to client data for user Id for logging */
2435     t_client = (struct client *)  rx_GetSpecific(tcon, rxcon_client_key);
2436     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2437     ViceLog(1, ("SAFS_FetchStatus,  Fid = %u.%d.%d, Host %s, Id %d\n",
2438             Fid->Volume, Fid->Vnode, Fid->Unique,
2439             inet_ntoa(logHostAddr), t_client->ViceId));
2440     FS_LOCK
2441     AFSCallStats.FetchStatus++, AFSCallStats.TotalCalls++;
2442     FS_UNLOCK
2443     /*
2444      * Get volume/vnode for the fetched file; caller's rights to it are
2445      * also returned
2446      */
2447     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2448                                      DONTCHECK, &parentwhentargetnotdir,
2449                                      &client, READ_LOCK, &rights, &anyrights)))
2450         goto Bad_FetchStatus;
2451
2452     /* set volume synchronization information */
2453     SetVolumeSync(Sync, volptr);
2454
2455     /* Are we allowed to fetch Fid's status? */
2456     if (targetptr->disk.type != vDirectory) {
2457       if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2458                                              CHK_FETCHSTATUS, 0))) {
2459           if (rx_GetCallAbortCode(acall) == errorCode) 
2460               rx_SetCallAbortCode(acall, 0);
2461           goto Bad_FetchStatus;
2462       }
2463     }
2464
2465     /* set OutStatus From the Fid  */
2466     GetStatus(targetptr, OutStatus, rights, anyrights, parentwhentargetnotdir);
2467
2468     /* If a r/w volume, also set the CallBack state */
2469     if (VolumeWriteable(volptr))
2470         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2471     else {
2472       struct AFSFid myFid;              
2473       memset(&myFid, 0, sizeof(struct AFSFid));
2474       myFid.Volume = Fid->Volume;
2475       SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2476       }
2477
2478 Bad_FetchStatus: 
2479     /* Update and store volume/vnode and parent vnodes back */
2480     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2481                             volptr);
2482     ViceLog(2, ("SAFS_FetchStatus returns %d\n", errorCode)); 
2483     return errorCode;
2484
2485 } /*SAFSS_FetchStatus*/
2486
2487
2488 afs_int32 SRXAFS_BulkStatus(struct rx_call *acall,
2489                             struct AFSCBFids *Fids,
2490                             struct AFSBulkStats *OutStats,
2491                             struct AFSCBs *CallBacks,
2492                             struct AFSVolSync *Sync)
2493 {
2494     register int i;
2495     afs_int32 nfiles;
2496     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2497     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2498     int     errorCode = 0;              /* return code to caller */
2499     Volume * volptr = 0;                /* pointer to the volume */
2500     struct client *client;              /* pointer to the client data */
2501     afs_int32 rights, anyrights;                /* rights for this and any user */
2502     register struct AFSFid *tfid;       /* file id we're dealing with now */
2503     struct rx_connection *tcon = rx_ConnectionOf(acall);
2504 #if FS_STATS_DETAILED
2505     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2506     struct timeval opStartTime,
2507                    opStopTime;              /* Start/stop times for RPC op*/
2508     struct timeval elapsedTime;             /* Transfer time */
2509
2510     /*
2511      * Set our stats pointer, remember when the RPC operation started, and
2512      * tally the operation.
2513      */
2514     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2515     FS_LOCK
2516     (opP->numOps)++;
2517     FS_UNLOCK
2518     TM_GetTimeOfDay(&opStartTime, 0);
2519 #endif /* FS_STATS_DETAILED */
2520
2521     ViceLog(1, ("SAFS_BulkStatus\n"));
2522     FS_LOCK
2523     AFSCallStats.TotalCalls++;
2524     FS_UNLOCK
2525
2526     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2527     if (nfiles <= 0) {                  /* Sanity check */
2528         errorCode = EINVAL;
2529         goto Audit_and_Return;
2530     }
2531
2532     /* allocate space for return output parameters */
2533     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2534         malloc(nfiles * sizeof(struct AFSFetchStatus));
2535     if (!OutStats->AFSBulkStats_val) {
2536         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2537         assert(0);
2538     }
2539     OutStats->AFSBulkStats_len = nfiles;
2540     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2541         malloc(nfiles * sizeof(struct AFSCallBack));
2542     if (!CallBacks->AFSCBs_val) {
2543         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2544         assert(0);
2545     }
2546     CallBacks->AFSCBs_len = nfiles;
2547
2548     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
2549         goto Bad_BulkStatus;
2550
2551     tfid = Fids->AFSCBFids_val;
2552     for (i=0; i<nfiles; i++, tfid++) {
2553         /*
2554          * Get volume/vnode for the fetched file; caller's rights to it
2555          * are also returned
2556          */
2557         if ((errorCode =
2558             GetVolumePackage(tcon, tfid, &volptr, &targetptr,
2559                              DONTCHECK, &parentwhentargetnotdir, &client,
2560                              READ_LOCK, &rights, &anyrights)))
2561                 goto Bad_BulkStatus;
2562         /* set volume synchronization information, but only once per call */
2563         if (i == nfiles)
2564             SetVolumeSync(Sync, volptr);
2565
2566         /* Are we allowed to fetch Fid's status? */
2567         if (targetptr->disk.type != vDirectory) {
2568             if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2569                                                    CHK_FETCHSTATUS, 0))) {
2570                 if (rx_GetCallAbortCode(acall) == errorCode) 
2571                     rx_SetCallAbortCode(acall, 0);
2572                 goto Bad_BulkStatus;
2573             }
2574         }
2575
2576         /* set OutStatus From the Fid  */
2577         GetStatus(targetptr, &OutStats->AFSBulkStats_val[i],
2578                   rights, anyrights, parentwhentargetnotdir);
2579
2580         /* If a r/w volume, also set the CallBack state */
2581         if (VolumeWriteable(volptr))
2582             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2583                               &CallBacks->AFSCBs_val[i]);
2584         else {
2585           struct AFSFid myFid;          
2586           memset(&myFid, 0, sizeof(struct AFSFid));
2587           myFid.Volume = tfid->Volume;
2588           SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2589                               &CallBacks->AFSCBs_val[i]);
2590         }
2591
2592         /* put back the file ID and volume */
2593         (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2594                                 volptr);
2595         parentwhentargetnotdir = (Vnode *) 0;
2596         targetptr = (Vnode *) 0;
2597         volptr = (Volume *) 0;
2598     }
2599
2600 Bad_BulkStatus: 
2601     /* Update and store volume/vnode and parent vnodes back */
2602     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
2603                             volptr);
2604     errorCode = CallPostamble(tcon, errorCode);
2605
2606 #if FS_STATS_DETAILED
2607     TM_GetTimeOfDay(&opStopTime, 0);
2608     if (errorCode == 0) {
2609         FS_LOCK
2610         (opP->numSuccesses)++;
2611         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2612         fs_stats_AddTo((opP->sumTime), elapsedTime);
2613         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2614         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2615             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2616         }
2617         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2618             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2619         }
2620         FS_UNLOCK
2621     }   
2622
2623 #endif /* FS_STATS_DETAILED */
2624
2625 Audit_and_Return:
2626     ViceLog(2, ("SAFS_BulkStatus        returns %d\n", errorCode)); 
2627     osi_auditU (acall, BulkFetchStatusEvent, errorCode, AUD_FIDS, Fids, AUD_END);
2628     return errorCode;
2629
2630 } /*SRXAFS_BulkStatus*/
2631
2632
2633 afs_int32 SRXAFS_InlineBulkStatus(struct rx_call *acall,
2634                                   struct AFSCBFids *Fids,
2635                                   struct AFSBulkStats *OutStats,
2636                                   struct AFSCBs *CallBacks,
2637                                   struct AFSVolSync *Sync)
2638 {
2639     register int i;
2640     afs_int32 nfiles;
2641     Vnode * targetptr = 0;              /* pointer to vnode to fetch */
2642     Vnode * parentwhentargetnotdir = 0; /* parent vnode if targetptr is a file */
2643     int     errorCode = 0;              /* return code to caller */
2644     Volume * volptr = 0;                /* pointer to the volume */
2645     struct client *client;              /* pointer to the client data */
2646     afs_int32 rights, anyrights;                /* rights for this and any user */
2647     register struct AFSFid *tfid;       /* file id we're dealing with now */
2648     struct rx_connection *tcon;
2649     AFSFetchStatus *tstatus;
2650 #if FS_STATS_DETAILED
2651     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2652     struct timeval opStartTime,
2653                    opStopTime;              /* Start/stop times for RPC op*/
2654     struct timeval elapsedTime;             /* Transfer time */
2655
2656     /*
2657      * Set our stats pointer, remember when the RPC operation started, and
2658      * tally the operation.
2659      */
2660     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2661     FS_LOCK
2662     (opP->numOps)++;
2663     FS_UNLOCK
2664     TM_GetTimeOfDay(&opStartTime, 0);
2665 #endif /* FS_STATS_DETAILED */
2666
2667     ViceLog(1, ("SAFS_InlineBulkStatus\n"));
2668     FS_LOCK
2669     AFSCallStats.TotalCalls++;
2670     FS_UNLOCK
2671
2672     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2673     if (nfiles <= 0) {                  /* Sanity check */
2674         errorCode = EINVAL;
2675         goto Audit_and_Return;
2676     }
2677
2678     /* allocate space for return output parameters */
2679     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2680         malloc(nfiles * sizeof(struct AFSFetchStatus));
2681     if (!OutStats->AFSBulkStats_val) {
2682         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2683         assert(0);
2684     }
2685     OutStats->AFSBulkStats_len = nfiles;
2686     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2687         malloc(nfiles * sizeof(struct AFSCallBack));
2688     if (!CallBacks->AFSCBs_val) {
2689         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2690         assert(0);
2691     }
2692     CallBacks->AFSCBs_len = nfiles;
2693
2694     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon))) {
2695         goto Bad_InlineBulkStatus;
2696     }
2697
2698     tfid = Fids->AFSCBFids_val;
2699     for (i=0; i<nfiles; i++, tfid++) {
2700         /*
2701          * Get volume/vnode for the fetched file; caller's rights to it
2702          * are also returned
2703          */
2704         if ((errorCode =
2705             GetVolumePackage(tcon, tfid, &volptr, &targetptr,
2706                              DONTCHECK, &parentwhentargetnotdir, &client,
2707                              READ_LOCK, &rights, &anyrights))) {
2708             tstatus = &OutStats->AFSBulkStats_val[i];
2709             tstatus->errorCode = errorCode;
2710             parentwhentargetnotdir = (Vnode *) 0;
2711             targetptr = (Vnode *) 0;
2712             volptr = (Volume *) 0;
2713             continue;
2714         }
2715
2716         /* set volume synchronization information, but only once per call */
2717         if (i == nfiles)
2718             SetVolumeSync(Sync, volptr);
2719
2720         /* Are we allowed to fetch Fid's status? */
2721         if (targetptr->disk.type != vDirectory) {
2722             if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2723                                                    CHK_FETCHSTATUS, 0))) {
2724                 tstatus = &OutStats->AFSBulkStats_val[i];
2725                 tstatus->errorCode = errorCode;
2726                 (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, volptr);
2727                 parentwhentargetnotdir = (Vnode *) 0;
2728                 targetptr = (Vnode *) 0;
2729                 volptr = (Volume *) 0;
2730                 continue;
2731             }
2732         }
2733
2734         /* set OutStatus From the Fid  */
2735         GetStatus(targetptr, (struct AFSFetchStatus *) &OutStats->AFSBulkStats_val[i], 
2736           rights, anyrights, parentwhentargetnotdir);
2737
2738         /* If a r/w volume, also set the CallBack state */
2739         if (VolumeWriteable(volptr))
2740             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2741                               &CallBacks->AFSCBs_val[i]);
2742         else {
2743           struct AFSFid myFid;          
2744           memset(&myFid, 0, sizeof(struct AFSFid));
2745           myFid.Volume = tfid->Volume;
2746           SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2747                               &CallBacks->AFSCBs_val[i]);
2748         }
2749
2750         /* put back the file ID and volume */
2751         (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, volptr);
2752         parentwhentargetnotdir = (Vnode *) 0;
2753         targetptr = (Vnode *) 0;
2754         volptr = (Volume *) 0;
2755     }
2756
2757 Bad_InlineBulkStatus: 
2758     /* Update and store volume/vnode and parent vnodes back */
2759     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
2760     errorCode = CallPostamble(tcon, errorCode);
2761
2762 #if FS_STATS_DETAILED
2763     TM_GetTimeOfDay(&opStopTime, 0);
2764     if (errorCode == 0) {
2765         FS_LOCK
2766         (opP->numSuccesses)++;
2767         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2768         fs_stats_AddTo((opP->sumTime), elapsedTime);
2769         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2770         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2771             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2772         }
2773         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2774             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2775         }
2776         FS_UNLOCK
2777     }   
2778
2779 #endif /* FS_STATS_DETAILED */
2780
2781 Audit_and_Return:
2782     ViceLog(2, ("SAFS_InlineBulkStatus  returns %d\n", errorCode)); 
2783     osi_auditU (acall, InlineBulkFetchStatusEvent, errorCode, AUD_FIDS, Fids, AUD_END);
2784     return 0;
2785
2786 } /*SRXAFS_InlineBulkStatus*/
2787
2788
2789 afs_int32 SRXAFS_FetchStatus (struct rx_call *acall,            
2790                               struct AFSFid *Fid,               
2791                               struct AFSFetchStatus *OutStatus, 
2792                               struct AFSCallBack *CallBack,     
2793                               struct AFSVolSync *Sync)
2794 {
2795     afs_int32 code;
2796     struct rx_connection *tcon;
2797 #if FS_STATS_DETAILED
2798     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2799     struct timeval opStartTime,
2800                    opStopTime;              /* Start/stop times for RPC op*/
2801     struct timeval elapsedTime;             /* Transfer time */
2802
2803     /*
2804      * Set our stats pointer, remember when the RPC operation started, and
2805      * tally the operation.
2806      */
2807     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHSTATUS]);
2808     FS_LOCK
2809     (opP->numOps)++;
2810     FS_UNLOCK
2811     TM_GetTimeOfDay(&opStartTime, 0);
2812 #endif /* FS_STATS_DETAILED */
2813
2814     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
2815         goto Bad_FetchStatus;
2816
2817     code = SAFSS_FetchStatus (acall, Fid, OutStatus, CallBack, Sync);
2818
2819 Bad_FetchStatus:    
2820     code = CallPostamble(tcon, code);
2821
2822 #if FS_STATS_DETAILED
2823     TM_GetTimeOfDay(&opStopTime, 0);
2824     if (code == 0) {
2825         FS_LOCK
2826         (opP->numSuccesses)++;
2827         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2828         fs_stats_AddTo((opP->sumTime), elapsedTime);
2829         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2830         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2831             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2832         }
2833         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2834             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2835         }
2836         FS_UNLOCK
2837       }
2838
2839 #endif /* FS_STATS_DETAILED */
2840
2841     osi_auditU (acall, FetchStatusEvent, code, AUD_FID, Fid, AUD_END);
2842     return code;
2843
2844 } /*SRXAFS_FetchStatus*/
2845
2846 static
2847 afs_int32 common_StoreData64 (struct rx_call *acall,            
2848                               struct AFSFid *Fid,                       
2849                               struct AFSStoreStatus *InStatus,  
2850                               afs_uint32 Pos,                     
2851                               afs_uint32 Length,                  
2852                               afs_uint32 FileLength,              
2853                               struct AFSFetchStatus *OutStatus, 
2854                               struct AFSVolSync *Sync)
2855 {
2856     Vnode * targetptr = 0;              /* pointer to input fid */
2857     Vnode * parentwhentargetnotdir = 0; /* parent of Fid to get ACL */
2858     Vnode   tparentwhentargetnotdir;    /* parent vnode for GetStatus */
2859     int     errorCode = 0;              /* return code for caller */
2860     int     fileCode =  0;              /* return code from vol package */
2861     Volume * volptr = 0;                /* pointer to the volume header */
2862     struct client * client;             /* pointer to client structure */
2863     afs_int32 rights, anyrights;                /* rights for this and any user */
2864     struct client *t_client;            /* tmp ptr to client data */
2865     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
2866     struct rx_connection *tcon;
2867 #if FS_STATS_DETAILED
2868     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
2869     struct fs_stats_xferData *xferP;        /* Ptr to this op's byte size struct */
2870     struct timeval opStartTime,
2871                    opStopTime;              /* Start/stop times for RPC op*/
2872     struct timeval xferStartTime,
2873                    xferStopTime;            /* Start/stop times for xfer portion*/
2874     struct timeval elapsedTime;             /* Transfer time */
2875     afs_int32 bytesToXfer;                          /* # bytes to xfer */
2876     afs_int32 bytesXferred;                         /* # bytes actually xfer */
2877     static afs_int32 tot_bytesXferred; /* shared access protected by FS_LOCK */
2878
2879     /*
2880      * Set our stats pointers, remember when the RPC operation started, and
2881      * tally the operation.
2882      */
2883     opP   = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREDATA]);
2884     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_STOREDATA]);
2885     FS_LOCK
2886     (opP->numOps)++;
2887     FS_UNLOCK
2888
2889     ViceLog(1, ("StoreData: Fid = %u.%d.%d\n",
2890             Fid->Volume, Fid->Vnode, Fid->Unique));
2891     TM_GetTimeOfDay(&opStartTime, 0);
2892 #endif /* FS_STATS_DETAILED */
2893
2894     FS_LOCK
2895     AFSCallStats.StoreData++, AFSCallStats.TotalCalls++;
2896     FS_UNLOCK
2897
2898     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
2899         goto Bad_StoreData;
2900
2901     /* Get ptr to client data for user Id for logging */
2902     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
2903     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
2904     ViceLog(5, ("StoreData: Fid = %u.%d.%d, Host %s, Id %d\n",
2905             Fid->Volume, Fid->Vnode, Fid->Unique,
2906             inet_ntoa(logHostAddr), t_client->ViceId));
2907
2908     /*
2909      * Get associated volume/vnode for the stored file; caller's rights
2910      * are also returned
2911      */
2912     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
2913                                      MustNOTBeDIR, &parentwhentargetnotdir,
2914                                      &client, WRITE_LOCK, &rights, &anyrights))) {
2915         goto Bad_StoreData;
2916     }
2917
2918     /* set volume synchronization information */
2919     SetVolumeSync(Sync, volptr);
2920
2921     if ((targetptr->disk.type == vSymlink)) {
2922         /* Should we return a better error code here??? */
2923         errorCode = EISDIR;
2924         goto Bad_StoreData;
2925     }
2926
2927     /* Check if we're allowed to store the data */
2928     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
2929                                            CHK_STOREDATA, InStatus))) {
2930         goto Bad_StoreData;
2931     }
2932
2933     /*
2934      * Drop the read lock on the parent directory after saving the parent
2935      * vnode information we need to pass to GetStatus
2936      */
2937     if (parentwhentargetnotdir != NULL) {
2938         tparentwhentargetnotdir = *parentwhentargetnotdir;
2939         VPutVnode(&fileCode, parentwhentargetnotdir);
2940         assert(!fileCode || (fileCode == VSALVAGE));
2941         parentwhentargetnotdir = NULL;
2942     }
2943
2944
2945
2946 #if FS_STATS_DETAILED
2947     /*
2948      * Remember when the data transfer started.
2949      */
2950     TM_GetTimeOfDay(&xferStartTime, 0);
2951 #endif /* FS_STATS_DETAILED */
2952
2953     /* Do the actual storing of the data */
2954 #if FS_STATS_DETAILED
2955     errorCode = StoreData_RXStyle(volptr, targetptr, Fid, client, acall,
2956                                   Pos, Length, FileLength,
2957                                   (InStatus->Mask & AFS_FSYNC),
2958                                   &bytesToXfer, &bytesXferred);
2959 #else
2960     errorCode = StoreData_RXStyle(volptr, targetptr, Fid, client,
2961                                       acall, Pos, Length, FileLength,
2962                                       (InStatus->Mask & AFS_FSYNC));
2963     if (errorCode && (!targetptr->changed_newTime))
2964             goto Bad_StoreData;
2965 #endif /* FS_STATS_DETAILED */
2966 #if FS_STATS_DETAILED
2967     /*
2968      * At this point, the data transfer is done, for good or ill.  Remember
2969      * when the transfer ended, bump the number of successes/failures, and
2970      * integrate the transfer size and elapsed time into the stats.  If the
2971      * operation failed, we jump to the appropriate point.
2972      */
2973     TM_GetTimeOfDay(&xferStopTime, 0);
2974     FS_LOCK
2975     (xferP->numXfers)++;
2976     if (!errorCode) {
2977         (xferP->numSuccesses)++;
2978
2979         /*
2980          * Bump the xfer sum by the number of bytes actually sent, NOT the
2981          * target number.
2982          */
2983         tot_bytesXferred += bytesXferred;
2984         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2985         tot_bytesXferred &= 0x3FF;
2986         if (bytesXferred < xferP->minBytes)
2987             xferP->minBytes = bytesXferred;
2988         if (bytesXferred > xferP->maxBytes)
2989             xferP->maxBytes = bytesXferred;
2990       
2991         /*
2992          * Tally the size of the object.  Note: we tally the actual size,
2993          * NOT the number of bytes that made it out over the wire.
2994          */
2995         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2996             (xferP->count[0])++;
2997         else
2998             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2999                 (xferP->count[1])++;
3000         else
3001             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
3002                 (xferP->count[2])++;
3003         else
3004             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
3005                 (xferP->count[3])++;
3006         else
3007             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
3008                 (xferP->count[4])++;
3009         else
3010             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
3011                 (xferP->count[5])++;
3012         else
3013             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
3014                 (xferP->count[6])++;
3015         else
3016             if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
3017                 (xferP->count[7])++;
3018         else
3019             (xferP->count[8])++;
3020       
3021         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
3022         fs_stats_AddTo((xferP->sumTime), elapsedTime);
3023         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
3024         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
3025             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
3026         }
3027         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
3028             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
3029         }
3030     }
3031     FS_UNLOCK
3032
3033     /*
3034      * Finally, go off to tell our caller the bad news in case the
3035      * store failed.
3036      */
3037     if (errorCode && (!targetptr->changed_newTime))
3038             goto Bad_StoreData;
3039 #endif /* FS_STATS_DETAILED */
3040
3041     /* Update the status of the target's vnode */
3042     Update_TargetVnodeStatus(targetptr, TVS_SDATA, client, InStatus, targetptr,
3043                              volptr, 0);
3044
3045     /* Get the updated File's status back to the caller */
3046     GetStatus(targetptr, OutStatus, rights, anyrights, &tparentwhentargetnotdir);
3047
3048 Bad_StoreData: 
3049     /* Update and store volume/vnode and parent vnodes back */
3050     (void) PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0,
3051                             volptr);
3052     ViceLog(2, ("SAFS_StoreData returns %d\n", errorCode));
3053
3054     errorCode = CallPostamble(tcon, errorCode);
3055
3056 #if FS_STATS_DETAILED
3057     TM_GetTimeOfDay(&opStopTime, 0);
3058     if (errorCode == 0) {
3059         FS_LOCK
3060         (opP->numSuccesses)++;
3061         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3062         fs_stats_AddTo((opP->sumTime), elapsedTime);
3063         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3064         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3065             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3066         }
3067         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3068             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3069         }
3070         FS_UNLOCK
3071       }
3072 #endif /* FS_STATS_DETAILED */
3073
3074     osi_auditU (acall, StoreDataEvent, errorCode, AUD_FID, Fid, AUD_END);
3075     return(errorCode);
3076
3077 } /*common_StoreData64*/
3078
3079 afs_int32 SRXAFS_StoreData (struct rx_call *acall,              
3080                             struct AFSFid *Fid,                 
3081                             struct AFSStoreStatus *InStatus,    
3082                             afs_uint32 Pos,                     
3083                             afs_uint32 Length,                  
3084                             afs_uint32 FileLength,              
3085                             struct AFSFetchStatus *OutStatus,   
3086                             struct AFSVolSync *Sync)
3087 {
3088     int code;
3089
3090     code = common_StoreData64 (acall, Fid, InStatus, Pos, Length, FileLength,
3091                                OutStatus, Sync);
3092     return code;
3093
3094 } /*SRXAFS_StoreData*/
3095
3096 afs_int32 SRXAFS_StoreData64 (struct rx_call *acall,            
3097                               struct AFSFid *Fid,               
3098                               struct AFSStoreStatus *InStatus,  
3099                               afs_uint64 Pos,                   
3100                               afs_uint64 Length,                
3101                               afs_uint64 FileLength,            
3102                               struct AFSFetchStatus *OutStatus, 
3103                               struct AFSVolSync *Sync)
3104 {
3105     int code;
3106     afs_int32 tPos;
3107     afs_int32 tLength;
3108     afs_int32 tFileLength;
3109
3110 #ifdef AFS_64BIT_ENV
3111     if (FileLength > 0x7fffffff)
3112         return E2BIG;
3113     tPos = Pos;
3114     tLength = Length;
3115     tFileLength = FileLength;
3116 #else /* AFS_64BIT_ENV */
3117     if (FileLength.high)
3118         return E2BIG;
3119     tPos = Pos.low;
3120     tLength = Length.low;
3121     tFileLength = FileLength.low;
3122 #endif /* AFS_64BIT_ENV */
3123
3124     code = common_StoreData64 (acall, Fid, InStatus, tPos, tLength, tFileLength,
3125                                OutStatus, Sync);
3126     return code;
3127 }
3128
3129 afs_int32 SRXAFS_StoreACL (struct rx_call *acall,               
3130                            struct AFSFid *Fid,                  
3131                            struct AFSOpaque *AccessList,        
3132                            struct AFSFetchStatus *OutStatus,
3133                            struct AFSVolSync *Sync)
3134 {
3135     Vnode * targetptr = 0;              /* pointer to input fid */
3136     Vnode * parentwhentargetnotdir = 0; /* parent of Fid to get ACL */
3137     int     errorCode = 0;              /* return code for caller */
3138     struct AFSStoreStatus InStatus;     /* Input status for fid */
3139     Volume * volptr = 0;                /* pointer to the volume header */
3140     struct client * client;             /* pointer to client structure */
3141     afs_int32 rights, anyrights;                /* rights for this and any user */
3142     struct rx_connection *tcon;
3143     struct client *t_client;            /* tmp ptr to client data */
3144     struct in_addr logHostAddr;             /* host ip holder for inet_ntoa */
3145 #if FS_STATS_DETAILED
3146     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
3147     struct timeval opStartTime,
3148                    opStopTime;              /* Start/stop times for RPC op*/
3149     struct timeval elapsedTime;             /* Transfer time */
3150
3151     /*
3152      * Set our stats pointer, remember when the RPC operation started, and
3153      * tally the operation.
3154      */
3155     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREACL]);
3156     FS_LOCK
3157     (opP->numOps)++;
3158     FS_UNLOCK
3159     TM_GetTimeOfDay(&opStartTime, 0);
3160 #endif /* FS_STATS_DETAILED */
3161     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon)))
3162         goto Bad_StoreACL;
3163
3164     /* Get ptr to client data for user Id for logging */
3165     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3166     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3167     ViceLog(1, ("SAFS_StoreACL, Fid = %u.%d.%d, ACL=%s, Host %s, Id %d\n",
3168             Fid->Volume, Fid->Vnode, Fid->Unique, AccessList->AFSOpaque_val,
3169             inet_ntoa(logHostAddr), t_client->ViceId));
3170     FS_LOCK
3171     AFSCallStats.StoreACL++, AFSCallStats.TotalCalls++;
3172     FS_UNLOCK
3173
3174     InStatus.Mask = 0;      /* not storing any status */
3175
3176     /*
3177      * Get associated volume/vnode for the target dir; caller's rights
3178      * are also returned.
3179      */
3180     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
3181                                      MustBeDIR, &parentwhentargetnotdir,
3182                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3183         goto Bad_StoreACL;
3184     }
3185
3186     /* set volume synchronization information */
3187     SetVolumeSync(Sync, volptr);
3188
3189     /* Check if we have permission to change the dir's ACL */
3190     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
3191                                            CHK_STOREACL, &InStatus))) {
3192         goto Bad_StoreACL;
3193     }
3194
3195     /* Build and store the new Access List for the dir */
3196     if ((errorCode = RXStore_AccessList(targetptr, AccessList))) {
3197         goto Bad_StoreACL;
3198     }
3199     
3200     targetptr->changed_newTime = 1; /* status change of directory */
3201
3202     /* convert the write lock to a read lock before breaking callbacks */
3203     VVnodeWriteToRead(&errorCode, targetptr);
3204     assert(!errorCode || errorCode == VSALVAGE);
3205
3206     /* break call backs on the directory  */
3207     BreakCallBack(client->host, Fid, 0);
3208
3209     /* Get the updated dir's status back to the caller */
3210     GetStatus(targetptr, OutStatus, rights, anyrights, 0);
3211
3212 Bad_StoreACL: 
3213     /* Update and store volume/vnode and parent vnodes back */
3214     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
3215     ViceLog(2, ("SAFS_StoreACL returns %d\n", errorCode)); 
3216     errorCode = CallPostamble(tcon, errorCode);
3217
3218 #if FS_STATS_DETAILED
3219     TM_GetTimeOfDay(&opStopTime, 0);
3220     if (errorCode == 0) {
3221       FS_LOCK
3222       (opP->numSuccesses)++;
3223       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3224       fs_stats_AddTo((opP->sumTime), elapsedTime);
3225       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3226       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3227         fs_stats_TimeAssign((opP->minTime), elapsedTime);
3228       }
3229       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3230         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3231       }
3232       FS_UNLOCK
3233     }
3234 #endif /* FS_STATS_DETAILED */
3235
3236     osi_auditU (acall, StoreACLEvent, errorCode, AUD_FID, Fid, AUD_END);
3237     return errorCode;
3238
3239 } /*SRXAFS_StoreACL*/
3240
3241
3242 /*
3243  * Note: This routine is called exclusively from SRXAFS_StoreStatus(), and
3244  * should be merged when possible.
3245  */
3246 static afs_int32
3247 SAFSS_StoreStatus (struct rx_call *acall,               
3248                    struct AFSFid *Fid,                  
3249                    struct AFSStoreStatus *InStatus,     
3250                    struct AFSFetchStatus *OutStatus,    
3251                    struct AFSVolSync *Sync)
3252
3253 {
3254     Vnode * targetptr = 0;              /* pointer to input fid */
3255     Vnode * parentwhentargetnotdir = 0; /* parent of Fid to get ACL */
3256     int     errorCode = 0;              /* return code for caller */
3257     Volume * volptr = 0;                /* pointer to the volume header */
3258     struct client * client;             /* pointer to client structure */
3259     afs_int32 rights, anyrights;                /* rights for this and any user */
3260     struct client *t_client;            /* tmp ptr to client data */
3261     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
3262     struct rx_connection *tcon = rx_ConnectionOf(acall);
3263
3264     /* Get ptr to client data for user Id for logging */
3265     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3266     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3267     ViceLog(1, ("SAFS_StoreStatus,  Fid = %u.%d.%d, Host %s, Id %d\n",
3268             Fid->Volume, Fid->Vnode,    Fid->Unique,
3269             inet_ntoa(logHostAddr), t_client->ViceId));
3270     FS_LOCK
3271     AFSCallStats.StoreStatus++, AFSCallStats.TotalCalls++;
3272     FS_UNLOCK
3273     /*
3274      * Get volume/vnode for the target file; caller's rights to it are
3275      * also returned
3276      */
3277     if ((errorCode = GetVolumePackage(tcon, Fid, &volptr, &targetptr,
3278                                      DONTCHECK, &parentwhentargetnotdir,
3279                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3280         goto Bad_StoreStatus;
3281     }
3282
3283     /* set volume synchronization information */
3284     SetVolumeSync(Sync, volptr);
3285
3286     /* Check if the caller has proper permissions to store status to Fid */
3287     if ((errorCode = Check_PermissionRights(targetptr, client, rights,
3288                                            CHK_STORESTATUS, InStatus))) {
3289         goto Bad_StoreStatus;
3290     }
3291     /*
3292      * Check for a symbolic link; we can't chmod these (otherwise could
3293      * change a symlink to a mt pt or vice versa)
3294      */
3295     if (targetptr->disk.type == vSymlink && (InStatus->Mask & AFS_SETMODE)) {
3296         errorCode = EINVAL;
3297         goto Bad_StoreStatus;
3298     }
3299
3300     /* Update the status of the target's vnode */
3301     Update_TargetVnodeStatus(targetptr, TVS_SSTATUS, client, InStatus,
3302                              (parentwhentargetnotdir ?
3303                               parentwhentargetnotdir : targetptr), volptr, 0);
3304
3305     /* convert the write lock to a read lock before breaking callbacks */
3306     VVnodeWriteToRead(&errorCode, targetptr);
3307     assert(!errorCode || errorCode == VSALVAGE);
3308
3309     /* Break call backs on Fid */
3310     BreakCallBack(client->host, Fid, 0);
3311
3312     /* Return the updated status back to caller */
3313     GetStatus(targetptr, OutStatus, rights, anyrights, parentwhentargetnotdir);
3314
3315 Bad_StoreStatus: 
3316     /* Update and store volume/vnode and parent vnodes back */
3317     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *)0, volptr);
3318     ViceLog(2, ("SAFS_StoreStatus returns %d\n", errorCode));
3319     return errorCode;
3320
3321 } /*SAFSS_StoreStatus*/
3322
3323
3324 afs_int32 SRXAFS_StoreStatus (struct rx_call *acall,            
3325                               struct AFSFid *Fid,               
3326                               struct AFSStoreStatus *InStatus,  
3327                               struct AFSFetchStatus *OutStatus, 
3328                               struct AFSVolSync *Sync)
3329 {
3330     afs_int32 code;
3331     struct rx_connection *tcon;
3332 #if FS_STATS_DETAILED
3333     struct fs_stats_opTimingData *opP;      /* Ptr to this op's timing struct */
3334     struct timeval opStartTime,
3335                    opStopTime;              /* Start/stop times for RPC op*/
3336     struct timeval elapsedTime;             /* Transfer time */
3337
3338     /*
3339      * Set our stats pointer, remember when the RPC operation started, and
3340      * tally the operation.
3341      */
3342     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STORESTATUS]);
3343     FS_LOCK
3344     (opP->numOps)++;
3345     FS_UNLOCK
3346     TM_GetTimeOfDay(&opStartTime, 0);
3347 #endif /* FS_STATS_DETAILED */
3348
3349     if ((code = CallPreamble(acall, ACTIVECALL, &tcon)))
3350         goto Bad_StoreStatus;
3351
3352     code = SAFSS_StoreStatus (acall, Fid, InStatus, OutStatus, Sync);
3353
3354 Bad_StoreStatus:
3355     code = CallPostamble(tcon, code);
3356
3357 #if FS_STATS_DETAILED
3358     TM_GetTimeOfDay(&opStopTime, 0);
3359     if (code == 0) {
3360       FS_LOCK
3361       (opP->numSuccesses)++;
3362       fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3363       fs_stats_AddTo((opP->sumTime), elapsedTime);
3364       fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3365       if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3366         fs_stats_TimeAssign((opP->minTime), elapsedTime);
3367       }
3368       if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3369         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3370       }
3371       FS_UNLOCK
3372     }
3373
3374 #endif /* FS_STATS_DETAILED */
3375
3376     osi_auditU (acall, StoreStatusEvent, code, AUD_FID, Fid, AUD_END);
3377     return code;
3378
3379 } /*SRXAFS_StoreStatus*/
3380
3381
3382 /*
3383  * This routine is called exclusively by SRXAFS_RemoveFile(), and should be
3384  * merged in when possible.
3385  */
3386 static afs_int32
3387 SAFSS_RemoveFile (struct rx_call *acall,               
3388                   struct AFSFid *DirFid,               
3389                   char *Name,                          
3390                   struct AFSFetchStatus *OutDirStatus, 
3391                   struct AFSVolSync *Sync)
3392 {
3393     Vnode * parentptr = 0;              /* vnode of input Directory */
3394     Vnode * parentwhentargetnotdir = 0; /* parent for use in SetAccessList */
3395     Vnode * targetptr = 0;              /* file to be deleted */
3396     Volume * volptr = 0;                /* pointer to the volume header */
3397     AFSFid fileFid;                     /* area for Fid from the directory */
3398     int     errorCode = 0;              /* error code */
3399     DirHandle dir;                      /* Handle for dir package I/O */
3400     struct client * client;             /* pointer to client structure */
3401     afs_int32 rights, anyrights;                /* rights for this and any user */
3402     struct client *t_client;            /* tmp ptr to client data */
3403     struct in_addr logHostAddr;         /* host ip holder for inet_ntoa */
3404     struct rx_connection *tcon = rx_ConnectionOf(acall);
3405
3406     FidZero(&dir);
3407     /* Get ptr to client data for user Id for logging */
3408     t_client = (struct client *) rx_GetSpecific(tcon, rxcon_client_key); 
3409     logHostAddr.s_addr =  rx_HostOf(rx_PeerOf(tcon));
3410     ViceLog(1, ("SAFS_RemoveFile %s,  Did = %u.%d.%d, Host %s, Id %d\n",
3411             Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3412             inet_ntoa(logHostAddr), t_client->ViceId));
3413     FS_LOCK
3414     AFSCallStats.RemoveFile++, AFSCallStats.TotalCalls++;
3415     FS_UNLOCK
3416     /*
3417      * Get volume/vnode for the parent dir; caller's access rights are
3418      * also returned
3419      */
3420     if ((errorCode = GetVolumePackage(tcon, DirFid, &volptr, &parentptr,
3421                                      MustBeDIR, &parentwhentargetnotdir,
3422                                      &client, WRITE_LOCK, &rights, &anyrights))) {
3423         goto Bad_RemoveFile;
3424     }
3425     /* set volume synchronization information */
3426     SetVolumeSync(Sync, volptr);
3427
3428     /* Does the caller has delete (& write) access to the parent directory? */
3429     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
3430         goto Bad_RemoveFile;
3431     }
3432
3433     /* Actually delete the desired file */
3434     if ((errorCode = DeleteTarget(parentptr, volptr, &targetptr, &dir,
3435                                  &fileFid, Name, MustNOTBeDIR))) {
3436         goto Bad_RemoveFile;
3437     }
3438
3439     /* Update the vnode status of the parent dir */
3440 #if FS_STATS_DETAILED
3441     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3442                              parentptr->disk.linkCount, client->InSameNetwork);
3443 #else
3444     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3445                              parentptr->disk.linkCount);
3446 #endif /* FS_STATS_DETAILED */
3447
3448     /* Return the updated parent dir's status back to caller */
3449     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3450
3451     /* Handle internal callback state for the parent and the deleted file */
3452     if (targetptr->disk.linkCount == 0) {
3453         /* no references left, discard entry */
3454         DeleteFileCallBacks(&fileFid);
3455         /* convert the parent lock to a read lock before breaking callbacks */
3456         VVnodeWriteToRead(&errorCode, parentptr);
3457         assert(!errorCode || errorCode == VSALVAGE);
3458     } else {
3459         /* convert the parent lock to a read lock before breaking callbacks */
3460         VVnodeWriteToRead(&errorCode, parentptr);
3461         assert(!errorCode || errorCode == VSALVAGE);