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