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