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