viced: REALLYCLOSE origfdP after CoW
[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;
4049     }
4050
4051     SetDirHandle(&newdir, newvptr);
4052
4053     /* Lookup the file to delete its vnode */
4054     if (Lookup(&olddir, OldName, &fileFid)) {
4055         errorCode = ENOENT;
4056         goto Bad_Rename;
4057     }
4058     if (fileFid.Vnode == oldvptr->vnodeNumber
4059         || fileFid.Vnode == newvptr->vnodeNumber) {
4060         errorCode = FSERR_ELOOP;
4061         goto Bad_Rename;
4062     }
4063     fileFid.Volume = V_id(volptr);
4064     fileptr = VGetVnode(&errorCode, volptr, fileFid.Vnode, WRITE_LOCK);
4065     if (errorCode != 0) {
4066         ViceLog(0,
4067                 ("SAFSS_Rename(): Error in VGetVnode() for old file %s, code %d\n",
4068                  OldName, errorCode));
4069         VTakeOffline(volptr);
4070         goto Bad_Rename;
4071     }
4072     if (fileptr->disk.uniquifier != fileFid.Unique) {
4073         ViceLog(0,
4074                 ("SAFSS_Rename(): Old file %s uniquifier mismatch\n",
4075                  OldName));
4076         VTakeOffline(volptr);
4077         errorCode = EIO;
4078         goto Bad_Rename;
4079     }
4080
4081     if (fileptr->disk.type != vDirectory && oldvptr != newvptr
4082         && fileptr->disk.linkCount != 1) {
4083         /*
4084          * Hard links exist to this file - cannot move one of the links to
4085          * a new directory because of AFS restrictions (this is the same
4086          * reason that links cannot be made across directories, i.e.
4087          * access lists)
4088          */
4089         errorCode = EXDEV;
4090         goto Bad_Rename;
4091     }
4092
4093     /* Lookup the new file  */
4094     if (!(Lookup(&newdir, NewName, &newFileFid))) {
4095         if (readonlyServer) {
4096             errorCode = VREADONLY;
4097             goto Bad_Rename;
4098         }
4099         if (!(newrights & PRSFS_DELETE)) {
4100             errorCode = EACCES;
4101             goto Bad_Rename;
4102         }
4103         if (newFileFid.Vnode == oldvptr->vnodeNumber
4104             || newFileFid.Vnode == newvptr->vnodeNumber
4105             || newFileFid.Vnode == fileFid.Vnode) {
4106             errorCode = EINVAL;
4107             goto Bad_Rename;
4108         }
4109         newFileFid.Volume = V_id(volptr);
4110         newfileptr =
4111             VGetVnode(&errorCode, volptr, newFileFid.Vnode, WRITE_LOCK);
4112         if (errorCode != 0) {
4113             ViceLog(0,
4114                     ("SAFSS_Rename(): Error in VGetVnode() for new file %s, code %d\n",
4115                      NewName, errorCode));
4116             VTakeOffline(volptr);
4117             goto Bad_Rename;
4118         }
4119         if (fileptr->disk.uniquifier != fileFid.Unique) {
4120             ViceLog(0,
4121                     ("SAFSS_Rename(): New file %s uniquifier mismatch\n",
4122                      NewName));
4123             VTakeOffline(volptr);
4124             errorCode = EIO;
4125             goto Bad_Rename;
4126         }
4127         SetDirHandle(&newfiledir, newfileptr);
4128         /* Now check that we're moving directories over directories properly, etc.
4129          * return proper POSIX error codes:
4130          * if fileptr is a file and new is a dir: EISDIR.
4131          * if fileptr is a dir and new is a file: ENOTDIR.
4132          * Also, dir to be removed must be empty, of course.
4133          */
4134         if (newfileptr->disk.type == vDirectory) {
4135             if (fileptr->disk.type != vDirectory) {
4136                 errorCode = EISDIR;
4137                 goto Bad_Rename;
4138             }
4139             if ((IsEmpty(&newfiledir))) {
4140                 errorCode = EEXIST;
4141                 goto Bad_Rename;
4142             }
4143         } else {
4144             if (fileptr->disk.type == vDirectory) {
4145                 errorCode = ENOTDIR;
4146                 goto Bad_Rename;
4147             }
4148         }
4149     }
4150
4151     /*
4152      * ok - now we check that the old name is not above new name in the
4153      * directory structure.  This is to prevent removing a subtree alltogether
4154      */
4155     if ((oldvptr != newvptr) && (fileptr->disk.type == vDirectory)) {
4156         afs_int32 forpass = 0, vnum = 0, top = 0;
4157         for (testnode = newvptr->disk.parent; testnode != 0; forpass++) {
4158             if (testnode > vnum) vnum = testnode;
4159             if (forpass > vnum) {
4160                 errorCode = FSERR_ELOOP;
4161                 goto Bad_Rename;
4162             }
4163             if (testnode == oldvptr->vnodeNumber) {
4164                 testnode = oldvptr->disk.parent;
4165                 continue;
4166             }
4167             if ((testnode == fileptr->vnodeNumber)
4168                 || (testnode == newvptr->vnodeNumber)) {
4169                 errorCode = FSERR_ELOOP;
4170                 goto Bad_Rename;
4171             }
4172             if ((newfileptr) && (testnode == newfileptr->vnodeNumber)) {
4173                 errorCode = FSERR_ELOOP;
4174                 goto Bad_Rename;
4175             }
4176             if (testnode == 1) top = 1;
4177             testvptr = VGetVnode(&errorCode, volptr, testnode, READ_LOCK);
4178             osi_Assert(errorCode == 0);
4179             testnode = testvptr->disk.parent;
4180             VPutVnode(&errorCode, testvptr);
4181             if ((top == 1) && (testnode != 0)) {
4182                 VTakeOffline(volptr);
4183                 ViceLog(0,
4184                         ("Volume %u now offline, must be salvaged.\n",
4185                          volptr->hashid));
4186                 errorCode = EIO;
4187                 goto Bad_Rename;
4188             }
4189             osi_Assert(errorCode == 0);
4190         }
4191     }
4192
4193     if (fileptr->disk.type == vDirectory) {
4194         SetDirHandle(&filedir, fileptr);
4195         if (oldvptr != newvptr) {
4196             /* we always need to update .. if we've moving fileptr to a
4197              * different directory */
4198             updatefile = 1;
4199         } else {
4200             struct AFSFid unused;
4201
4202             code = Lookup(&filedir, "..", &unused);
4203             if (code == ENOENT) {
4204                 /* only update .. if it doesn't already exist */
4205                 updatefile = 1;
4206             }
4207         }
4208     }
4209
4210     /* Do the CopyonWrite first before modifying anything else. Copying is
4211      * required when we have to change entries for ..
4212      */
4213     if (updatefile && (fileptr->disk.cloned)) {
4214         ViceLog(25, ("Rename : calling CopyOnWrite on  target dir\n"));
4215         if ((errorCode = CopyOnWrite(fileptr, volptr, 0, MAXFSIZE)))
4216             goto Bad_Rename;
4217     }
4218
4219     /* If the new name exists already, delete it and the file it points to */
4220     doDelete = 0;
4221     if (newfileptr) {
4222         /* Delete NewName from its directory */
4223         code = Delete(&newdir, NewName);
4224         osi_Assert(code == 0);
4225
4226         /* Drop the link count */
4227         newfileptr->disk.linkCount--;
4228         if (newfileptr->disk.linkCount == 0) {  /* Link count 0 - delete */
4229             afs_fsize_t newSize;
4230             VN_GET_LEN(newSize, newfileptr);
4231             VAdjustDiskUsage((Error *) & errorCode, volptr,
4232                              (afs_sfsize_t) - nBlocks(newSize), 0);
4233             if (VN_GET_INO(newfileptr)) {
4234                 IH_REALLYCLOSE(newfileptr->handle);
4235                 errorCode =
4236                     IH_DEC(V_linkHandle(volptr), VN_GET_INO(newfileptr),
4237                            V_parentId(volptr));
4238                 IH_RELEASE(newfileptr->handle);
4239                 if (errorCode == -1) {
4240                     ViceLog(0,
4241                             ("Del: inode=%s, name=%s, errno=%d\n",
4242                              PrintInode(stmp, VN_GET_INO(newfileptr)),
4243                              NewName, errno));
4244                     if ((errno != ENOENT) && (errno != EIO)
4245                         && (errno != ENXIO))
4246                         ViceLog(0, ("Do we need to fsck?"));
4247                 }
4248             }
4249             VN_SET_INO(newfileptr, (Inode) 0);
4250             newfileptr->delete = 1;     /* Mark NewName vnode to delete */
4251             doDelete = 1;
4252         } else {
4253             /* Link count did not drop to zero.
4254              * Mark NewName vnode as changed - updates stime.
4255              */
4256             newfileptr->changed_newTime = 1;
4257         }
4258     }
4259
4260     /*
4261      * If the create below fails, and the delete above worked, we have
4262      * removed the new name and not replaced it.  This is not very likely,
4263      * but possible.  We could try to put the old file back, but it is
4264      * highly unlikely that it would work since it would involve issuing
4265      * another create.
4266      */
4267     if ((errorCode = Create(&newdir, (char *)NewName, &fileFid)))
4268         goto Bad_Rename;
4269
4270     /* Delete the old name */
4271     osi_Assert(Delete(&olddir, (char *)OldName) == 0);
4272
4273     /* if the directory length changes, reflect it in the statistics */
4274 #if FS_STATS_DETAILED
4275     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4276                              oldvptr->disk.linkCount, client->InSameNetwork);
4277     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4278                              newvptr->disk.linkCount, client->InSameNetwork);
4279 #else
4280     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4281                              oldvptr->disk.linkCount);
4282     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4283                              newvptr->disk.linkCount);
4284 #endif /* FS_STATS_DETAILED */
4285
4286     if (oldvptr == newvptr)
4287         oldvptr->disk.dataVersion--;    /* Since it was bumped by 2! */
4288
4289     if (fileptr->disk.parent != newvptr->vnodeNumber) {
4290         fileptr->disk.parent = newvptr->vnodeNumber;
4291         fileptr->changed_newTime = 1;
4292     }
4293
4294     /* if we are dealing with a rename of a directory, and we need to
4295      * update the .. entry of that directory */
4296     if (updatefile) {
4297         osi_Assert(!fileptr->disk.cloned);
4298
4299         fileptr->changed_newTime = 1;   /* status change of moved file */
4300
4301         /* fix .. to point to the correct place */
4302         Delete(&filedir, ".."); /* No assert--some directories may be bad */
4303         osi_Assert(Create(&filedir, "..", NewDirFid) == 0);
4304         fileptr->disk.dataVersion++;
4305
4306         /* if the parent directories are different the link counts have to be   */
4307         /* changed due to .. in the renamed directory */
4308         if (oldvptr != newvptr) {
4309             oldvptr->disk.linkCount--;
4310             newvptr->disk.linkCount++;
4311         }
4312     }
4313
4314     /* set up return status */
4315     GetStatus(oldvptr, OutOldDirStatus, rights, anyrights, 0);
4316     GetStatus(newvptr, OutNewDirStatus, newrights, newanyrights, 0);
4317     if (newfileptr && doDelete) {
4318         DeleteFileCallBacks(&newFileFid);       /* no other references */
4319     }
4320
4321     DFlush();
4322
4323     /* convert the write locks to a read locks before breaking callbacks */
4324     VVnodeWriteToRead(&errorCode, newvptr);
4325     osi_Assert(!errorCode || errorCode == VSALVAGE);
4326     if (oldvptr != newvptr) {
4327         VVnodeWriteToRead(&errorCode, oldvptr);
4328         osi_Assert(!errorCode || errorCode == VSALVAGE);
4329     }
4330     if (newfileptr && !doDelete) {
4331         /* convert the write lock to a read lock before breaking callbacks */
4332         VVnodeWriteToRead(&errorCode, newfileptr);
4333         osi_Assert(!errorCode || errorCode == VSALVAGE);
4334     }
4335
4336     /* break call back on NewDirFid, OldDirFid, NewDirFid and newFileFid  */
4337     BreakCallBack(client->host, NewDirFid, 0);
4338     if (oldvptr != newvptr) {
4339         BreakCallBack(client->host, OldDirFid, 0);
4340     }
4341     if (updatefile) {
4342         /* if a dir moved, .. changed */
4343         /* we do not give an AFSFetchStatus structure back to the
4344          * originating client, and the file's status has changed, so be
4345          * sure to send a callback break. In theory the client knows
4346          * enough to know that the callback could be broken implicitly,
4347          * but that may not be clear, and some client implementations
4348          * may not know to. */
4349         BreakCallBack(client->host, &fileFid, 1);
4350     }
4351     if (newfileptr) {
4352         /* Note:  it is not necessary to break the callback */
4353         if (doDelete)
4354             DeleteFileCallBacks(&newFileFid);   /* no other references */
4355         else
4356             /* other's still exist (with wrong link count) */
4357             BreakCallBack(client->host, &newFileFid, 1);
4358     }
4359
4360   Bad_Rename:
4361     if (newfileptr) {
4362         VPutVnode(&fileCode, newfileptr);
4363         osi_Assert(fileCode == 0);
4364     }
4365     (void)PutVolumePackage(fileptr, (newvptr && newvptr != oldvptr ?
4366                                      newvptr : 0), oldvptr, volptr, &client);
4367     FidZap(&olddir);
4368     FidZap(&newdir);
4369     FidZap(&filedir);
4370     FidZap(&newfiledir);
4371     ViceLog(2, ("SAFS_Rename returns %d\n", errorCode));
4372     return errorCode;
4373
4374 }                               /*SAFSS_Rename */
4375
4376
4377 afs_int32
4378 SRXAFS_Rename(struct rx_call * acall, struct AFSFid * OldDirFid,
4379               char *OldName, struct AFSFid * NewDirFid, char *NewName,
4380               struct AFSFetchStatus * OutOldDirStatus,
4381               struct AFSFetchStatus * OutNewDirStatus,
4382               struct AFSVolSync * Sync)
4383 {
4384     afs_int32 code;
4385     struct rx_connection *tcon;
4386     struct host *thost;
4387     struct client *t_client = NULL;     /* tmp ptr to client data */
4388 #if FS_STATS_DETAILED
4389     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4390     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4391     struct timeval elapsedTime; /* Transfer time */
4392
4393     /*
4394      * Set our stats pointer, remember when the RPC operation started, and
4395      * tally the operation.
4396      */
4397     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RENAME]);
4398     FS_LOCK;
4399     (opP->numOps)++;
4400     FS_UNLOCK;
4401     FT_GetTimeOfDay(&opStartTime, 0);
4402 #endif /* FS_STATS_DETAILED */
4403
4404     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4405         goto Bad_Rename;
4406
4407     code =
4408         SAFSS_Rename(acall, OldDirFid, OldName, NewDirFid, NewName,
4409                      OutOldDirStatus, OutNewDirStatus, Sync);
4410
4411   Bad_Rename:
4412     code = CallPostamble(tcon, code, thost);
4413
4414     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4415
4416 #if FS_STATS_DETAILED
4417     FT_GetTimeOfDay(&opStopTime, 0);
4418     if (code == 0) {
4419         FS_LOCK;
4420         (opP->numSuccesses)++;
4421         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4422         fs_stats_AddTo((opP->sumTime), elapsedTime);
4423         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4424         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4425             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4426         }
4427         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4428             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4429         }
4430         FS_UNLOCK;
4431     }
4432 #endif /* FS_STATS_DETAILED */
4433
4434     osi_auditU(acall, RenameFileEvent, code,
4435                AUD_ID, t_client ? t_client->ViceId : 0,
4436                AUD_FID, OldDirFid, AUD_STR, OldName,
4437                AUD_FID, NewDirFid, AUD_STR, NewName, AUD_END);
4438     return code;
4439
4440 }                               /*SRXAFS_Rename */
4441
4442
4443 /*
4444  * This routine is called exclusively by SRXAFS_Symlink(), and should be
4445  * merged into it when possible.
4446  */
4447 static afs_int32
4448 SAFSS_Symlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4449               char *LinkContents, struct AFSStoreStatus *InStatus,
4450               struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
4451               struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4452 {
4453     Vnode *parentptr = 0;       /* vnode of input Directory */
4454     Vnode *targetptr = 0;       /* vnode of the new link */
4455     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4456     Error errorCode = 0;                /* error code */
4457     afs_sfsize_t len;
4458     int code = 0;
4459     DirHandle dir;              /* Handle for dir package I/O */
4460     Volume *volptr = 0;         /* pointer to the volume header */
4461     struct client *client = 0;  /* pointer to client structure */
4462     afs_int32 rights, anyrights;        /* rights for this and any user */
4463     struct client *t_client;    /* tmp ptr to client data */
4464     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4465     FdHandle_t *fdP;
4466     struct rx_connection *tcon = rx_ConnectionOf(acall);
4467
4468     FidZero(&dir);
4469
4470     /* Get ptr to client data for user Id for logging */
4471     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4472     logHostAddr.s_addr = rxr_HostOf(tcon);
4473     ViceLog(1,
4474             ("SAFS_Symlink %s to %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4475              LinkContents, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4476              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4477     FS_LOCK;
4478     AFSCallStats.Symlink++, AFSCallStats.TotalCalls++;
4479     FS_UNLOCK;
4480     if (!FileNameOK(Name)) {
4481         errorCode = EINVAL;
4482         goto Bad_SymLink;
4483     }
4484
4485     /*
4486      * Get the vnode and volume for the parent dir along with the caller's
4487      * rights to it
4488      */
4489     if ((errorCode =
4490          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4491                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4492                           &rights, &anyrights))) {
4493         goto Bad_SymLink;
4494     }
4495
4496     /* set volume synchronization information */
4497     SetVolumeSync(Sync, volptr);
4498
4499     /* Does the caller has insert (and write) access to the parent directory? */
4500     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4501         goto Bad_SymLink;
4502     }
4503
4504     /*
4505      * If we're creating a mount point (any x bits clear), we must have
4506      * administer access to the directory, too.  Always allow sysadmins
4507      * to do this.
4508      */
4509     if ((InStatus->Mask & AFS_SETMODE) && !(InStatus->UnixModeBits & 0111)) {
4510         if (readonlyServer) {
4511             errorCode = VREADONLY;
4512             goto Bad_SymLink;
4513         }
4514         /*
4515          * We have a mountpoint, 'cause we're trying to set the Unix mode
4516          * bits to something with some x bits missing (default mode bits
4517          * if AFS_SETMODE is false is 0777)
4518          */
4519         if (VanillaUser(client) && !(rights & PRSFS_ADMINISTER)) {
4520             errorCode = EACCES;
4521             goto Bad_SymLink;
4522         }
4523     }
4524
4525     /* get a new vnode for the symlink and set it up */
4526     if ((errorCode =
4527          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
4528                         vSymlink, nBlocks(strlen((char *)LinkContents))))) {
4529         goto Bad_SymLink;
4530     }
4531
4532     /* update the status of the parent vnode */
4533 #if FS_STATS_DETAILED
4534     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4535                              parentptr->disk.linkCount,
4536                              client->InSameNetwork);
4537 #else
4538     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4539                              parentptr->disk.linkCount);
4540 #endif /* FS_STATS_DETAILED */
4541
4542     /* update the status of the new symbolic link file vnode */
4543     Update_TargetVnodeStatus(targetptr, TVS_SLINK, client, InStatus,
4544                              parentptr, volptr, strlen((char *)LinkContents));
4545
4546     /* Write the contents of the symbolic link name into the target inode */
4547     fdP = IH_OPEN(targetptr->handle);
4548     if (fdP == NULL) {
4549         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4550                                volptr, &client);
4551         VTakeOffline(volptr);
4552         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
4553                     volptr->hashid));
4554         return EIO;
4555     }
4556     len = strlen((char *) LinkContents);
4557     code = (len == FDH_PWRITE(fdP, (char *) LinkContents, len, 0)) ? 0 : VDISKFULL;
4558     if (code)
4559         ViceLog(0, ("SAFSS_Symlink FDH_PWRITE failed for len=%d, Fid=%u.%d.%d\n", (int)len, OutFid->Volume, OutFid->Vnode, OutFid->Unique));
4560     FDH_CLOSE(fdP);
4561     /*
4562      * Set up and return modified status for the parent dir and new symlink
4563      * to caller.
4564      */
4565     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4566     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4567
4568     /* convert the write lock to a read lock before breaking callbacks */
4569     VVnodeWriteToRead(&errorCode, parentptr);
4570     osi_Assert(!errorCode || errorCode == VSALVAGE);
4571
4572     /* break call back on the parent dir */
4573     BreakCallBack(client->host, DirFid, 0);
4574
4575   Bad_SymLink:
4576     /* Write the all modified vnodes (parent, new files) and volume back */
4577     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4578                            volptr, &client);
4579     FidZap(&dir);
4580     ViceLog(2, ("SAFS_Symlink returns %d\n", errorCode));
4581     return ( errorCode ? errorCode : code );
4582
4583 }                               /*SAFSS_Symlink */
4584
4585
4586 afs_int32
4587 SRXAFS_Symlink(struct rx_call *acall,   /* Rx call */
4588                struct AFSFid *DirFid,   /* Parent dir's fid */
4589                char *Name,              /* File name to create */
4590                char *LinkContents,      /* Contents of the new created file */
4591                struct AFSStoreStatus *InStatus, /* Input status for the new symbolic link */
4592                struct AFSFid *OutFid,   /* Fid for newly created symbolic link */
4593                struct AFSFetchStatus *OutFidStatus,     /* Output status for new symbolic link */
4594                struct AFSFetchStatus *OutDirStatus,     /* Output status for parent dir */
4595                struct AFSVolSync *Sync)
4596 {
4597     afs_int32 code;
4598     struct rx_connection *tcon;
4599     struct host *thost;
4600     struct client *t_client = NULL;     /* tmp ptr to client data */
4601 #if FS_STATS_DETAILED
4602     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4603     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4604     struct timeval elapsedTime; /* Transfer time */
4605
4606     /*
4607      * Set our stats pointer, remember when the RPC operation started, and
4608      * tally the operation.
4609      */
4610     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SYMLINK]);
4611     FS_LOCK;
4612     (opP->numOps)++;
4613     FS_UNLOCK;
4614     FT_GetTimeOfDay(&opStartTime, 0);
4615 #endif /* FS_STATS_DETAILED */
4616
4617     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4618         goto Bad_Symlink;
4619
4620     code =
4621         SAFSS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4622                       OutFidStatus, OutDirStatus, Sync);
4623
4624   Bad_Symlink:
4625     code = CallPostamble(tcon, code, thost);
4626
4627     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4628
4629 #if FS_STATS_DETAILED
4630     FT_GetTimeOfDay(&opStopTime, 0);
4631     if (code == 0) {
4632         FS_LOCK;
4633         (opP->numSuccesses)++;
4634         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4635         fs_stats_AddTo((opP->sumTime), elapsedTime);
4636         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4637         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4638             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4639         }
4640         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4641             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4642         }
4643         FS_UNLOCK;
4644     }
4645 #endif /* FS_STATS_DETAILED */
4646
4647     osi_auditU(acall, SymlinkEvent, code,
4648                AUD_ID, t_client ? t_client->ViceId : 0,
4649                AUD_FID, DirFid, AUD_STR, Name,
4650                AUD_FID, OutFid, AUD_STR, LinkContents, AUD_END);
4651     return code;
4652
4653 }                               /*SRXAFS_Symlink */
4654
4655
4656 /*
4657  * This routine is called exclusively by SRXAFS_Link(), and should be
4658  * merged into it when possible.
4659  */
4660 static afs_int32
4661 SAFSS_Link(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4662            struct AFSFid *ExistingFid, struct AFSFetchStatus *OutFidStatus,
4663            struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4664 {
4665     Vnode *parentptr = 0;       /* vnode of input Directory */
4666     Vnode *targetptr = 0;       /* vnode of the new file */
4667     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4668     Volume *volptr = 0;         /* pointer to the volume header */
4669     Error errorCode = 0;                /* error code */
4670     DirHandle dir;              /* Handle for dir package I/O */
4671     struct client *client = 0;  /* pointer to client structure */
4672     afs_int32 rights, anyrights;        /* rights for this and any user */
4673     struct client *t_client;    /* tmp ptr to client data */
4674     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4675     struct rx_connection *tcon = rx_ConnectionOf(acall);
4676
4677     FidZero(&dir);
4678
4679     /* Get ptr to client data for user Id for logging */
4680     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4681     logHostAddr.s_addr = rxr_HostOf(tcon);
4682     ViceLog(1,
4683             ("SAFS_Link %s,     Did = %u.%u.%u, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
4684              Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4685              ExistingFid->Volume, ExistingFid->Vnode, ExistingFid->Unique,
4686              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4687     FS_LOCK;
4688     AFSCallStats.Link++, AFSCallStats.TotalCalls++;
4689     FS_UNLOCK;
4690     if (DirFid->Volume != ExistingFid->Volume) {
4691         errorCode = EXDEV;
4692         goto Bad_Link;
4693     }
4694     if (!FileNameOK(Name)) {
4695         errorCode = EINVAL;
4696         goto Bad_Link;
4697     }
4698
4699     /*
4700      * Get the vnode and volume for the parent dir along with the caller's
4701      * rights to it
4702      */
4703     if ((errorCode =
4704          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4705                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4706                           &rights, &anyrights))) {
4707         goto Bad_Link;
4708     }
4709
4710     /* set volume synchronization information */
4711     SetVolumeSync(Sync, volptr);
4712
4713     /* Can the caller insert into the parent directory? */
4714     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4715         goto Bad_Link;
4716     }
4717
4718     if (((DirFid->Vnode & 1) && (ExistingFid->Vnode & 1)) || (DirFid->Vnode == ExistingFid->Vnode)) {   /* at present, */
4719         /* AFS fileservers always have directory vnodes that are odd.   */
4720         errorCode = EISDIR;
4721         goto Bad_Link;
4722     }
4723
4724     /* get the file vnode  */
4725     if ((errorCode =
4726          CheckVnode(ExistingFid, &volptr, &targetptr, WRITE_LOCK))) {
4727         goto Bad_Link;
4728     }
4729     if (targetptr->disk.type != vFile) {
4730         errorCode = EISDIR;
4731         goto Bad_Link;
4732     }
4733     if (targetptr->disk.parent != DirFid->Vnode) {
4734         errorCode = EXDEV;
4735         goto Bad_Link;
4736     }
4737     if (parentptr->disk.cloned) {
4738         ViceLog(25, ("Link : calling CopyOnWrite on  target dir\n"));
4739         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE)))
4740             goto Bad_Link;      /* disk full error */
4741     }
4742
4743     /* add the name to the directory */
4744     SetDirHandle(&dir, parentptr);
4745     if ((errorCode = Create(&dir, (char *)Name, ExistingFid)))
4746         goto Bad_Link;
4747     DFlush();
4748
4749     /* update the status in the parent vnode */
4750     /**WARNING** --> disk.author SHOULDN'T be modified???? */
4751 #if FS_STATS_DETAILED
4752     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4753                              parentptr->disk.linkCount,
4754                              client->InSameNetwork);
4755 #else
4756     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4757                              parentptr->disk.linkCount);
4758 #endif /* FS_STATS_DETAILED */
4759
4760     targetptr->disk.linkCount++;
4761     targetptr->disk.author = client->ViceId;
4762     targetptr->changed_newTime = 1;     /* Status change of linked-to file */
4763
4764     /* set up return status */
4765     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4766     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4767
4768     /* convert the write locks to read locks before breaking callbacks */
4769     VVnodeWriteToRead(&errorCode, targetptr);
4770     osi_Assert(!errorCode || errorCode == VSALVAGE);
4771     VVnodeWriteToRead(&errorCode, parentptr);
4772     osi_Assert(!errorCode || errorCode == VSALVAGE);
4773
4774     /* break call back on DirFid */
4775     BreakCallBack(client->host, DirFid, 0);
4776     /*
4777      * We also need to break the callback for the file that is hard-linked since part
4778      * of its status (like linkcount) is changed
4779      */
4780     BreakCallBack(client->host, ExistingFid, 0);
4781
4782   Bad_Link:
4783     /* Write the all modified vnodes (parent, new files) and volume back */
4784     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4785                            volptr, &client);
4786     FidZap(&dir);
4787     ViceLog(2, ("SAFS_Link returns %d\n", errorCode));
4788     return errorCode;
4789
4790 }                               /*SAFSS_Link */
4791
4792
4793 afs_int32
4794 SRXAFS_Link(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4795             struct AFSFid * ExistingFid, struct AFSFetchStatus * OutFidStatus,
4796             struct AFSFetchStatus * OutDirStatus, struct AFSVolSync * Sync)
4797 {
4798     afs_int32 code;
4799     struct rx_connection *tcon;
4800     struct host *thost;
4801     struct client *t_client = NULL;     /* tmp ptr to client data */
4802 #if FS_STATS_DETAILED
4803     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4804     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4805     struct timeval elapsedTime; /* Transfer time */
4806
4807     /*
4808      * Set our stats pointer, remember when the RPC operation started, and
4809      * tally the operation.
4810      */
4811     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_LINK]);
4812     FS_LOCK;
4813     (opP->numOps)++;
4814     FS_UNLOCK;
4815     FT_GetTimeOfDay(&opStartTime, 0);
4816 #endif /* FS_STATS_DETAILED */
4817
4818     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4819         goto Bad_Link;
4820
4821     code =
4822         SAFSS_Link(acall, DirFid, Name, ExistingFid, OutFidStatus,
4823                    OutDirStatus, Sync);
4824
4825   Bad_Link:
4826     code = CallPostamble(tcon, code, thost);
4827
4828     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4829
4830 #if FS_STATS_DETAILED
4831     FT_GetTimeOfDay(&opStopTime, 0);
4832     if (code == 0) {
4833         FS_LOCK;
4834         (opP->numSuccesses)++;
4835         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4836         fs_stats_AddTo((opP->sumTime), elapsedTime);
4837         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4838         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4839             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4840         }
4841         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4842             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4843         }
4844         FS_UNLOCK;
4845     }
4846 #endif /* FS_STATS_DETAILED */
4847
4848     osi_auditU(acall, LinkEvent, code,
4849                AUD_ID, t_client ? t_client->ViceId : 0,
4850                AUD_FID, DirFid, AUD_STR, Name,
4851                AUD_FID, ExistingFid, AUD_END);
4852     return code;
4853
4854 }                               /*SRXAFS_Link */
4855
4856
4857 /*
4858  * This routine is called exclusively by SRXAFS_MakeDir(), and should be
4859  * merged into it when possible.
4860  */
4861 static afs_int32
4862 SAFSS_MakeDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4863               struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
4864               struct AFSFetchStatus *OutFidStatus,
4865               struct AFSFetchStatus *OutDirStatus,
4866               struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
4867 {
4868     Vnode *parentptr = 0;       /* vnode of input Directory */
4869     Vnode *targetptr = 0;       /* vnode of the new file */
4870     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4871     Volume *volptr = 0;         /* pointer to the volume header */
4872     Error errorCode = 0;                /* error code */
4873     struct acl_accessList *newACL;      /* Access list */
4874     int newACLSize;             /* Size of access list */
4875     DirHandle dir;              /* Handle for dir package I/O */
4876     DirHandle parentdir;        /* Handle for dir package I/O */
4877     struct client *client = 0;  /* pointer to client structure */
4878     afs_int32 rights, anyrights;        /* rights for this and any user */
4879     struct client *t_client;    /* tmp ptr to client data */
4880     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4881     struct rx_connection *tcon = rx_ConnectionOf(acall);
4882
4883     FidZero(&dir);
4884     FidZero(&parentdir);
4885
4886     /* Get ptr to client data for user Id for logging */
4887     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4888     logHostAddr.s_addr = rxr_HostOf(tcon);
4889     ViceLog(1,
4890             ("SAFS_MakeDir %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4891              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4892              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4893     FS_LOCK;
4894     AFSCallStats.MakeDir++, AFSCallStats.TotalCalls++;
4895     FS_UNLOCK;
4896     if (!FileNameOK(Name)) {
4897         errorCode = EINVAL;
4898         goto Bad_MakeDir;
4899     }
4900
4901     /*
4902      * Get the vnode and volume for the parent dir along with the caller's
4903      * rights to it.
4904      */
4905     if ((errorCode =
4906          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4907                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4908                           &rights, &anyrights))) {
4909         goto Bad_MakeDir;
4910     }
4911
4912     /* set volume synchronization information */
4913     SetVolumeSync(Sync, volptr);
4914
4915     /* Write access to the parent directory? */
4916 #ifdef DIRCREATE_NEED_WRITE
4917     /*
4918      * requires w access for the user to create a directory. this
4919      * closes a loophole in the current security arrangement, since a
4920      * user with i access only can create a directory and get the
4921      * implcit a access that goes with dir ownership, and proceed to
4922      * subvert quota in the volume.
4923      */
4924     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))
4925         || (errorCode = CheckWriteMode(parentptr, rights, PRSFS_WRITE))) {
4926 #else
4927     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4928 #endif /* DIRCREATE_NEED_WRITE */
4929         goto Bad_MakeDir;
4930     }
4931 #define EMPTYDIRBLOCKS 2
4932     /* get a new vnode and set it up */
4933     if ((errorCode =
4934          Alloc_NewVnode(parentptr, &parentdir, volptr, &targetptr, Name,
4935                         OutFid, vDirectory, EMPTYDIRBLOCKS))) {
4936         goto Bad_MakeDir;
4937     }
4938
4939     /* Update the status for the parent dir */
4940 #if FS_STATS_DETAILED
4941     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4942                              parentptr->disk.linkCount + 1,
4943                              client->InSameNetwork);
4944 #else
4945     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4946                              parentptr->disk.linkCount + 1);
4947 #endif /* FS_STATS_DETAILED */
4948
4949     /* Point to target's ACL buffer and copy the parent's ACL contents to it */
4950     osi_Assert((SetAccessList
4951             (&targetptr, &volptr, &newACL, &newACLSize,
4952              &parentwhentargetnotdir, (AFSFid *) 0, 0)) == 0);
4953     osi_Assert(parentwhentargetnotdir == 0);
4954     memcpy((char *)newACL, (char *)VVnodeACL(parentptr), VAclSize(parentptr));
4955
4956     /* update the status for the target vnode */
4957     Update_TargetVnodeStatus(targetptr, TVS_MKDIR, client, InStatus,
4958                              parentptr, volptr, 0);
4959
4960     /* Actually create the New directory in the directory package */
4961     SetDirHandle(&dir, targetptr);
4962     osi_Assert(!(MakeDir(&dir, (afs_int32 *)OutFid, (afs_int32 *)DirFid)));
4963     DFlush();
4964     VN_SET_LEN(targetptr, (afs_fsize_t) Length(&dir));
4965
4966     /* set up return status */
4967     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4968     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4969
4970     /* convert the write lock to a read lock before breaking callbacks */
4971     VVnodeWriteToRead(&errorCode, parentptr);
4972     osi_Assert(!errorCode || errorCode == VSALVAGE);
4973
4974     /* break call back on DirFid */
4975     BreakCallBack(client->host, DirFid, 0);
4976
4977     /* Return a callback promise to caller */
4978     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
4979
4980   Bad_MakeDir:
4981     /* Write the all modified vnodes (parent, new files) and volume back */
4982     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4983                            volptr, &client);
4984     FidZap(&dir);
4985     FidZap(&parentdir);
4986     ViceLog(2, ("SAFS_MakeDir returns %d\n", errorCode));
4987     return errorCode;
4988
4989 }                               /*SAFSS_MakeDir */
4990
4991
4992 afs_int32
4993 SRXAFS_MakeDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4994                struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
4995                struct AFSFetchStatus * OutFidStatus,
4996                struct AFSFetchStatus * OutDirStatus,
4997                struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
4998 {
4999     afs_int32 code;
5000     struct rx_connection *tcon;
5001     struct host *thost;
5002     struct client *t_client = NULL;     /* tmp ptr to client data */
5003 #if FS_STATS_DETAILED
5004     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5005     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5006     struct timeval elapsedTime; /* Transfer time */
5007
5008     /*
5009      * Set our stats pointer, remember when the RPC operation started, and
5010      * tally the operation.
5011      */
5012     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_MAKEDIR]);
5013     FS_LOCK;
5014     (opP->numOps)++;
5015     FS_UNLOCK;
5016     FT_GetTimeOfDay(&opStartTime, 0);
5017 #endif /* FS_STATS_DETAILED */
5018     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5019         goto Bad_MakeDir;
5020
5021     code =
5022         SAFSS_MakeDir(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
5023                       OutDirStatus, CallBack, Sync);
5024
5025   Bad_MakeDir:
5026     code = CallPostamble(tcon, code, thost);
5027
5028     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5029
5030 #if FS_STATS_DETAILED
5031     FT_GetTimeOfDay(&opStopTime, 0);
5032     if (code == 0) {
5033         FS_LOCK;
5034         (opP->numSuccesses)++;
5035         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5036         fs_stats_AddTo((opP->sumTime), elapsedTime);
5037         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5038         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5039             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5040         }
5041         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5042             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5043         }
5044         FS_UNLOCK;
5045     }
5046 #endif /* FS_STATS_DETAILED */
5047
5048     osi_auditU(acall, MakeDirEvent, code,
5049                AUD_ID, t_client ? t_client->ViceId : 0,
5050                AUD_FID, DirFid, AUD_STR, Name,
5051                AUD_FID, OutFid, AUD_END);
5052     return code;
5053
5054 }                               /*SRXAFS_MakeDir */
5055
5056
5057 /*
5058  * This routine is called exclusively by SRXAFS_RemoveDir(), and should be
5059  * merged into it when possible.
5060  */
5061 static afs_int32
5062 SAFSS_RemoveDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
5063                 struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
5064 {
5065     Vnode *parentptr = 0;       /* vnode of input Directory */
5066     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5067     Vnode *targetptr = 0;       /* file to be deleted */
5068     AFSFid fileFid;             /* area for Fid from the directory */
5069     Error errorCode = 0;                /* error code */
5070     DirHandle dir;              /* Handle for dir package I/O */
5071     Volume *volptr = 0;         /* pointer to the volume header */
5072     struct client *client = 0;  /* pointer to client structure */
5073     afs_int32 rights, anyrights;        /* rights for this and any user */
5074     struct client *t_client;    /* tmp ptr to client data */
5075     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5076     struct rx_connection *tcon = rx_ConnectionOf(acall);
5077
5078     FidZero(&dir);
5079
5080     /* Get ptr to client data for user Id for logging */
5081     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5082     logHostAddr.s_addr = rxr_HostOf(tcon);
5083     ViceLog(1,
5084             ("SAFS_RemoveDir    %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
5085              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
5086              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5087     FS_LOCK;
5088     AFSCallStats.RemoveDir++, AFSCallStats.TotalCalls++;
5089     FS_UNLOCK;
5090     /*
5091      * Get the vnode and volume for the parent dir along with the caller's
5092      * rights to it
5093      */
5094     if ((errorCode =
5095          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
5096                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5097                           &rights, &anyrights))) {
5098         goto Bad_RemoveDir;
5099     }
5100
5101     /* set volume synchronization information */
5102     SetVolumeSync(Sync, volptr);
5103
5104     /* Does the caller has delete (&write) access to the parent dir? */
5105     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
5106         goto Bad_RemoveDir;
5107     }
5108
5109     /* Do the actual delete of the desired (empty) directory, Name */
5110     if ((errorCode =
5111          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
5112                       MustBeDIR))) {
5113         goto Bad_RemoveDir;
5114     }
5115
5116     /* Update the status for the parent dir; link count is also adjusted */
5117 #if FS_STATS_DETAILED
5118     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
5119                              parentptr->disk.linkCount - 1,
5120                              client->InSameNetwork);
5121 #else
5122     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
5123                              parentptr->disk.linkCount - 1);
5124 #endif /* FS_STATS_DETAILED */
5125
5126     /* Return to the caller the updated parent dir status */
5127     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
5128
5129     /*
5130      * Note: it is not necessary to break the callback on fileFid, since
5131      * refcount is now 0, so no one should be able to refer to the dir
5132      * any longer
5133      */
5134     DeleteFileCallBacks(&fileFid);
5135
5136     /* convert the write lock to a read lock before breaking callbacks */
5137     VVnodeWriteToRead(&errorCode, parentptr);
5138     osi_Assert(!errorCode || errorCode == VSALVAGE);
5139
5140     /* break call back on DirFid and fileFid */
5141     BreakCallBack(client->host, DirFid, 0);
5142
5143   Bad_RemoveDir:
5144     /* Write the all modified vnodes (parent, new files) and volume back */
5145     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
5146                            volptr, &client);
5147     FidZap(&dir);
5148     ViceLog(2, ("SAFS_RemoveDir returns %d\n", errorCode));
5149     return errorCode;
5150
5151 }                               /*SAFSS_RemoveDir */
5152
5153
5154 afs_int32
5155 SRXAFS_RemoveDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
5156                  struct AFSFetchStatus * OutDirStatus,
5157                  struct AFSVolSync * Sync)
5158 {
5159     afs_int32 code;
5160     struct rx_connection *tcon;
5161     struct host *thost;
5162     struct client *t_client = NULL;     /* tmp ptr to client data */
5163 #if FS_STATS_DETAILED
5164     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5165     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5166     struct timeval elapsedTime; /* Transfer time */
5167
5168     /*
5169      * Set our stats pointer, remember when the RPC operation started, and
5170      * tally the operation.
5171      */
5172     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEDIR]);
5173     FS_LOCK;
5174     (opP->numOps)++;
5175     FS_UNLOCK;
5176     FT_GetTimeOfDay(&opStartTime, 0);
5177 #endif /* FS_STATS_DETAILED */
5178
5179     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5180         goto Bad_RemoveDir;
5181
5182     code = SAFSS_RemoveDir(acall, DirFid, Name, OutDirStatus, Sync);
5183
5184   Bad_RemoveDir:
5185     code = CallPostamble(tcon, code, thost);
5186
5187     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5188
5189 #if FS_STATS_DETAILED
5190     FT_GetTimeOfDay(&opStopTime, 0);
5191     if (code == 0) {
5192         FS_LOCK;
5193         (opP->numSuccesses)++;
5194         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5195         fs_stats_AddTo((opP->sumTime), elapsedTime);
5196         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5197         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5198             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5199         }
5200         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5201             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5202         }
5203         FS_UNLOCK;
5204     }
5205 #endif /* FS_STATS_DETAILED */
5206
5207     osi_auditU(acall, RemoveDirEvent, code,
5208                AUD_ID, t_client ? t_client->ViceId : 0,
5209                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
5210     return code;
5211
5212 }                               /*SRXAFS_RemoveDir */
5213
5214
5215 /*
5216  * This routine is called exclusively by SRXAFS_SetLock(), and should be
5217  * merged into it when possible.
5218  */
5219 static afs_int32
5220 SAFSS_SetLock(struct rx_call *acall, struct AFSFid *Fid, ViceLockType type,
5221               struct AFSVolSync *Sync)
5222 {
5223     Vnode *targetptr = 0;       /* vnode of input file */
5224     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5225     Error errorCode = 0;                /* error code */
5226     Volume *volptr = 0;         /* pointer to the volume header */
5227     struct client *client = 0;  /* pointer to client structure */
5228     afs_int32 rights, anyrights;        /* rights for this and any user */
5229     struct client *t_client;    /* tmp ptr to client data */
5230     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5231     static char *locktype[4] = { "LockRead", "LockWrite", "LockExtend", "LockRelease" };
5232     struct rx_connection *tcon = rx_ConnectionOf(acall);
5233
5234     if (type != LockRead && type != LockWrite) {
5235         errorCode = EINVAL;
5236         goto Bad_SetLock;
5237     }
5238     /* Get ptr to client data for user Id for logging */
5239     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5240     logHostAddr.s_addr = rxr_HostOf(tcon);
5241     ViceLog(1,
5242             ("SAFS_SetLock type = %s Fid = %u.%u.%u, Host %s:%d, Id %d\n",
5243              locktype[(int)type], Fid->Volume, Fid->Vnode, Fid->Unique,
5244              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5245     FS_LOCK;
5246     AFSCallStats.SetLock++, AFSCallStats.TotalCalls++;
5247     FS_UNLOCK;
5248     /*
5249      * Get the vnode and volume for the desired file along with the caller's
5250      * rights to it
5251      */
5252     if ((errorCode =
5253          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5254                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5255                           &rights, &anyrights))) {
5256         goto Bad_SetLock;
5257     }
5258
5259     /* set volume synchronization information */
5260     SetVolumeSync(Sync, volptr);
5261
5262     /* Handle the particular type of set locking, type */
5263     errorCode = HandleLocking(targetptr, client, rights, type);
5264
5265   Bad_SetLock:
5266     /* Write the all modified vnodes (parent, new files) and volume back */
5267     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5268                            volptr, &client);
5269
5270     if ((errorCode == VREADONLY) && (type == LockRead))
5271         errorCode = 0;          /* allow read locks on RO volumes without saving state */
5272
5273     ViceLog(2, ("SAFS_SetLock returns %d\n", errorCode));
5274     return (errorCode);
5275
5276 }                               /*SAFSS_SetLock */
5277
5278
5279 afs_int32
5280 SRXAFS_OldSetLock(struct rx_call * acall, struct AFSFid * Fid,
5281                   ViceLockType type, struct AFSVolSync * Sync)
5282 {
5283     return SRXAFS_SetLock(acall, Fid, type, Sync);
5284 }                               /*SRXAFS_OldSetLock */
5285
5286
5287 afs_int32
5288 SRXAFS_SetLock(struct rx_call * acall, struct AFSFid * Fid, ViceLockType type,
5289                struct AFSVolSync * Sync)
5290 {
5291     afs_int32 code;
5292     struct rx_connection *tcon;
5293     struct host *thost;
5294     struct client *t_client = NULL;     /* tmp ptr to client data */
5295 #if FS_STATS_DETAILED
5296     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5297     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5298     struct timeval elapsedTime; /* Transfer time */
5299
5300     /*
5301      * Set our stats pointer, remember when the RPC operation started, and
5302      * tally the operation.
5303      */
5304     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETLOCK]);
5305     FS_LOCK;
5306     (opP->numOps)++;
5307     FS_UNLOCK;
5308     FT_GetTimeOfDay(&opStartTime, 0);
5309 #endif /* FS_STATS_DETAILED */
5310
5311     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5312         goto Bad_SetLock;
5313
5314     code = SAFSS_SetLock(acall, Fid, type, Sync);
5315
5316   Bad_SetLock:
5317     code = CallPostamble(tcon, code, thost);
5318
5319     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5320
5321 #if FS_STATS_DETAILED
5322     FT_GetTimeOfDay(&opStopTime, 0);
5323     if (code == 0) {
5324         FS_LOCK;
5325         (opP->numSuccesses)++;
5326         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5327         fs_stats_AddTo((opP->sumTime), elapsedTime);
5328         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5329         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5330             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5331         }
5332         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5333             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5334         }
5335         FS_UNLOCK;
5336     }
5337 #endif /* FS_STATS_DETAILED */
5338
5339     osi_auditU(acall, SetLockEvent, code,
5340                AUD_ID, t_client ? t_client->ViceId : 0,
5341                AUD_FID, Fid, AUD_LONG, type, AUD_END);
5342     return code;
5343 }                               /*SRXAFS_SetLock */
5344
5345
5346 /*
5347  * This routine is called exclusively by SRXAFS_ExtendLock(), and should be
5348  * merged into it when possible.
5349  */
5350 static afs_int32
5351 SAFSS_ExtendLock(struct rx_call *acall, struct AFSFid *Fid,
5352                  struct AFSVolSync *Sync)
5353 {
5354     Vnode *targetptr = 0;       /* vnode of input file */
5355     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5356     Error errorCode = 0;                /* error code */
5357     Volume *volptr = 0;         /* pointer to the volume header */
5358     struct client *client = 0;  /* pointer to client structure */
5359     afs_int32 rights, anyrights;        /* rights for this and any user */
5360     struct client *t_client;    /* tmp ptr to client data */
5361     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5362     struct rx_connection *tcon = rx_ConnectionOf(acall);
5363
5364     /* Get ptr to client data for user Id for logging */
5365     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5366     logHostAddr.s_addr = rxr_HostOf(tcon);
5367     ViceLog(1,
5368             ("SAFS_ExtendLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5369              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5370              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5371     FS_LOCK;
5372     AFSCallStats.ExtendLock++, AFSCallStats.TotalCalls++;
5373     FS_UNLOCK;
5374     /*
5375      * Get the vnode and volume for the desired file along with the caller's
5376      * rights to it
5377      */
5378     if ((errorCode =
5379          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5380                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5381                           &rights, &anyrights))) {
5382         goto Bad_ExtendLock;
5383     }
5384
5385     /* set volume synchronization information */
5386     SetVolumeSync(Sync, volptr);
5387
5388     /* Handle the actual lock extension */
5389     errorCode = HandleLocking(targetptr, client, rights, LockExtend);
5390
5391   Bad_ExtendLock:
5392     /* Put back file's vnode and volume */
5393     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5394                            volptr, &client);
5395
5396     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5397         errorCode = 0;          /* under our generous policy re RO vols */
5398
5399     ViceLog(2, ("SAFS_ExtendLock returns %d\n", errorCode));
5400     return (errorCode);
5401
5402 }                               /*SAFSS_ExtendLock */
5403
5404
5405 afs_int32
5406 SRXAFS_OldExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5407                      struct AFSVolSync * Sync)
5408 {
5409     return SRXAFS_ExtendLock(acall, Fid, Sync);
5410 }                               /*SRXAFS_OldExtendLock */
5411
5412
5413 afs_int32
5414 SRXAFS_ExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5415                   struct AFSVolSync * Sync)
5416 {
5417     afs_int32 code;
5418     struct rx_connection *tcon;
5419     struct host *thost;
5420     struct client *t_client = NULL;     /* tmp ptr to client data */
5421 #if FS_STATS_DETAILED
5422     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5423     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5424     struct timeval elapsedTime; /* Transfer time */
5425
5426     /*
5427      * Set our stats pointer, remember when the RPC operation started, and
5428      * tally the operation.
5429      */
5430     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_EXTENDLOCK]);
5431     FS_LOCK;
5432     (opP->numOps)++;
5433     FS_UNLOCK;
5434     FT_GetTimeOfDay(&opStartTime, 0);
5435 #endif /* FS_STATS_DETAILED */
5436
5437     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5438         goto Bad_ExtendLock;
5439
5440     code = SAFSS_ExtendLock(acall, Fid, Sync);
5441
5442   Bad_ExtendLock:
5443     code = CallPostamble(tcon, code, thost);
5444
5445     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5446
5447 #if FS_STATS_DETAILED
5448     FT_GetTimeOfDay(&opStopTime, 0);
5449     if (code == 0) {
5450         FS_LOCK;
5451         (opP->numSuccesses)++;
5452         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5453         fs_stats_AddTo((opP->sumTime), elapsedTime);
5454         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5455         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5456             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5457         }
5458         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5459             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5460         }
5461         FS_UNLOCK;
5462     }
5463 #endif /* FS_STATS_DETAILED */
5464
5465     osi_auditU(acall, ExtendLockEvent, code,
5466                AUD_ID, t_client ? t_client->ViceId : 0,
5467                AUD_FID, Fid, AUD_END);
5468     return code;
5469
5470 }                               /*SRXAFS_ExtendLock */
5471
5472
5473 /*
5474  * This routine is called exclusively by SRXAFS_ReleaseLock(), and should be
5475  * merged into it when possible.
5476  */
5477 static afs_int32
5478 SAFSS_ReleaseLock(struct rx_call *acall, struct AFSFid *Fid,
5479                   struct AFSVolSync *Sync)
5480 {
5481     Vnode *targetptr = 0;       /* vnode of input file */
5482     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5483     Error errorCode = 0;                /* error code */
5484     Volume *volptr = 0;         /* pointer to the volume header */
5485     struct client *client = 0;  /* pointer to client structure */
5486     afs_int32 rights, anyrights;        /* rights for this and any user */
5487     struct client *t_client;    /* tmp ptr to client data */
5488     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5489     struct rx_connection *tcon = rx_ConnectionOf(acall);
5490
5491     /* Get ptr to client data for user Id for logging */
5492     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5493     logHostAddr.s_addr = rxr_HostOf(tcon);
5494     ViceLog(1,
5495             ("SAFS_ReleaseLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5496              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5497              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5498     FS_LOCK;
5499     AFSCallStats.ReleaseLock++, AFSCallStats.TotalCalls++;
5500     FS_UNLOCK;
5501     /*
5502      * Get the vnode and volume for the desired file along with the caller's
5503      * rights to it
5504      */
5505     if ((errorCode =
5506          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5507                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5508                           &rights, &anyrights))) {
5509         goto Bad_ReleaseLock;
5510     }
5511
5512     /* set volume synchronization information */
5513     SetVolumeSync(Sync, volptr);
5514
5515     /* Handle the actual lock release */
5516     if ((errorCode = HandleLocking(targetptr, client, rights, LockRelease)))
5517         goto Bad_ReleaseLock;
5518
5519     /* if no more locks left, a callback would be triggered here */
5520     if (targetptr->disk.lock.lockCount <= 0) {
5521         /* convert the write lock to a read lock before breaking callbacks */
5522         VVnodeWriteToRead(&errorCode, targetptr);
5523         osi_Assert(!errorCode || errorCode == VSALVAGE);
5524         BreakCallBack(client->host, Fid, 0);
5525     }
5526
5527   Bad_ReleaseLock:
5528     /* Put back file's vnode and volume */
5529     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5530                            volptr, &client);
5531
5532     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5533         errorCode = 0;          /* under our generous policy re RO vols */
5534
5535     ViceLog(2, ("SAFS_ReleaseLock returns %d\n", errorCode));
5536     return (errorCode);
5537
5538 }                               /*SAFSS_ReleaseLock */
5539
5540
5541 afs_int32
5542 SRXAFS_OldReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5543                       struct AFSVolSync * Sync)
5544 {
5545     return SRXAFS_ReleaseLock(acall, Fid, Sync);
5546 }                               /*SRXAFS_OldReleaseLock */
5547
5548
5549 afs_int32
5550 SRXAFS_ReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5551                    struct AFSVolSync * Sync)
5552 {
5553     afs_int32 code;
5554     struct rx_connection *tcon;
5555     struct host *thost;
5556     struct client *t_client = NULL;     /* tmp ptr to client data */
5557 #if FS_STATS_DETAILED
5558     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5559     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5560     struct timeval elapsedTime; /* Transfer time */
5561
5562     /*
5563      * Set our stats pointer, remember when the RPC operation started, and
5564      * tally the operation.
5565      */
5566     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RELEASELOCK]);
5567     FS_LOCK;
5568     (opP->numOps)++;
5569     FS_UNLOCK;
5570     FT_GetTimeOfDay(&opStartTime, 0);
5571 #endif /* FS_STATS_DETAILED */
5572
5573     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5574         goto Bad_ReleaseLock;
5575
5576     code = SAFSS_ReleaseLock(acall, Fid, Sync);
5577
5578   Bad_ReleaseLock:
5579     code = CallPostamble(tcon, code, thost);
5580
5581     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5582
5583 #if FS_STATS_DETAILED
5584     FT_GetTimeOfDay(&opStopTime, 0);
5585     if (code == 0) {
5586         FS_LOCK;
5587         (opP->numSuccesses)++;
5588         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5589         fs_stats_AddTo((opP->sumTime), elapsedTime);
5590         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5591         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5592             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5593         }
5594         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5595             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5596         }
5597         FS_UNLOCK;
5598     }
5599 #endif /* FS_STATS_DETAILED */
5600
5601     osi_auditU(acall, ReleaseLockEvent, code,
5602                AUD_ID, t_client ? t_client->ViceId : 0,
5603                AUD_FID, Fid, AUD_END);
5604     return code;
5605
5606 }                               /*SRXAFS_ReleaseLock */
5607
5608
5609 void
5610 SetSystemStats(struct AFSStatistics *stats)
5611 {
5612     /* Fix this sometime soon.. */
5613     /* Because hey, it's not like we have a network monitoring protocol... */
5614     struct timeval time;
5615
5616     /* this works on all system types */
5617     FT_GetTimeOfDay(&time, 0);
5618     stats->CurrentTime = time.tv_sec;
5619 }                               /*SetSystemStats */
5620
5621 void
5622 SetAFSStats(struct AFSStatistics *stats)
5623 {
5624     extern afs_int32 StartTime, CurrentConnections;
5625     int seconds;
5626
5627     FS_LOCK;
5628     stats->CurrentMsgNumber = 0;
5629     stats->OldestMsgNumber = 0;
5630     stats->StartTime = StartTime;
5631     stats->CurrentConnections = CurrentConnections;
5632     stats->TotalAFSCalls = AFSCallStats.TotalCalls;
5633     stats->TotalFetchs =
5634         AFSCallStats.FetchData + AFSCallStats.FetchACL +
5635         AFSCallStats.FetchStatus;
5636     stats->FetchDatas = AFSCallStats.FetchData;
5637     stats->FetchedBytes = AFSCallStats.TotalFetchedBytes;
5638     seconds = AFSCallStats.AccumFetchTime / 1000;
5639     if (seconds <= 0)
5640         seconds = 1;
5641     stats->FetchDataRate = AFSCallStats.TotalFetchedBytes / seconds;
5642     stats->TotalStores =
5643         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5644         AFSCallStats.StoreStatus;
5645     stats->StoreDatas = AFSCallStats.StoreData;
5646     stats->StoredBytes = AFSCallStats.TotalStoredBytes;
5647     seconds = AFSCallStats.AccumStoreTime / 1000;
5648     if (seconds <= 0)
5649         seconds = 1;
5650     stats->StoreDataRate = AFSCallStats.TotalStoredBytes / seconds;
5651 #ifdef AFS_NT40_ENV
5652     stats->ProcessSize = -1;    /* TODO: */
5653 #else
5654     stats->ProcessSize = (afs_int32) ((long)sbrk(0) >> 10);
5655 #endif
5656     FS_UNLOCK;
5657     h_GetWorkStats((int *)&(stats->WorkStations),
5658                    (int *)&(stats->ActiveWorkStations), (int *)0,
5659                    (afs_int32) (FT_ApproxTime()) - (15 * 60));
5660
5661 }                               /*SetAFSStats */
5662
5663 /* Get disk related information from all AFS partitions. */
5664
5665 void
5666 SetVolumeStats(struct AFSStatistics *stats)
5667 {
5668     struct DiskPartition64 *part;
5669     int i = 0;
5670
5671     for (part = DiskPartitionList; part && i < AFS_MSTATDISKS;
5672          part = part->next) {
5673         stats->Disks[i].TotalBlocks = RoundInt64ToInt32(part->totalUsable);
5674         stats->Disks[i].BlocksAvailable = RoundInt64ToInt32(part->free);
5675         memset(stats->Disks[i].Name, 0, AFS_DISKNAMESIZE);
5676         strncpy(stats->Disks[i].Name, part->name, AFS_DISKNAMESIZE);
5677         i++;
5678     }
5679     while (i < AFS_MSTATDISKS) {
5680         stats->Disks[i].TotalBlocks = -1;
5681         i++;
5682     }
5683 }                               /*SetVolumeStats */
5684
5685 afs_int32
5686 SRXAFS_GetStatistics(struct rx_call *acall, struct ViceStatistics *Statistics)
5687 {
5688     afs_int32 code;
5689     struct rx_connection *tcon = rx_ConnectionOf(acall);
5690     struct host *thost;
5691     struct client *t_client = NULL;     /* tmp ptr to client data */
5692 #if FS_STATS_DETAILED
5693     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5694     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5695     struct timeval elapsedTime; /* Transfer time */
5696
5697     /*
5698      * Set our stats pointer, remember when the RPC operation started, and
5699      * tally the operation.
5700      */
5701     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5702     FS_LOCK;
5703     (opP->numOps)++;
5704     FS_UNLOCK;
5705     FT_GetTimeOfDay(&opStartTime, 0);
5706 #endif /* FS_STATS_DETAILED */
5707
5708     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5709         goto Bad_GetStatistics;
5710
5711     ViceLog(1, ("SAFS_GetStatistics Received\n"));
5712     FS_LOCK;
5713     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5714     FS_UNLOCK;
5715     memset(Statistics, 0, sizeof(*Statistics));
5716     SetAFSStats((struct AFSStatistics *)Statistics);
5717     SetVolumeStats((struct AFSStatistics *)Statistics);
5718     SetSystemStats((struct AFSStatistics *)Statistics);
5719
5720   Bad_GetStatistics:
5721     code = CallPostamble(tcon, code, thost);
5722
5723     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5724
5725 #if FS_STATS_DETAILED
5726     FT_GetTimeOfDay(&opStopTime, 0);
5727     if (code == 0) {
5728         FS_LOCK;
5729         (opP->numSuccesses)++;
5730         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5731         fs_stats_AddTo((opP->sumTime), elapsedTime);
5732         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5733         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5734             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5735         }
5736         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5737             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5738         }
5739         FS_UNLOCK;
5740     }
5741 #endif /* FS_STATS_DETAILED */
5742
5743     osi_auditU(acall, GetStatisticsEvent, code,
5744                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5745     return code;
5746 }                               /*SRXAFS_GetStatistics */
5747
5748
5749 afs_int32
5750 SRXAFS_GetStatistics64(struct rx_call *acall, afs_int32 statsVersion, ViceStatistics64 *Statistics)
5751 {
5752     extern afs_int32 StartTime, CurrentConnections;
5753     int seconds;
5754     afs_int32 code;
5755     struct rx_connection *tcon = rx_ConnectionOf(acall);
5756     struct host *thost;
5757     struct client *t_client = NULL;     /* tmp ptr to client data */
5758     struct timeval time;
5759 #if FS_STATS_DETAILED
5760     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5761     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5762     struct timeval elapsedTime; /* Transfer time */
5763
5764     /*
5765      * Set our stats pointer, remember when the RPC operation started, and
5766      * tally the operation.
5767      */
5768     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5769     FS_LOCK;
5770     (opP->numOps)++;
5771     FS_UNLOCK;
5772     FT_GetTimeOfDay(&opStartTime, 0);
5773 #endif /* FS_STATS_DETAILED */
5774
5775     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5776         goto Bad_GetStatistics64;
5777
5778     ViceLog(1, ("SAFS_GetStatistics64 Received\n"));
5779     Statistics->ViceStatistics64_val =
5780         malloc(statsVersion*sizeof(afs_int64));
5781     Statistics->ViceStatistics64_len = statsVersion;
5782     FS_LOCK;
5783     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5784     Statistics->ViceStatistics64_val[STATS64_STARTTIME] = StartTime;
5785     Statistics->ViceStatistics64_val[STATS64_CURRENTCONNECTIONS] =
5786         CurrentConnections;
5787     Statistics->ViceStatistics64_val[STATS64_TOTALVICECALLS] =
5788         AFSCallStats.TotalCalls;
5789     Statistics->ViceStatistics64_val[STATS64_TOTALFETCHES] =
5790        AFSCallStats.FetchData + AFSCallStats.FetchACL +
5791        AFSCallStats.FetchStatus;
5792     Statistics->ViceStatistics64_val[STATS64_FETCHDATAS] =
5793         AFSCallStats.FetchData;
5794     Statistics->ViceStatistics64_val[STATS64_FETCHEDBYTES] =
5795         AFSCallStats.TotalFetchedBytes;
5796     seconds = AFSCallStats.AccumFetchTime / 1000;
5797     if (seconds <= 0)
5798         seconds = 1;
5799     Statistics->ViceStatistics64_val[STATS64_FETCHDATARATE] =
5800         AFSCallStats.TotalFetchedBytes / seconds;
5801     Statistics->ViceStatistics64_val[STATS64_TOTALSTORES] =
5802         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5803         AFSCallStats.StoreStatus;
5804     Statistics->ViceStatistics64_val[STATS64_STOREDATAS] =
5805         AFSCallStats.StoreData;
5806     Statistics->ViceStatistics64_val[STATS64_STOREDBYTES] =
5807         AFSCallStats.TotalStoredBytes;
5808     seconds = AFSCallStats.AccumStoreTime / 1000;
5809     if (seconds <= 0)
5810         seconds = 1;
5811     Statistics->ViceStatistics64_val[STATS64_STOREDATARATE] =
5812         AFSCallStats.TotalStoredBytes / seconds;
5813 #ifdef AFS_NT40_ENV
5814     Statistics->ViceStatistics64_val[STATS64_PROCESSSIZE] = -1;
5815 #else
5816     Statistics->ViceStatistics64_val[STATS64_PROCESSSIZE] =
5817         (afs_int32) ((long)sbrk(0) >> 10);
5818 #endif
5819     FS_UNLOCK;
5820     h_GetWorkStats64(&(Statistics->ViceStatistics64_val[STATS64_WORKSTATIONS]),
5821                      &(Statistics->ViceStatistics64_val[STATS64_ACTIVEWORKSTATIONS]),
5822                      0,
5823                      (afs_int32) (FT_ApproxTime()) - (15 * 60));
5824
5825
5826
5827     /* this works on all system types */
5828     FT_GetTimeOfDay(&time, 0);
5829     Statistics->ViceStatistics64_val[STATS64_CURRENTTIME] = time.tv_sec;
5830
5831   Bad_GetStatistics64:
5832     code = CallPostamble(tcon, code, thost);
5833
5834     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5835
5836 #if FS_STATS_DETAILED
5837     FT_GetTimeOfDay(&opStopTime, 0);
5838     if (code == 0) {
5839         FS_LOCK;
5840         (opP->numSuccesses)++;
5841         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5842         fs_stats_AddTo((opP->sumTime), elapsedTime);
5843         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5844         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5845             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5846         }
5847         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5848             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5849         }
5850         FS_UNLOCK;
5851     }
5852 #endif /* FS_STATS_DETAILED */
5853
5854     osi_auditU(acall, GetStatisticsEvent, code,
5855                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5856     return code;
5857 }                               /*SRXAFS_GetStatistics */
5858
5859
5860 /*------------------------------------------------------------------------
5861  * EXPORTED SRXAFS_XStatsVersion
5862  *
5863  * Description:
5864  *      Routine called by the server-side RPC interface to implement
5865  *      pulling out the xstat version number for the File Server.
5866  *
5867  * Arguments:
5868  *      a_versionP : Ptr to the version number variable to set.
5869  *
5870  * Returns:
5871  *      0 (always)
5872  *
5873  * Environment:
5874  *      Nothing interesting.
5875  *
5876  * Side Effects:
5877  *      As advertised.
5878  *------------------------------------------------------------------------*/
5879
5880 afs_int32
5881 SRXAFS_XStatsVersion(struct rx_call * a_call, afs_int32 * a_versionP)
5882 {                               /*SRXAFS_XStatsVersion */
5883
5884     struct client *t_client = NULL;     /* tmp ptr to client data */
5885     struct rx_connection *tcon = rx_ConnectionOf(a_call);
5886 #if FS_STATS_DETAILED
5887     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5888     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5889     struct timeval elapsedTime; /* Transfer time */
5890
5891     /*
5892      * Set our stats pointer, remember when the RPC operation started, and
5893      * tally the operation.
5894      */
5895     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_XSTATSVERSION]);
5896     FS_LOCK;
5897     (opP->numOps)++;
5898     FS_UNLOCK;
5899     FT_GetTimeOfDay(&opStartTime, 0);
5900 #endif /* FS_STATS_DETAILED */
5901
5902     *a_versionP = AFS_XSTAT_VERSION;
5903
5904     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5905
5906 #if FS_STATS_DETAILED
5907     FT_GetTimeOfDay(&opStopTime, 0);
5908     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5909     fs_stats_AddTo((opP->sumTime), elapsedTime);
5910     fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5911     if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5912         fs_stats_TimeAssign((opP->minTime), elapsedTime);
5913     }
5914     if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5915         fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5916     }
5917     FS_LOCK;
5918     (opP->numSuccesses)++;
5919     FS_UNLOCK;
5920 #endif /* FS_STATS_DETAILED */
5921
5922     osi_auditU(a_call, XStatsVersionEvent, 0,
5923                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5924     return (0);
5925 }                               /*SRXAFS_XStatsVersion */
5926
5927
5928 /*------------------------------------------------------------------------
5929  * PRIVATE FillPerfValues
5930  *
5931  * Description:
5932  *      Routine called to fill a regular performance data structure.
5933  *
5934  * Arguments:
5935  *      a_perfP : Ptr to perf structure to fill
5936  *
5937  * Returns:
5938  *      Nothing.
5939  *
5940  * Environment:
5941  *      Various collections need this info, so the guts were put in
5942  *      this separate routine.
5943  *
5944  * Side Effects:
5945  *      As advertised.
5946  *------------------------------------------------------------------------*/
5947
5948 static void
5949 FillPerfValues(struct afs_PerfStats *a_perfP)
5950 {                               /*FillPerfValues */
5951     afs_uint32 hi, lo;
5952     int dir_Buffers;            /*# buffers in use by dir package */
5953     int dir_Calls;              /*# read calls in dir package */
5954     int dir_IOs;                /*# I/O ops in dir package */
5955     struct rx_statistics *stats;
5956
5957     /*
5958      * Vnode cache section.
5959      */
5960     a_perfP->vcache_L_Entries = VnodeClassInfo[vLarge].cacheSize;
5961     a_perfP->vcache_L_Allocs = VnodeClassInfo[vLarge].allocs;
5962     a_perfP->vcache_L_Gets = VnodeClassInfo[vLarge].gets;
5963     a_perfP->vcache_L_Reads = VnodeClassInfo[vLarge].reads;
5964     a_perfP->vcache_L_Writes = VnodeClassInfo[vLarge].writes;
5965     a_perfP->vcache_S_Entries = VnodeClassInfo[vSmall].cacheSize;
5966     a_perfP->vcache_S_Allocs = VnodeClassInfo[vSmall].allocs;
5967     a_perfP->vcache_S_Gets = VnodeClassInfo[vSmall].gets;
5968     a_perfP->vcache_S_Reads = VnodeClassInfo[vSmall].reads;
5969     a_perfP->vcache_S_Writes = VnodeClassInfo[vSmall].writes;
5970     a_perfP->vcache_H_Entries = VStats.hdr_cache_size;
5971     SplitInt64(VStats.hdr_gets, hi, lo);
5972     a_perfP->vcache_H_Gets = lo;
5973     SplitInt64(VStats.hdr_loads, hi, lo);
5974     a_perfP->vcache_H_Replacements = lo;
5975
5976     /*
5977      * Directory section.
5978      */
5979     DStat(&dir_Buffers, &dir_Calls, &dir_IOs);
5980     a_perfP->dir_Buffers = (afs_int32) dir_Buffers;
5981     a_perfP->dir_Calls = (afs_int32) dir_Calls;
5982     a_perfP->dir_IOs = (afs_int32) dir_IOs;
5983
5984     /*
5985      * Rx section.
5986      */
5987     stats = rx_GetStatistics();
5988
5989     a_perfP->rx_packetRequests = (afs_int32) stats->packetRequests;
5990     a_perfP->rx_noPackets_RcvClass =
5991         (afs_int32) stats->receivePktAllocFailures;
5992     a_perfP->rx_noPackets_SendClass =
5993         (afs_int32) stats->sendPktAllocFailures;
5994     a_perfP->rx_noPackets_SpecialClass =
5995         (afs_int32) stats->specialPktAllocFailures;
5996     a_perfP->rx_socketGreedy = (afs_int32) stats->socketGreedy;
5997     a_perfP->rx_bogusPacketOnRead = (afs_int32) stats->bogusPacketOnRead;
5998     a_perfP->rx_bogusHost = (afs_int32) stats->bogusHost;
5999     a_perfP->rx_noPacketOnRead = (afs_int32) stats->noPacketOnRead;
6000     a_perfP->rx_noPacketBuffersOnRead =
6001         (afs_int32) stats->noPacketBuffersOnRead;
6002     a_perfP->rx_selects = (afs_int32) stats->selects;
6003     a_perfP->rx_sendSelects = (afs_int32) stats->sendSelects;
6004     a_perfP->rx_packetsRead_RcvClass =
6005         (afs_int32) stats->packetsRead[RX_PACKET_CLASS_RECEIVE];
6006     a_perfP->rx_packetsRead_SendClass =
6007         (afs_int32) stats->packetsRead[RX_PACKET_CLASS_SEND];
6008     a_perfP->rx_packetsRead_SpecialClass =
6009         (afs_int32) stats->packetsRead[RX_PACKET_CLASS_SPECIAL];
6010     a_perfP->rx_dataPacketsRead = (afs_int32) stats->dataPacketsRead;
6011     a_perfP->rx_ackPacketsRead = (afs_int32) stats->ackPacketsRead;
6012     a_perfP->rx_dupPacketsRead = (afs_int32) stats->dupPacketsRead;
6013     a_perfP->rx_spuriousPacketsRead =
6014         (afs_int32) stats->spuriousPacketsRead;
6015     a_perfP->rx_packetsSent_RcvClass =
6016         (afs_int32) stats->packetsSent[RX_PACKET_CLASS_RECEIVE];
6017     a_perfP->rx_packetsSent_SendClass =
6018         (afs_int32) stats->packetsSent[RX_PACKET_CLASS_SEND];
6019     a_perfP->rx_packetsSent_SpecialClass =
6020         (afs_int32) stats->packetsSent[RX_PACKET_CLASS_SPECIAL];
6021     a_perfP->rx_ackPacketsSent = (afs_int32) stats->ackPacketsSent;
6022     a_perfP->rx_pingPacketsSent = (afs_int32) stats->pingPacketsSent;
6023     a_perfP->rx_abortPacketsSent = (afs_int32) stats->abortPacketsSent;
6024     a_perfP->rx_busyPacketsSent = (afs_int32) stats->busyPacketsSent;
6025     a_perfP->rx_dataPacketsSent = (afs_int32) stats->dataPacketsSent;
6026     a_perfP->rx_dataPacketsReSent = (afs_int32) stats->dataPacketsReSent;
6027     a_perfP->rx_dataPacketsPushed = (afs_int32) stats->dataPacketsPushed;
6028     a_perfP->rx_ignoreAckedPacket = (afs_int32) stats->ignoreAckedPacket;
6029     a_perfP->rx_totalRtt_Sec = (afs_int32) stats->totalRtt.sec;
6030     a_perfP->rx_totalRtt_Usec = (afs_int32) stats->totalRtt.usec;
6031     a_perfP->rx_minRtt_Sec = (afs_int32) stats->minRtt.sec;
6032     a_perfP->rx_minRtt_Usec = (afs_int32) stats->minRtt.usec;
6033     a_perfP->rx_maxRtt_Sec = (afs_int32) stats->maxRtt.sec;
6034     a_perfP->rx_maxRtt_Usec = (afs_int32) stats->maxRtt.usec;
6035     a_perfP->rx_nRttSamples = (afs_int32) stats->nRttSamples;
6036     a_perfP->rx_nServerConns = (afs_int32) stats->nServerConns;
6037     a_perfP->rx_nClientConns = (afs_int32) stats->nClientConns;
6038     a_perfP->rx_nPeerStructs = (afs_int32) stats->nPeerStructs;
6039     a_perfP->rx_nCallStructs = (afs_int32) stats->nCallStructs;
6040     a_perfP->rx_nFreeCallStructs = (afs_int32) stats->nFreeCallStructs;
6041
6042     a_perfP->host_NumHostEntries = HTs;
6043     a_perfP->host_HostBlocks = HTBlocks;
6044     h_GetHostNetStats(&(a_perfP->host_NonDeletedHosts),
6045                       &(a_perfP->host_HostsInSameNetOrSubnet),
6046                       &(a_perfP->host_HostsInDiffSubnet),
6047                       &(a_perfP->host_HostsInDiffNetwork));
6048     a_perfP->host_NumClients = CEs;
6049     a_perfP->host_ClientBlocks = CEBlocks;
6050
6051     a_perfP->sysname_ID = afs_perfstats.sysname_ID;
6052     a_perfP->rx_nBusies = (afs_int32) stats->nBusies;
6053     a_perfP->fs_nBusies = afs_perfstats.fs_nBusies;
6054     rx_FreeStatistics(&stats);
6055 }                               /*FillPerfValues */
6056
6057
6058 /*------------------------------------------------------------------------
6059  * EXPORTED SRXAFS_GetXStats
6060  *
6061  * Description:
6062  *      Routine called by the server-side callback RPC interface to
6063  *      implement getting the given data collection from the extended
6064  *      File Server statistics.
6065  *
6066  * Arguments:
6067  *      a_call              : Ptr to Rx call on which this request came in.
6068  *      a_clientVersionNum  : Client version number.
6069  *      a_opCode            : Desired operation.
6070  *      a_serverVersionNumP : Ptr to version number to set.
6071  *      a_timeP             : Ptr to time value (seconds) to set.
6072  *      a_dataP             : Ptr to variable array structure to return
6073  *                            stuff in.
6074  *
6075  * Returns:
6076  *      0 (always).
6077  *
6078  * Environment:
6079  *      Nothing interesting.
6080  *
6081  * Side Effects:
6082  *      As advertised.
6083  *------------------------------------------------------------------------*/
6084
6085 afs_int32
6086 SRXAFS_GetXStats(struct rx_call *a_call, afs_int32 a_clientVersionNum,
6087                  afs_int32 a_collectionNumber, afs_int32 * a_srvVersionNumP,
6088                  afs_int32 * a_timeP, AFS_CollData * a_dataP)
6089 {                               /*SRXAFS_GetXStats */
6090
6091     int code;           /*Return value */
6092     afs_int32 *dataBuffP;       /*Ptr to data to be returned */
6093     afs_int32 dataBytes;        /*Bytes in data buffer */
6094 #if FS_STATS_DETAILED
6095     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6096     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6097     struct timeval elapsedTime; /* Transfer time */
6098
6099     /*
6100      * Set our stats pointer, remember when the RPC operation started, and
6101      * tally the operation.
6102      */
6103     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETXSTATS]);
6104     FS_LOCK;
6105     (opP->numOps)++;
6106     FS_UNLOCK;
6107     FT_GetTimeOfDay(&opStartTime, 0);
6108 #endif /* FS_STATS_DETAILED */
6109
6110     /*
6111      * Record the time of day and the server version number.
6112      */
6113     *a_srvVersionNumP = AFS_XSTAT_VERSION;
6114     *a_timeP = FT_ApproxTime();
6115
6116     /*
6117      * Stuff the appropriate data in there (assume victory)
6118      */
6119     code = 0;
6120
6121     ViceLog(1,
6122             ("Received GetXStats call for collection %d\n",
6123              a_collectionNumber));
6124
6125 #if 0
6126     /*
6127      * We're not keeping stats, so just return successfully with
6128      * no data.
6129      */
6130     a_dataP->AFS_CollData_len = 0;
6131     a_dataP->AFS_CollData_val = NULL;
6132 #endif /* 0 */
6133
6134     switch (a_collectionNumber) {
6135     case AFS_XSTATSCOLL_CALL_INFO:
6136         /*
6137          * Pass back all the call-count-related data.
6138          *
6139          * >>> We are forced to allocate a separate area in which to
6140          * >>> put this stuff in by the RPC stub generator, since it
6141          * >>> will be freed at the tail end of the server stub code.
6142          */
6143 #if 0
6144         /*
6145          * I don't think call-level stats are being collected yet
6146          * for the File Server.
6147          */
6148         dataBytes = sizeof(struct afs_Stats);
6149         dataBuffP = (afs_int32 *) malloc(dataBytes);
6150         memcpy(dataBuffP, &afs_cmstats, dataBytes);
6151         a_dataP->AFS_CollData_len = dataBytes >> 2;
6152         a_dataP->AFS_CollData_val = dataBuffP;
6153 #else
6154         a_dataP->AFS_CollData_len = 0;
6155         a_dataP->AFS_CollData_val = NULL;
6156 #endif /* 0 */
6157         break;
6158
6159     case AFS_XSTATSCOLL_PERF_INFO:
6160         /*
6161          * Pass back all the regular performance-related data.
6162          *
6163          * >>> We are forced to allocate a separate area in which to
6164          * >>> put this stuff in by the RPC stub generator, since it
6165          * >>> will be freed at the tail end of the server stub code.
6166          */
6167
6168         afs_perfstats.numPerfCalls++;
6169         FillPerfValues(&afs_perfstats);
6170
6171         /*
6172          * Don't overwrite the spares at the end.
6173          */
6174
6175         dataBytes = sizeof(struct afs_PerfStats);
6176         dataBuffP = (afs_int32 *) malloc(dataBytes);
6177         memcpy(dataBuffP, &afs_perfstats, dataBytes);
6178         a_dataP->AFS_CollData_len = dataBytes >> 2;
6179         a_dataP->AFS_CollData_val = dataBuffP;
6180         break;
6181
6182     case AFS_XSTATSCOLL_FULL_PERF_INFO:
6183         /*
6184          * Pass back the full collection of performance-related data.
6185          * We have to stuff the basic, overall numbers in, but the
6186          * detailed numbers are kept in the structure already.
6187          *
6188          * >>> We are forced to allocate a separate area in which to
6189          * >>> put this stuff in by the RPC stub generator, since it
6190          * >>> will be freed at the tail end of the server stub code.
6191          */
6192
6193         afs_perfstats.numPerfCalls++;
6194 #if FS_STATS_DETAILED
6195         afs_FullPerfStats.overall.numPerfCalls = afs_perfstats.numPerfCalls;
6196         FillPerfValues(&afs_FullPerfStats.overall);
6197
6198         /*
6199          * Don't overwrite the spares at the end.
6200          */
6201
6202         dataBytes = sizeof(struct fs_stats_FullPerfStats);
6203         dataBuffP = (afs_int32 *) malloc(dataBytes);
6204         memcpy(dataBuffP, &afs_FullPerfStats, dataBytes);
6205         a_dataP->AFS_CollData_len = dataBytes >> 2;
6206         a_dataP->AFS_CollData_val = dataBuffP;
6207 #endif
6208         break;
6209
6210     case AFS_XSTATSCOLL_CBSTATS:
6211         afs_perfstats.numPerfCalls++;
6212
6213         dataBytes = sizeof(struct cbcounters);
6214         dataBuffP = (afs_int32 *) malloc(dataBytes);
6215         {
6216             extern struct cbcounters cbstuff;
6217             dataBuffP[0]=cbstuff.DeleteFiles;
6218             dataBuffP[1]=cbstuff.DeleteCallBacks;
6219             dataBuffP[2]=cbstuff.BreakCallBacks;
6220             dataBuffP[3]=cbstuff.AddCallBacks;
6221             dataBuffP[4]=cbstuff.GotSomeSpaces;
6222             dataBuffP[5]=cbstuff.DeleteAllCallBacks;
6223             dataBuffP[6]=cbstuff.nFEs;
6224             dataBuffP[7]=cbstuff.nCBs;
6225             dataBuffP[8]=cbstuff.nblks;
6226             dataBuffP[9]=cbstuff.CBsTimedOut;
6227             dataBuffP[10]=cbstuff.nbreakers;
6228             dataBuffP[11]=cbstuff.GSS1;
6229             dataBuffP[12]=cbstuff.GSS2;
6230             dataBuffP[13]=cbstuff.GSS3;
6231             dataBuffP[14]=cbstuff.GSS4;
6232             dataBuffP[15]=cbstuff.GSS5;
6233         }
6234
6235         a_dataP->AFS_CollData_len = dataBytes >> 2;
6236         a_dataP->AFS_CollData_val = dataBuffP;
6237         break;
6238
6239
6240     default:
6241         /*
6242          * Illegal collection number.
6243          */
6244         a_dataP->AFS_CollData_len = 0;
6245         a_dataP->AFS_CollData_val = NULL;
6246         code = 1;
6247     }                           /*Switch on collection number */
6248
6249 #if FS_STATS_DETAILED
6250     FT_GetTimeOfDay(&opStopTime, 0);
6251     if (code == 0) {
6252         FS_LOCK;
6253         (opP->numSuccesses)++;
6254         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6255         fs_stats_AddTo((opP->sumTime), elapsedTime);
6256         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6257         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6258             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6259         }
6260         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6261             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6262         }
6263         FS_UNLOCK;
6264     }
6265 #endif /* FS_STATS_DETAILED */
6266
6267     return (code);
6268
6269 }                               /*SRXAFS_GetXStats */
6270
6271
6272 static afs_int32
6273 common_GiveUpCallBacks(struct rx_call *acall, struct AFSCBFids *FidArray,
6274                        struct AFSCBs *CallBackArray)
6275 {
6276     afs_int32 errorCode = 0;
6277     int i;
6278     struct client *client = 0;
6279     struct rx_connection *tcon;
6280     struct host *thost;
6281 #if FS_STATS_DETAILED
6282     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6283     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6284     struct timeval elapsedTime; /* Transfer time */
6285
6286     /*
6287      * Set our stats pointer, remember when the RPC operation started, and
6288      * tally the operation.
6289      */
6290     opP =
6291         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GIVEUPCALLBACKS]);
6292     FS_LOCK;
6293     (opP->numOps)++;
6294     FS_UNLOCK;
6295     FT_GetTimeOfDay(&opStartTime, 0);
6296 #endif /* FS_STATS_DETAILED */
6297
6298     if (FidArray)
6299         ViceLog(1,
6300                 ("SAFS_GiveUpCallBacks (Noffids=%d)\n",
6301                  FidArray->AFSCBFids_len));
6302
6303     FS_LOCK;
6304     AFSCallStats.GiveUpCallBacks++, AFSCallStats.TotalCalls++;
6305     FS_UNLOCK;
6306     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6307         goto Bad_GiveUpCallBacks;
6308
6309     if (!FidArray && !CallBackArray) {
6310         ViceLog(1,
6311                 ("SAFS_GiveUpAllCallBacks: host=%x\n",
6312                  (tcon->peer ? tcon->peer->host : 0)));
6313         errorCode = GetClient(tcon, &client);
6314         if (!errorCode) {
6315             H_LOCK;
6316             DeleteAllCallBacks_r(client->host, 1);
6317             H_UNLOCK;
6318             PutClient(&client);
6319         }
6320     } else {
6321         if (FidArray->AFSCBFids_len < CallBackArray->AFSCBs_len) {
6322             ViceLog(0,
6323                     ("GiveUpCallBacks: #Fids %d < #CallBacks %d, host=%x\n",
6324                      FidArray->AFSCBFids_len, CallBackArray->AFSCBs_len,
6325                      (tcon->peer ? tcon->peer->host : 0)));
6326             errorCode = EINVAL;
6327             goto Bad_GiveUpCallBacks;
6328         }
6329
6330         errorCode = GetClient(tcon, &client);
6331         if (!errorCode) {
6332             for (i = 0; i < FidArray->AFSCBFids_len; i++) {
6333                 struct AFSFid *fid = &(FidArray->AFSCBFids_val[i]);
6334                 DeleteCallBack(client->host, fid);
6335             }
6336             PutClient(&client);
6337         }
6338     }
6339
6340   Bad_GiveUpCallBacks:
6341     errorCode = CallPostamble(tcon, errorCode, thost);
6342
6343 #if FS_STATS_DETAILED
6344     FT_GetTimeOfDay(&opStopTime, 0);
6345     if (errorCode == 0) {
6346         FS_LOCK;
6347         (opP->numSuccesses)++;
6348         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6349         fs_stats_AddTo((opP->sumTime), elapsedTime);
6350         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6351         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6352             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6353         }
6354         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6355             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6356         }
6357         FS_UNLOCK;
6358     }
6359 #endif /* FS_STATS_DETAILED */
6360     return errorCode;
6361
6362 }                               /*common_GiveUpCallBacks */
6363
6364
6365 afs_int32
6366 SRXAFS_GiveUpCallBacks(struct rx_call * acall, struct AFSCBFids * FidArray,
6367                        struct AFSCBs * CallBackArray)
6368 {
6369     return common_GiveUpCallBacks(acall, FidArray, CallBackArray);
6370 }                               /*SRXAFS_GiveUpCallBacks */
6371
6372 afs_int32
6373 SRXAFS_GiveUpAllCallBacks(struct rx_call * acall)
6374 {
6375     return common_GiveUpCallBacks(acall, 0, 0);
6376 }                               /*SRXAFS_GiveUpAllCallBacks */
6377
6378
6379 afs_int32
6380 SRXAFS_NGetVolumeInfo(struct rx_call * acall, char *avolid,
6381                       struct AFSVolumeInfo * avolinfo)
6382 {
6383     return (VNOVOL);            /* XXX Obsolete routine XXX */
6384
6385 }                               /*SRXAFS_NGetVolumeInfo */
6386
6387
6388 /*
6389  * Dummy routine. Should never be called (the cache manager should only
6390  * invoke this interface when communicating with a AFS/DFS Protocol
6391  * Translator).
6392  */
6393 afs_int32
6394 SRXAFS_Lookup(struct rx_call * call_p, struct AFSFid * afs_dfid_p,
6395               char *afs_name_p, struct AFSFid * afs_fid_p,
6396               struct AFSFetchStatus * afs_status_p,
6397               struct AFSFetchStatus * afs_dir_status_p,
6398               struct AFSCallBack * afs_callback_p,
6399               struct AFSVolSync * afs_sync_p)
6400 {
6401     return EINVAL;
6402 }
6403
6404
6405 afs_int32
6406 SRXAFS_GetCapabilities(struct rx_call * acall, Capabilities * capabilities)
6407 {
6408     afs_int32 code;
6409     struct rx_connection *tcon;
6410     struct host *thost;
6411     afs_uint32 *dataBuffP;
6412     afs_int32 dataBytes;
6413
6414     FS_LOCK;
6415     AFSCallStats.GetCapabilities++, AFSCallStats.TotalCalls++;
6416     afs_FullPerfStats.overall.fs_nGetCaps++;
6417     FS_UNLOCK;
6418     ViceLog(2, ("SAFS_GetCapabilties\n"));
6419
6420     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6421         goto Bad_GetCaps;
6422
6423     dataBytes = 1 * sizeof(afs_int32);
6424     dataBuffP = (afs_uint32 *) malloc(dataBytes);
6425     dataBuffP[0] = VICED_CAPABILITY_ERRORTRANS | VICED_CAPABILITY_WRITELOCKACL;
6426     dataBuffP[0] |= VICED_CAPABILITY_64BITFILES;
6427     if (saneacls)
6428         dataBuffP[0] |= VICED_CAPABILITY_SANEACLS;
6429
6430     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
6431     capabilities->Capabilities_val = dataBuffP;
6432
6433   Bad_GetCaps:
6434     code = CallPostamble(tcon, code, thost);
6435
6436
6437     return 0;
6438 }
6439
6440 afs_int32
6441 SRXAFS_FlushCPS(struct rx_call * acall, struct ViceIds * vids,
6442                 struct IPAddrs * addrs, afs_int32 spare1, afs_int32 * spare2,
6443                 afs_int32 * spare3)
6444 {
6445     int i;
6446     afs_int32 nids, naddrs;
6447     afs_int32 *vd, *addr;
6448     Error errorCode = 0;                /* return code to caller */
6449     struct client *client = 0;
6450
6451     ViceLog(1, ("SRXAFS_FlushCPS\n"));
6452     FS_LOCK;
6453     AFSCallStats.TotalCalls++;
6454     FS_UNLOCK;
6455     nids = vids->ViceIds_len;   /* # of users in here */
6456     naddrs = addrs->IPAddrs_len;        /* # of hosts in here */
6457     if (nids < 0 || naddrs < 0) {
6458         errorCode = EINVAL;
6459         goto Bad_FlushCPS;
6460     }
6461
6462     vd = vids->ViceIds_val;
6463     for (i = 0; i < nids; i++, vd++) {
6464         if (!*vd)
6465             continue;
6466         client = h_ID2Client(*vd);      /* returns write locked and refCounted, or NULL */
6467         if (!client)
6468             continue;
6469
6470         client->prfail = 2;     /* Means re-eval client's cps */
6471 #ifdef  notdef
6472         if (client->tcon) {
6473             rx_SetRock(((struct rx_connection *)client->tcon), 0);
6474         }
6475 #endif
6476         if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
6477             free(client->CPS.prlist_val);
6478             client->CPS.prlist_val = NULL;
6479             client->CPS.prlist_len = 0;
6480         }
6481         ReleaseWriteLock(&client->lock);
6482         PutClient(&client);
6483     }
6484
6485     addr = addrs->IPAddrs_val;
6486     for (i = 0; i < naddrs; i++, addr++) {
6487         if (*addr)
6488             h_flushhostcps(*addr, htons(7001));
6489     }
6490
6491   Bad_FlushCPS:
6492     ViceLog(2, ("SAFS_FlushCPS  returns %d\n", errorCode));
6493     return errorCode;
6494 }                               /*SRXAFS_FlushCPS */
6495
6496 /* worthless hack to let CS keep running ancient software */
6497 static int
6498 afs_vtoi(char *aname)
6499 {
6500     afs_int32 temp;
6501     int tc;
6502
6503     temp = 0;
6504     while ((tc = *aname++)) {
6505         if (tc > '9' || tc < '0')
6506             return 0;           /* invalid name */
6507         temp *= 10;
6508         temp += tc - '0';
6509     }
6510     return temp;
6511 }
6512
6513 /*
6514  * may get name or #, but must handle all weird cases (recognize readonly
6515  * or backup volumes by name or #
6516  */
6517 static afs_int32
6518 CopyVolumeEntry(char *aname, struct vldbentry *ave,
6519                 struct VolumeInfo *av)
6520 {
6521     int i, j, vol;
6522     afs_int32 mask, whichType;
6523     afs_uint32 *serverHost, *typePtr;
6524
6525     /* figure out what type we want if by name */
6526     i = strlen(aname);
6527     if (i >= 8 && strcmp(aname + i - 7, ".backup") == 0)
6528         whichType = BACKVOL;
6529     else if (i >= 10 && strcmp(aname + i - 9, ".readonly") == 0)
6530         whichType = ROVOL;
6531     else
6532         whichType = RWVOL;
6533
6534     vol = afs_vtoi(aname);
6535     if (vol == 0)
6536         vol = ave->volumeId[whichType];
6537
6538     /*
6539      * Now vol has volume # we're interested in.  Next, figure out the type
6540      * of the volume by looking finding it in the vldb entry
6541      */
6542     if ((ave->flags & VLF_RWEXISTS) && vol == ave->volumeId[RWVOL]) {
6543         mask = VLSF_RWVOL;
6544         whichType = RWVOL;
6545     } else if ((ave->flags & VLF_ROEXISTS) && vol == ave->volumeId[ROVOL]) {
6546         mask = VLSF_ROVOL;
6547         whichType = ROVOL;
6548     } else if ((ave->flags & VLF_BACKEXISTS) && vol == ave->volumeId[BACKVOL]) {
6549         mask = VLSF_RWVOL;      /* backup always is on the same volume as parent */
6550         whichType = BACKVOL;
6551     } else
6552         return EINVAL;          /* error: can't find volume in vldb entry */
6553
6554     typePtr = &av->Type0;
6555     serverHost = &av->Server0;
6556     av->Vid = vol;
6557     av->Type = whichType;
6558     av->Type0 = av->Type1 = av->Type2 = av->Type3 = av->Type4 = 0;
6559     if (ave->flags & VLF_RWEXISTS)
6560         typePtr[RWVOL] = ave->volumeId[RWVOL];
6561     if (ave->flags & VLF_ROEXISTS)
6562         typePtr[ROVOL] = ave->volumeId[ROVOL];
6563     if (ave->flags & VLF_BACKEXISTS)
6564         typePtr[BACKVOL] = ave->volumeId[BACKVOL];
6565
6566     for (i = 0, j = 0; i < ave->nServers; i++) {
6567         if ((ave->serverFlags[i] & mask) == 0)
6568             continue;           /* wrong volume */
6569         serverHost[j] = ave->serverNumber[i];
6570         j++;
6571     }
6572     av->ServerCount = j;
6573     if (j < 8)
6574         serverHost[j++] = 0;    /* bogus 8, but compat only now */
6575     return 0;
6576 }
6577
6578 static afs_int32
6579 TryLocalVLServer(char *avolid, struct VolumeInfo *avolinfo)
6580 {
6581     static struct rx_connection *vlConn = 0;
6582     static int down = 0;
6583     static afs_int32 lastDownTime = 0;
6584     struct vldbentry tve;
6585     struct rx_securityClass *vlSec;
6586     afs_int32 code;
6587
6588     if (!vlConn) {
6589         vlSec = rxnull_NewClientSecurityObject();
6590         vlConn =
6591             rx_NewConnection(htonl(0x7f000001), htons(7003), 52, vlSec, 0);
6592         rx_SetConnDeadTime(vlConn, 15); /* don't wait long */
6593     }
6594     if (down && (FT_ApproxTime() < lastDownTime + 180)) {
6595         return 1;               /* failure */
6596     }
6597
6598     code = VL_GetEntryByNameO(vlConn, avolid, &tve);
6599     if (code >= 0)
6600         down = 0;               /* call worked */
6601     if (code) {
6602         if (code < 0) {
6603             lastDownTime = FT_ApproxTime();     /* last time we tried an RPC */
6604             down = 1;
6605         }
6606         return code;
6607     }
6608
6609     /* otherwise convert to old format vldb entry */
6610     code = CopyVolumeEntry(avolid, &tve, avolinfo);
6611     return code;
6612 }
6613
6614
6615
6616
6617
6618
6619 afs_int32
6620 SRXAFS_GetVolumeInfo(struct rx_call * acall, char *avolid,
6621                      struct VolumeInfo * avolinfo)
6622 {
6623     afs_int32 code;
6624     struct rx_connection *tcon;
6625     struct host *thost;
6626 #if FS_STATS_DETAILED
6627     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6628     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6629     struct timeval elapsedTime; /* Transfer time */
6630
6631     /*
6632      * Set our stats pointer, remember when the RPC operation started, and
6633      * tally the operation.
6634      */
6635     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMEINFO]);
6636     FS_LOCK;
6637     (opP->numOps)++;
6638     FS_UNLOCK;
6639     FT_GetTimeOfDay(&opStartTime, 0);
6640 #endif /* FS_STATS_DETAILED */
6641     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6642         goto Bad_GetVolumeInfo;
6643
6644     FS_LOCK;
6645     AFSCallStats.GetVolumeInfo++, AFSCallStats.TotalCalls++;
6646     FS_UNLOCK;
6647     code = TryLocalVLServer(avolid, avolinfo);
6648     ViceLog(1,
6649             ("SAFS_GetVolumeInfo returns %d, Volume %u, type %x, servers %x %x %x %x...\n",
6650              code, avolinfo->Vid, avolinfo->Type, avolinfo->Server0,
6651              avolinfo->Server1, avolinfo->Server2, avolinfo->Server3));
6652     avolinfo->Type4 = 0xabcd9999;       /* tell us to try new vldb */
6653
6654   Bad_GetVolumeInfo:
6655     code = CallPostamble(tcon, code, thost);
6656
6657 #if FS_STATS_DETAILED
6658     FT_GetTimeOfDay(&opStopTime, 0);
6659     if (code == 0) {
6660         FS_LOCK;
6661         (opP->numSuccesses)++;
6662         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6663         fs_stats_AddTo((opP->sumTime), elapsedTime);
6664         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6665         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6666             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6667         }
6668         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6669             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6670         }
6671         FS_UNLOCK;
6672     }
6673 #endif /* FS_STATS_DETAILED */
6674
6675     return code;
6676
6677 }                               /*SRXAFS_GetVolumeInfo */
6678
6679
6680 afs_int32
6681 SRXAFS_GetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6682                        AFSFetchVolumeStatus * FetchVolStatus, char **Name,
6683                        char **OfflineMsg, char **Motd)
6684 {
6685     Vnode *targetptr = 0;       /* vnode of the new file */
6686     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6687     Error errorCode = 0;                /* error code */
6688     Volume *volptr = 0;         /* pointer to the volume header */
6689     struct client *client = 0;  /* pointer to client entry */
6690     afs_int32 rights, anyrights;        /* rights for this and any user */
6691     AFSFid dummyFid;
6692     struct rx_connection *tcon;
6693     struct host *thost;
6694     struct client *t_client = NULL;     /* tmp ptr to client data */
6695 #if FS_STATS_DETAILED
6696     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6697     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6698     struct timeval elapsedTime; /* Transfer time */
6699
6700     /*
6701      * Set our stats pointer, remember when the RPC operation started, and
6702      * tally the operation.
6703      */
6704     opP =
6705         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMESTATUS]);
6706     FS_LOCK;
6707     (opP->numOps)++;
6708     FS_UNLOCK;
6709     FT_GetTimeOfDay(&opStartTime, 0);
6710 #endif /* FS_STATS_DETAILED */
6711
6712     ViceLog(1, ("SAFS_GetVolumeStatus for volume %u\n", avolid));
6713     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6714         goto Bad_GetVolumeStatus;
6715
6716     FS_LOCK;
6717     AFSCallStats.GetVolumeStatus++, AFSCallStats.TotalCalls++;
6718     FS_UNLOCK;
6719     if (avolid == 0) {
6720         errorCode = EINVAL;
6721         goto Bad_GetVolumeStatus;
6722     }
6723     dummyFid.Volume = avolid, dummyFid.Vnode =
6724         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6725
6726     if ((errorCode =
6727          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6728                           &parentwhentargetnotdir, &client, READ_LOCK,
6729                           &rights, &anyrights)))
6730         goto Bad_GetVolumeStatus;
6731
6732     if ((VanillaUser(client)) && (!(rights & PRSFS_READ))) {
6733         errorCode = EACCES;
6734         goto Bad_GetVolumeStatus;
6735     }
6736     (void)RXGetVolumeStatus(FetchVolStatus, Name, OfflineMsg, Motd, volptr);
6737
6738   Bad_GetVolumeStatus:
6739     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
6740                            volptr, &client);
6741     ViceLog(2, ("SAFS_GetVolumeStatus returns %d\n", errorCode));
6742     /* next is to guarantee out strings exist for stub */
6743     if (*Name == 0) {
6744         *Name = (char *)malloc(1);
6745         **Name = 0;
6746     }
6747     if (*Motd == 0) {
6748         *Motd = (char *)malloc(1);
6749         **Motd = 0;
6750     }
6751     if (*OfflineMsg == 0) {
6752         *OfflineMsg = (char *)malloc(1);
6753         **OfflineMsg = 0;
6754     }
6755     errorCode = CallPostamble(tcon, errorCode, thost);
6756
6757     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6758
6759 #if FS_STATS_DETAILED
6760     FT_GetTimeOfDay(&opStopTime, 0);
6761     if (errorCode == 0) {
6762         FS_LOCK;
6763         (opP->numSuccesses)++;
6764         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6765         fs_stats_AddTo((opP->sumTime), elapsedTime);
6766         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6767         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6768             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6769         }
6770         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6771             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6772         }
6773         FS_UNLOCK;
6774     }
6775 #endif /* FS_STATS_DETAILED */
6776
6777     osi_auditU(acall, GetVolumeStatusEvent, errorCode,
6778                AUD_ID, t_client ? t_client->ViceId : 0,
6779                AUD_LONG, avolid, AUD_STR, *Name, AUD_END);
6780     return (errorCode);
6781
6782 }                               /*SRXAFS_GetVolumeStatus */
6783
6784
6785 afs_int32
6786 SRXAFS_SetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6787                        AFSStoreVolumeStatus * StoreVolStatus, char *Name,
6788                        char *OfflineMsg, char *Motd)
6789 {
6790     Vnode *targetptr = 0;       /* vnode of the new file */
6791     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6792     Error errorCode = 0;                /* error code */
6793     Volume *volptr = 0;         /* pointer to the volume header */
6794     struct client *client = 0;  /* pointer to client entry */
6795     afs_int32 rights, anyrights;        /* rights for this and any user */
6796     AFSFid dummyFid;
6797     struct rx_connection *tcon = rx_ConnectionOf(acall);
6798     struct host *thost;
6799     struct client *t_client = NULL;     /* tmp ptr to client data */
6800 #if FS_STATS_DETAILED
6801     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6802     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6803     struct timeval elapsedTime; /* Transfer time */
6804
6805     /*
6806      * Set our stats pointer, remember when the RPC operation started, and
6807      * tally the operation.
6808      */
6809     opP =
6810         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETVOLUMESTATUS]);
6811     FS_LOCK;
6812     (opP->numOps)++;
6813     FS_UNLOCK;
6814     FT_GetTimeOfDay(&opStartTime, 0);
6815 #endif /* FS_STATS_DETAILED */
6816
6817     ViceLog(1, ("SAFS_SetVolumeStatus for volume %u\n", avolid));
6818     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6819         goto Bad_SetVolumeStatus;
6820
6821     FS_LOCK;
6822     AFSCallStats.SetVolumeStatus++, AFSCallStats.TotalCalls++;
6823     FS_UNLOCK;
6824     if (avolid == 0) {
6825         errorCode = EINVAL;
6826         goto Bad_SetVolumeStatus;
6827     }
6828     dummyFid.Volume = avolid, dummyFid.Vnode =
6829         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6830
6831     if ((errorCode =
6832          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6833                           &parentwhentargetnotdir, &client, READ_LOCK,
6834                           &rights, &anyrights)))
6835         goto Bad_SetVolumeStatus;
6836
6837     if (readonlyServer) {
6838         errorCode = VREADONLY;
6839         goto Bad_SetVolumeStatus;
6840     }
6841     if (VanillaUser(client)) {
6842         errorCode = EACCES;
6843         goto Bad_SetVolumeStatus;
6844     }
6845
6846     errorCode =
6847         RXUpdate_VolumeStatus(volptr, StoreVolStatus, Name, OfflineMsg, Motd);
6848
6849   Bad_SetVolumeStatus:
6850     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
6851                      volptr, &client);
6852     ViceLog(2, ("SAFS_SetVolumeStatus returns %d\n", errorCode));
6853     errorCode = CallPostamble(tcon, errorCode, thost);
6854
6855     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6856
6857 #if FS_STATS_DETAILED
6858     FT_GetTimeOfDay(&opStopTime, 0);
6859     if (errorCode == 0) {
6860         FS_LOCK;
6861         (opP->numSuccesses)++;
6862         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6863         fs_stats_AddTo((opP->sumTime), elapsedTime);
6864         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6865         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6866             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6867         }
6868         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6869             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6870         }
6871         FS_UNLOCK;
6872     }
6873 #endif /* FS_STATS_DETAILED */
6874
6875     osi_auditU(acall, SetVolumeStatusEvent, errorCode,
6876                AUD_ID, t_client ? t_client->ViceId : 0,
6877                AUD_LONG, avolid, AUD_STR, Name, AUD_END);
6878     return (errorCode);
6879 }                               /*SRXAFS_SetVolumeStatus */
6880
6881 #define DEFAULTVOLUME   "root.afs"
6882
6883 afs_int32
6884 SRXAFS_GetRootVolume(struct rx_call * acall, char **VolumeName)
6885 {
6886 #ifdef notdef
6887     int fd;
6888     int len;
6889     char *temp;
6890     struct rx_connection *tcon;
6891     struct host *thost;
6892     Error errorCode = 0;
6893 #endif
6894 #if FS_STATS_DETAILED
6895     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6896     struct timeval opStartTime; /* Start time for RPC op */
6897 #ifdef notdef
6898     struct timeval opStopTime;
6899     struct timeval elapsedTime; /* Transfer time */
6900 #endif
6901
6902     /*
6903      * Set our stats pointer, remember when the RPC operation started, and
6904      * tally the operation.
6905      */
6906     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETROOTVOLUME]);
6907     FS_LOCK;
6908     (opP->numOps)++;
6909     FS_UNLOCK;
6910     FT_GetTimeOfDay(&opStartTime, 0);
6911 #endif /* FS_STATS_DETAILED */
6912
6913     return FSERR_EOPNOTSUPP;
6914
6915 #ifdef  notdef
6916     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))
6917         goto Bad_GetRootVolume;
6918     FS_LOCK;
6919     AFSCallStats.GetRootVolume++, AFSCallStats.TotalCalls++;
6920     FS_UNLOCK;
6921     temp = malloc(256);
6922     fd = afs_open(AFSDIR_SERVER_ROOTVOL_FILEPATH, O_RDONLY, 0666);
6923     if (fd <= 0)
6924         strcpy(temp, DEFAULTVOLUME);
6925     else {
6926 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6927         lockf(fd, F_LOCK, 0);
6928 #else
6929         flock(fd, LOCK_EX);
6930 #endif
6931         len = read(fd, temp, 256);
6932 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6933         lockf(fd, F_ULOCK, 0);
6934 #else
6935         flock(fd, LOCK_UN);
6936 #endif
6937         close(fd);
6938         if (temp[len - 1] == '\n')
6939             len--;
6940         temp[len] = '\0';
6941     }
6942     *VolumeName = temp;         /* freed by rx server-side stub */
6943
6944   Bad_GetRootVolume:
6945     errorCode = CallPostamble(tcon, errorCode, thost);
6946
6947 #if FS_STATS_DETAILED
6948     FT_GetTimeOfDay(&opStopTime, 0);
6949     if (errorCode == 0) {
6950         FS_LOCK;
6951         (opP->numSuccesses)++;
6952         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6953         fs_stats_AddTo((opP->sumTime), elapsedTime);
6954         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6955         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6956             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6957         }
6958         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6959             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6960         }
6961         FS_UNLOCK;
6962     }
6963 #endif /* FS_STATS_DETAILED */
6964
6965     return (errorCode);
6966 #endif /* notdef */
6967
6968 }                               /*SRXAFS_GetRootVolume */
6969
6970
6971 /* still works because a struct CBS is the same as a struct AFSOpaque */
6972 afs_int32
6973 SRXAFS_CheckToken(struct rx_call * acall, afs_int32 AfsId,
6974                   struct AFSOpaque * Token)
6975 {
6976     afs_int32 code;
6977     struct rx_connection *tcon;
6978     struct host *thost;
6979 #if FS_STATS_DETAILED
6980     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6981     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6982     struct timeval elapsedTime; /* Transfer time */
6983
6984     /*
6985      * Set our stats pointer, remember when the RPC operation started, and
6986      * tally the operation.
6987      */
6988     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CHECKTOKEN]);
6989     FS_LOCK;
6990     (opP->numOps)++;
6991     FS_UNLOCK;
6992     FT_GetTimeOfDay(&opStartTime, 0);
6993 #endif /* FS_STATS_DETAILED */
6994
6995     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6996         goto Bad_CheckToken;
6997
6998     code = FSERR_ECONNREFUSED;
6999
7000   Bad_CheckToken:
7001     code = CallPostamble(tcon, code, thost);
7002
7003 #if FS_STATS_DETAILED
7004     FT_GetTimeOfDay(&opStopTime, 0);
7005     if (code == 0) {
7006         FS_LOCK;
7007         (opP->numSuccesses)++;
7008         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
7009         fs_stats_AddTo((opP->sumTime), elapsedTime);
7010         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
7011         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
7012             fs_stats_TimeAssign((opP->minTime), elapsedTime);
7013         }
7014         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
7015             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
7016         }
7017         FS_UNLOCK;
7018     }
7019 #endif /* FS_STATS_DETAILED */
7020
7021     return code;
7022
7023 }                               /*SRXAFS_CheckToken */
7024
7025 afs_int32
7026 SRXAFS_GetTime(struct rx_call * acall, afs_uint32 * Seconds,
7027                afs_uint32 * USeconds)
7028 {
7029     afs_int32 code;
7030     struct rx_connection *tcon;
7031     struct host *thost;
7032     struct timeval tpl;
7033 #if FS_STATS_DETAILED
7034     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
7035     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
7036     struct timeval elapsedTime; /* Transfer time */
7037
7038     /*
7039      * Set our stats pointer, remember when the RPC operation started, and
7040      * tally the operation.
7041      */
7042     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETTIME]);
7043     FS_LOCK;
7044     (opP->numOps)++;
7045     FS_UNLOCK;
7046     FT_GetTimeOfDay(&opStartTime, 0);
7047 #endif /* FS_STATS_DETAILED */
7048
7049     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
7050         goto Bad_GetTime;
7051
7052     FS_LOCK;
7053     AFSCallStats.GetTime++, AFSCallStats.TotalCalls++;
7054     FS_UNLOCK;
7055     FT_GetTimeOfDay(&tpl, 0);
7056     *Seconds = tpl.tv_sec;
7057     *USeconds = tpl.tv_usec;
7058
7059     ViceLog(2, ("SAFS_GetTime returns %u, %u\n", *Seconds, *USeconds));
7060
7061   Bad_GetTime:
7062     code = CallPostamble(tcon, code, thost);
7063
7064 #if FS_STATS_DETAILED
7065     FT_GetTimeOfDay(&opStopTime, 0);
7066     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
7067     if (code == 0) {
7068         FS_LOCK;
7069         (opP->numSuccesses)++;
7070         fs_stats_AddTo((opP->sumTime), elapsedTime);
7071         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
7072         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
7073             fs_stats_TimeAssign((opP->minTime), elapsedTime);
7074         }
7075         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
7076             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
7077         }
7078         FS_UNLOCK;
7079     }
7080 #endif /* FS_STATS_DETAILED */
7081
7082     return code;
7083
7084 }                               /*SRXAFS_GetTime */
7085
7086
7087 /*
7088  * FetchData_RXStyle
7089  *
7090  * Purpose:
7091  *      Implement a client's data fetch using Rx.
7092  *
7093  * Arguments:
7094  *      volptr          : Ptr to the given volume's info.
7095  *      targetptr       : Pointer to the vnode involved.
7096  *      Call            : Ptr to the Rx call involved.
7097  *      Pos             : Offset within the file.
7098  *      Len             : Length in bytes to read; this value is bogus!
7099  * if FS_STATS_DETAILED
7100  *      a_bytesToFetchP : Set to the number of bytes to be fetched from
7101  *                        the File Server.
7102  *      a_bytesFetchedP : Set to the actual number of bytes fetched from
7103  *                        the File Server.
7104  * endif
7105  */
7106
7107 afs_int32
7108 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
7109                   struct rx_call * Call, afs_sfsize_t Pos,
7110                   afs_sfsize_t Len, afs_int32 Int64Mode,
7111 #if FS_STATS_DETAILED
7112                   afs_sfsize_t * a_bytesToFetchP,
7113                   afs_sfsize_t * a_bytesFetchedP
7114 #endif                          /* FS_STATS_DETAILED */
7115     )
7116 {
7117     struct timeval StartTime, StopTime; /* used to calculate file  transfer rates */
7118     IHandle_t *ihP;
7119     FdHandle_t *fdP;
7120 #ifndef HAVE_PIOV
7121     char *tbuffer;
7122 #else /* HAVE_PIOV */
7123     struct iovec tiov[RX_MAXIOVECS];
7124     int tnio;
7125 #endif /* HAVE_PIOV */
7126     afs_sfsize_t tlen;
7127     afs_int32 optSize;
7128
7129 #if FS_STATS_DETAILED
7130     /*
7131      * Initialize the byte count arguments.
7132      */
7133     (*a_bytesToFetchP) = 0;
7134     (*a_bytesFetchedP) = 0;
7135 #endif /* FS_STATS_DETAILED */
7136
7137
7138     ViceLog(25,
7139             ("FetchData_RXStyle: Pos %llu, Len %llu\n", (afs_uintmax_t) Pos,
7140              (afs_uintmax_t) Len));
7141
7142     if (!VN_GET_INO(targetptr)) {
7143         afs_int32 zero = htonl(0);
7144         /*
7145          * This is used for newly created files; we simply send 0 bytes
7146          * back to make the cache manager happy...
7147          */
7148         if (Int64Mode)
7149             rx_Write(Call, (char *)&zero, sizeof(afs_int32));   /* send 0-length  */
7150         rx_Write(Call, (char *)&zero, sizeof(afs_int32));       /* send 0-length  */
7151         return (0);
7152     }
7153     FT_GetTimeOfDay(&StartTime, 0);
7154     ihP = targetptr->handle;
7155     fdP = IH_OPEN(ihP);
7156     if (fdP == NULL) {
7157         VTakeOffline(volptr);
7158         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7159                     volptr->hashid));
7160         return EIO;
7161     }
7162     optSize = sendBufSize;
7163     tlen = FDH_SIZE(fdP);
7164     ViceLog(25,
7165             ("FetchData_RXStyle: file size %llu\n", (afs_uintmax_t) tlen));
7166     if (tlen < 0) {
7167         FDH_CLOSE(fdP);
7168         VTakeOffline(volptr);
7169         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7170                     volptr->hashid));
7171         return EIO;
7172     }
7173     if (CheckLength(volptr, targetptr, tlen)) {
7174         FDH_CLOSE(fdP);
7175         VTakeOffline(volptr);
7176         return VSALVAGE;
7177     }
7178     if (Pos > tlen) {
7179         Len = 0;
7180     }
7181
7182     if (Pos + Len > tlen) /* get length we should send */
7183         Len = ((tlen - Pos) < 0) ? 0 : tlen - Pos;
7184
7185     {
7186         afs_int32 high, low;
7187         SplitOffsetOrSize(Len, high, low);
7188         osi_Assert(Int64Mode || (Len >= 0 && high == 0) || Len < 0);
7189         if (Int64Mode) {
7190             high = htonl(high);
7191             rx_Write(Call, (char *)&high, sizeof(afs_int32));   /* High order bits */
7192         }
7193         low = htonl(low);
7194         rx_Write(Call, (char *)&low, sizeof(afs_int32));        /* send length on fetch */
7195     }
7196 #if FS_STATS_DETAILED
7197     (*a_bytesToFetchP) = Len;
7198 #endif /* FS_STATS_DETAILED */
7199 #ifndef HAVE_PIOV
7200     tbuffer = AllocSendBuffer();
7201 #endif /* HAVE_PIOV */
7202     while (Len > 0) {
7203         size_t wlen;
7204         ssize_t nBytes;
7205         if (Len > optSize)
7206             wlen = optSize;
7207         else
7208             wlen = Len;
7209 #ifndef HAVE_PIOV
7210         nBytes = FDH_PREAD(fdP, tbuffer, wlen, Pos);
7211         if (nBytes != wlen) {
7212             FDH_CLOSE(fdP);
7213             FreeSendBuffer((struct afs_buffer *)tbuffer);
7214             VTakeOffline(volptr);
7215             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7216                         volptr->hashid));
7217             return EIO;
7218         }
7219         nBytes = rx_Write(Call, tbuffer, wlen);
7220 #else /* HAVE_PIOV */
7221         nBytes = rx_WritevAlloc(Call, tiov, &tnio, RX_MAXIOVECS, wlen);
7222         if (nBytes <= 0) {
7223             FDH_CLOSE(fdP);
7224             return EIO;
7225         }
7226         wlen = nBytes;
7227         nBytes = FDH_PREADV(fdP, tiov, tnio, Pos);
7228         if (nBytes != wlen) {
7229             FDH_CLOSE(fdP);
7230             VTakeOffline(volptr);
7231             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7232                         volptr->hashid));
7233             return EIO;
7234         }
7235         nBytes = rx_Writev(Call, tiov, tnio, wlen);
7236 #endif /* HAVE_PIOV */
7237         Pos += wlen;
7238 #if FS_STATS_DETAILED
7239         /*
7240          * Bump the number of bytes actually sent by the number from this
7241          * latest iteration
7242          */
7243         (*a_bytesFetchedP) += nBytes;
7244 #endif /* FS_STATS_DETAILED */
7245         if (nBytes != wlen) {
7246             afs_int32 err;
7247             FDH_CLOSE(fdP);
7248 #ifndef HAVE_PIOV
7249             FreeSendBuffer((struct afs_buffer *)tbuffer);
7250 #endif /* HAVE_PIOV */
7251             err = VIsGoingOffline(volptr);
7252             if (err) {
7253                 return err;
7254             }
7255             return -31;
7256         }
7257         Len -= wlen;
7258     }
7259 #ifndef HAVE_PIOV
7260     FreeSendBuffer((struct afs_buffer *)tbuffer);
7261 #endif /* HAVE_PIOV */
7262     FDH_CLOSE(fdP);
7263     FT_GetTimeOfDay(&StopTime, 0);
7264
7265     /* Adjust all Fetch Data related stats */
7266     FS_LOCK;
7267     if (AFSCallStats.TotalFetchedBytes > 2000000000)    /* Reset if over 2 billion */
7268         AFSCallStats.TotalFetchedBytes = AFSCallStats.AccumFetchTime = 0;
7269     AFSCallStats.AccumFetchTime +=
7270         ((StopTime.tv_sec - StartTime.tv_sec) * 1000) +
7271         ((StopTime.tv_usec - StartTime.tv_usec) / 1000);
7272     {
7273         afs_fsize_t targLen;
7274         VN_GET_LEN(targLen, targetptr);
7275         AFSCallStats.TotalFetchedBytes += targLen;
7276         AFSCallStats.FetchSize1++;
7277         if (targLen < SIZE2)
7278             AFSCallStats.FetchSize2++;
7279         else if (targLen < SIZE3)
7280             AFSCallStats.FetchSize3++;
7281         else if (targLen < SIZE4)
7282             AFSCallStats.FetchSize4++;
7283         else
7284             AFSCallStats.FetchSize5++;
7285     }
7286     FS_UNLOCK;
7287     return (0);
7288
7289 }                               /*FetchData_RXStyle */
7290
7291 static int
7292 GetLinkCountAndSize(Volume * vp, FdHandle_t * fdP, int *lc,
7293                     afs_sfsize_t * size)
7294 {
7295 #ifdef AFS_NAMEI_ENV
7296     FdHandle_t *lhp;
7297     lhp = IH_OPEN(V_linkHandle(vp));
7298     if (!lhp)
7299         return EIO;
7300     *lc = namei_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0, 0, 1);
7301     FDH_CLOSE(lhp);
7302     if (*lc < 0)
7303         return -1;
7304     *size = OS_SIZE(fdP->fd_fd);
7305     return (*size == -1) ? -1 : 0;
7306 #else
7307     struct afs_stat status;
7308
7309     if (afs_fstat(fdP->fd_fd, &status) < 0) {
7310         return -1;
7311     }
7312
7313     *lc = GetLinkCount(vp, &status);
7314     *size = status.st_size;
7315     return 0;
7316 #endif
7317 }
7318
7319 /*
7320  * StoreData_RXStyle
7321  *
7322  * Purpose:
7323  *      Implement a client's data store using Rx.
7324  *
7325  * Arguments:
7326  *      volptr          : Ptr to the given volume's info.
7327  *      targetptr       : Pointer to the vnode involved.
7328  *      Call            : Ptr to the Rx call involved.
7329  *      Pos             : Offset within the file.
7330  *      Len             : Length in bytes to store; this value is bogus!
7331  * if FS_STATS_DETAILED
7332  *      a_bytesToStoreP : Set to the number of bytes to be stored to
7333  *                        the File Server.
7334  *      a_bytesStoredP  : Set to the actual number of bytes stored to
7335  *                        the File Server.
7336  * endif
7337  */
7338 afs_int32
7339 StoreData_RXStyle(Volume * volptr, Vnode * targetptr, struct AFSFid * Fid,
7340                   struct client * client, struct rx_call * Call,
7341                   afs_fsize_t Pos, afs_fsize_t Length, afs_fsize_t FileLength,
7342                   int sync,
7343 #if FS_STATS_DETAILED
7344                   afs_sfsize_t * a_bytesToStoreP,
7345                   afs_sfsize_t * a_bytesStoredP
7346 #endif                          /* FS_STATS_DETAILED */
7347     )
7348 {
7349     afs_sfsize_t bytesTransfered;       /* number of bytes actually transfered */
7350     struct timeval StartTime, StopTime; /* Used to measure how long the store takes */
7351     Error errorCode = 0;                /* Returned error code to caller */
7352 #ifndef HAVE_PIOV
7353     char *tbuffer;      /* data copying buffer */
7354 #else /* HAVE_PIOV */
7355     struct iovec tiov[RX_MAXIOVECS];    /* no data copying with iovec */
7356     int tnio;                   /* temp for iovec size */
7357 #endif /* HAVE_PIOV */
7358     afs_sfsize_t tlen;          /* temp for xfr length */
7359     Inode tinode;               /* inode for I/O */
7360     afs_int32 optSize;          /* optimal transfer size */
7361     afs_sfsize_t DataLength = 0;        /* size of inode */
7362     afs_sfsize_t TruncatedLength;       /* size after ftruncate */
7363     afs_fsize_t NewLength;      /* size after this store completes */
7364     afs_sfsize_t adjustSize;    /* bytes to call VAdjust... with */
7365     int linkCount = 0;          /* link count on inode */
7366     afs_fsize_t CoW_off, CoW_len;
7367     ssize_t nBytes;
7368     FdHandle_t *fdP, *origfdP = NULL;
7369     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
7370     afs_ino_str_t stmp;
7371
7372 #if FS_STATS_DETAILED
7373     /*
7374      * Initialize the byte count arguments.
7375      */
7376     (*a_bytesToStoreP) = 0;
7377     (*a_bytesStoredP) = 0;
7378 #endif /* FS_STATS_DETAILED */
7379
7380     /*
7381      * We break the callbacks here so that the following signal will not
7382      * leave a window.
7383      */
7384     BreakCallBack(client->host, Fid, 0);
7385
7386     if (Pos == -1 || VN_GET_INO(targetptr) == 0) {
7387         /* the inode should have been created in Alloc_NewVnode */
7388         logHostAddr.s_addr = rxr_HostOf(rx_ConnectionOf(Call));
7389         ViceLog(0,
7390                 ("StoreData_RXStyle : Inode non-existent Fid = %u.%u.%u, inode = %llu, Pos %llu Host %s:%d\n",
7391                  Fid->Volume, Fid->Vnode, Fid->Unique,
7392                  (afs_uintmax_t) VN_GET_INO(targetptr), (afs_uintmax_t) Pos,
7393                  inet_ntoa(logHostAddr), ntohs(rxr_PortOf(rx_ConnectionOf(Call)))));
7394         return ENOENT;          /* is this proper error code? */
7395     } else {
7396         /*
7397          * See if the file has several links (from other volumes).  If it
7398          * does, then we have to make a copy before changing it to avoid
7399          *changing read-only clones of this dude
7400          */
7401         ViceLog(25,
7402                 ("StoreData_RXStyle : Opening inode %s\n",
7403                  PrintInode(stmp, VN_GET_INO(targetptr))));
7404         fdP = IH_OPEN(targetptr->handle);
7405         if (fdP == NULL)
7406             return ENOENT;
7407         if (GetLinkCountAndSize(volptr, fdP, &linkCount, &DataLength) < 0) {
7408             FDH_CLOSE(fdP);
7409             VTakeOffline(volptr);
7410             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7411                         volptr->hashid));
7412             return EIO;
7413         }
7414         if (CheckLength(volptr, targetptr, DataLength)) {
7415             FDH_CLOSE(fdP);
7416             VTakeOffline(volptr);
7417             return VSALVAGE;
7418         }
7419
7420         if (linkCount != 1) {
7421             afs_fsize_t size;
7422             ViceLog(25,
7423                     ("StoreData_RXStyle : inode %s has more than onelink\n",
7424                      PrintInode(stmp, VN_GET_INO(targetptr))));
7425             /* other volumes share this data, better copy it first */
7426
7427             /* Adjust the disk block count by the creation of the new inode.
7428              * We call the special VDiskUsage so we don't adjust the volume's
7429              * quota since we don't want to penalyze the user for afs's internal
7430              * mechanisms (i.e. copy on write overhead.) Also the right size
7431              * of the disk will be recorded...
7432              */
7433             origfdP = fdP;
7434             VN_GET_LEN(size, targetptr);
7435             volptr->partition->flags &= ~PART_DONTUPDATE;
7436             VSetPartitionDiskUsage(volptr->partition);
7437             volptr->partition->flags |= PART_DONTUPDATE;
7438             if ((errorCode = VDiskUsage(volptr, nBlocks(size)))) {
7439                 volptr->partition->flags &= ~PART_DONTUPDATE;
7440                 FDH_CLOSE(origfdP);
7441                 return (errorCode);
7442             }
7443
7444             CoW_len = (FileLength >= (Length + Pos)) ? FileLength - Length : Pos;
7445             CopyOnWrite_calls++;
7446             if (CoW_len == 0) CopyOnWrite_size0++;
7447             if (Pos == 0) CopyOnWrite_off0++;
7448             if (CoW_len > CopyOnWrite_maxsize) CopyOnWrite_maxsize = CoW_len;
7449
7450             ViceLog(1, ("StoreData : calling CopyOnWrite on vnode %u.%u (%s) "
7451                         "off 0x0 size 0x%llx\n",
7452                         afs_printable_VolumeId_u(V_id(volptr)),
7453                         afs_printable_VnodeId_u(targetptr->vnodeNumber),
7454                         V_name(volptr), Pos));
7455             if ((errorCode = CopyOnWrite(targetptr, volptr, 0, Pos))) {
7456                 ViceLog(25, ("StoreData : CopyOnWrite failed\n"));
7457                 volptr->partition->flags &= ~PART_DONTUPDATE;
7458                 FDH_CLOSE(origfdP);
7459                 return (errorCode);
7460             }
7461             volptr->partition->flags &= ~PART_DONTUPDATE;
7462             VSetPartitionDiskUsage(volptr->partition);
7463             fdP = IH_OPEN(targetptr->handle);
7464             if (fdP == NULL) {
7465                 ViceLog(25,
7466                         ("StoreData : Reopen after CopyOnWrite failed\n"));
7467                 FDH_REALLYCLOSE(origfdP);
7468                 return ENOENT;
7469             }
7470         }
7471         tinode = VN_GET_INO(targetptr);
7472     }
7473     if (!VALID_INO(tinode)) {
7474         VTakeOffline(volptr);
7475         ViceLog(0,("Volume %u now offline, must be salvaged.\n",
7476                    volptr->hashid));
7477         return EIO;
7478     }
7479
7480     /* compute new file length */
7481     NewLength = DataLength;
7482     if (FileLength < NewLength)
7483         /* simulate truncate */
7484         NewLength = FileLength;
7485     TruncatedLength = NewLength;        /* remember length after possible ftruncate */
7486     if (Pos + Length > NewLength)
7487         NewLength = Pos + Length;       /* and write */
7488
7489     /* adjust the disk block count by the difference in the files */
7490     {
7491         afs_fsize_t targSize;
7492         VN_GET_LEN(targSize, targetptr);
7493         adjustSize = nBlocks(NewLength) - nBlocks(targSize);
7494     }
7495     if ((errorCode =
7496          AdjustDiskUsage(volptr, adjustSize,
7497                          adjustSize - SpareComp(volptr)))) {
7498         FDH_CLOSE(fdP);
7499         if (origfdP) FDH_REALLYCLOSE(origfdP);
7500         return (errorCode);
7501     }
7502
7503     /* can signal cache manager to proceed from close now */
7504     /* this bit means that the locks are set and protections are OK */
7505     rx_SetLocalStatus(Call, 1);
7506
7507     FT_GetTimeOfDay(&StartTime, 0);
7508
7509     optSize = sendBufSize;
7510     ViceLog(25,
7511             ("StoreData_RXStyle: Pos %llu, DataLength %llu, FileLength %llu, Length %llu\n",
7512              (afs_uintmax_t) Pos, (afs_uintmax_t) DataLength,
7513              (afs_uintmax_t) FileLength, (afs_uintmax_t) Length));
7514
7515     /* truncate the file iff it needs it (ftruncate is slow even when its a noop) */
7516     if (FileLength < DataLength)
7517         FDH_TRUNC(fdP, FileLength);
7518     bytesTransfered = 0;
7519 #ifndef HAVE_PIOV
7520     tbuffer = AllocSendBuffer();
7521 #endif /* HAVE_PIOV */
7522     /* if length == 0, the loop below isn't going to do anything, including
7523      * extend the length of the inode, which it must do, since the file system
7524      * assumes that the inode length == vnode's file length.  So, we extend
7525      * the file length manually if need be.  Note that if file is bigger than
7526      * Pos+(Length==0), we dont' have to do anything, and certainly shouldn't
7527      * do what we're going to do below.
7528      */
7529     if (Length == 0 && Pos > TruncatedLength) {
7530         /* Set the file's length; we've already done an lseek to the right
7531          * spot above.
7532          */
7533         nBytes = FDH_PWRITE(fdP, &tlen, 1, Pos);
7534         if (nBytes != 1) {
7535             errorCode = -1;
7536             goto done;
7537         }
7538         errorCode = FDH_TRUNC(fdP, Pos);
7539     } else {
7540         /* have some data to copy */
7541 #if FS_STATS_DETAILED
7542         (*a_bytesToStoreP) = Length;
7543 #endif /* FS_STATS_DETAILED */
7544         while (1) {
7545             int rlen;
7546             if (bytesTransfered >= Length) {
7547                 errorCode = 0;
7548                 break;
7549             }
7550             tlen = Length - bytesTransfered;    /* how much more to do */
7551             if (tlen > optSize)
7552                 rlen = optSize; /* bound by buffer size */
7553             else
7554                 rlen = (int)tlen;
7555 #ifndef HAVE_PIOV
7556             errorCode = rx_Read(Call, tbuffer, rlen);
7557 #else /* HAVE_PIOV */
7558             errorCode = rx_Readv(Call, tiov, &tnio, RX_MAXIOVECS, rlen);
7559 #endif /* HAVE_PIOV */
7560             if (errorCode <= 0) {
7561                 errorCode = -32;
7562                 break;
7563             }
7564 #if FS_STATS_DETAILED
7565             (*a_bytesStoredP) += errorCode;
7566 #endif /* FS_STATS_DETAILED */
7567             rlen = errorCode;
7568 #ifndef HAVE_PIOV
7569             nBytes = FDH_PWRITE(fdP, tbuffer, rlen, Pos);
7570 #else /* HAVE_PIOV */
7571             nBytes = FDH_PWRITEV(fdP, tiov, tnio, Pos);
7572 #endif /* HAVE_PIOV */
7573             if (nBytes != rlen) {
7574                 errorCode = VDISKFULL;
7575                 break;
7576             }
7577             bytesTransfered += rlen;
7578             Pos += rlen;
7579         }
7580     }
7581   done:
7582 #ifndef HAVE_PIOV
7583     FreeSendBuffer((struct afs_buffer *)tbuffer);
7584 #endif /* HAVE_PIOV */
7585     if (sync) {
7586         FDH_SYNC(fdP);
7587     }
7588     if (errorCode) {
7589         afs_sfsize_t nfSize = FDH_SIZE(fdP);
7590         osi_Assert(nfSize >= 0);
7591         /* something went wrong: adjust size and return */
7592         VN_SET_LEN(targetptr, nfSize);  /* set new file size. */
7593         /* changed_newTime is tested in StoreData to detemine if we
7594          * need to update the target vnode.
7595          */
7596         targetptr->changed_newTime = 1;
7597         if (origfdP && (bytesTransfered < Length))      /* Need to "finish" CopyOnWrite still */
7598             CopyOnWrite2(origfdP, fdP, Pos + bytesTransfered, NewLength - Pos - bytesTransfered);
7599         if (origfdP) FDH_REALLYCLOSE(origfdP);
7600         FDH_CLOSE(fdP);
7601         /* set disk usage to be correct */
7602         VAdjustDiskUsage(&errorCode, volptr,
7603                          (afs_sfsize_t) (nBlocks(nfSize) -
7604                                          nBlocks(NewLength)), 0);
7605         return errorCode;
7606     }
7607     if (origfdP) {                                      /* finish CopyOnWrite */
7608         if ( (CoW_off = Pos + Length) < NewLength) {
7609             errorCode = CopyOnWrite2(origfdP, fdP, CoW_off, CoW_len = NewLength - CoW_off);
7610             ViceLog(1, ("StoreData : CopyOnWrite2 on vnode %u.%u (%s) "
7611                         "off 0x%llx size 0x%llx returns %d\n",
7612                         afs_printable_VolumeId_u(V_id(volptr)),
7613                         afs_printable_VnodeId_u(targetptr->vnodeNumber),
7614                         V_name(volptr), CoW_off, CoW_len, errorCode));
7615         }
7616         FDH_REALLYCLOSE(origfdP);
7617     }
7618     FDH_CLOSE(fdP);
7619
7620     FT_GetTimeOfDay(&StopTime, 0);
7621
7622     VN_SET_LEN(targetptr, NewLength);
7623
7624     /* Update all StoreData related stats */
7625     FS_LOCK;
7626     if (AFSCallStats.TotalStoredBytes > 2000000000)     /* reset if over 2 billion */
7627         AFSCallStats.TotalStoredBytes = AFSCallStats.AccumStoreTime = 0;
7628     AFSCallStats.StoreSize1++;  /* Piggybacked data */
7629     {
7630         afs_fsize_t targLen;
7631         VN_GET_LEN(targLen, targetptr);
7632         if (targLen < SIZE2)
7633             AFSCallStats.StoreSize2++;
7634         else if (targLen < SIZE3)
7635             AFSCallStats.StoreSize3++;
7636         else if (targLen < SIZE4)
7637             AFSCallStats.StoreSize4++;
7638         else
7639             AFSCallStats.StoreSize5++;
7640     }
7641     FS_UNLOCK;
7642     return (errorCode);
7643
7644 }                               /*StoreData_RXStyle */
7645
7646 static int sys2et[512];
7647
7648 void
7649 init_sys_error_to_et(void)
7650 {
7651     memset(&sys2et, 0, sizeof(sys2et));
7652     sys2et[EPERM] = UAEPERM;
7653     sys2et[ENOENT] = UAENOENT;
7654     sys2et[ESRCH] = UAESRCH;
7655     sys2et[EINTR] = UAEINTR;
7656     sys2et[EIO] = UAEIO;
7657     sys2et[ENXIO] = UAENXIO;
7658     sys2et[E2BIG] = UAE2BIG;
7659     sys2et[ENOEXEC] = UAENOEXEC;
7660     sys2et[EBADF] = UAEBADF;
7661     sys2et[ECHILD] = UAECHILD;
7662     sys2et[EAGAIN] = UAEAGAIN;
7663     sys2et[ENOMEM] = UAENOMEM;
7664     sys2et[EACCES] = UAEACCES;
7665     sys2et[EFAULT] = UAEFAULT;
7666     sys2et[ENOTBLK] = UAENOTBLK;
7667     sys2et[EBUSY] = UAEBUSY;
7668     sys2et[EEXIST] = UAEEXIST;
7669     sys2et[EXDEV] = UAEXDEV;
7670     sys2et[ENODEV] = UAENODEV;
7671     sys2et[ENOTDIR] = UAENOTDIR;
7672     sys2et[EISDIR] = UAEISDIR;
7673     sys2et[EINVAL] = UAEINVAL;
7674     sys2et[ENFILE] = UAENFILE;
7675     sys2et[EMFILE] = UAEMFILE;
7676     sys2et[ENOTTY] = UAENOTTY;
7677     sys2et[ETXTBSY] = UAETXTBSY;
7678     sys2et[EFBIG] = UAEFBIG;
7679     sys2et[ENOSPC] = UAENOSPC;
7680     sys2et[ESPIPE] = UAESPIPE;
7681     sys2et[EROFS] = UAEROFS;
7682     sys2et[EMLINK] = UAEMLINK;
7683     sys2et[EPIPE] = UAEPIPE;
7684     sys2et[EDOM] = UAEDOM;
7685     sys2et[ERANGE] = UAERANGE;
7686     sys2et[EDEADLK] = UAEDEADLK;
7687     sys2et[ENAMETOOLONG] = UAENAMETOOLONG;
7688     sys2et[ENOLCK] = UAENOLCK;
7689     sys2et[ENOSYS] = UAENOSYS;
7690 #if (ENOTEMPTY != EEXIST)
7691     sys2et[ENOTEMPTY] = UAENOTEMPTY;
7692 #endif
7693     sys2et[ELOOP] = UAELOOP;
7694 #if (EWOULDBLOCK != EAGAIN)
7695     sys2et[EWOULDBLOCK] = UAEWOULDBLOCK;
7696 #endif
7697     sys2et[ENOMSG] = UAENOMSG;
7698     sys2et[EIDRM] = UAEIDRM;
7699     sys2et[ECHRNG] = UAECHRNG;
7700     sys2et[EL2NSYNC] = UAEL2NSYNC;
7701     sys2et[EL3HLT] = UAEL3HLT;
7702     sys2et[EL3RST] = UAEL3RST;
7703     sys2et[ELNRNG] = UAELNRNG;
7704     sys2et[EUNATCH] = UAEUNATCH;
7705     sys2et[ENOCSI] = UAENOCSI;
7706     sys2et[EL2HLT] = UAEL2HLT;
7707     sys2et[EBADE] = UAEBADE;
7708     sys2et[EBADR] = UAEBADR;
7709     sys2et[EXFULL] = UAEXFULL;
7710     sys2et[ENOANO] = UAENOANO;
7711     sys2et[EBADRQC] = UAEBADRQC;
7712     sys2et[EBADSLT] = UAEBADSLT;
7713     sys2et[EDEADLK] = UAEDEADLK;
7714     sys2et[EBFONT] = UAEBFONT;
7715     sys2et[ENOSTR] = UAENOSTR;
7716     sys2et[ENODATA] = UAENODATA;
7717     sys2et[ETIME] = UAETIME;
7718     sys2et[ENOSR] = UAENOSR;
7719     sys2et[ENONET] = UAENONET;
7720     sys2et[ENOPKG] = UAENOPKG;
7721     sys2et[EREMOTE] = UAEREMOTE;
7722     sys2et[ENOLINK] = UAENOLINK;
7723     sys2et[EADV] = UAEADV;
7724     sys2et[ESRMNT] = UAESRMNT;
7725     sys2et[ECOMM] = UAECOMM;
7726     sys2et[EPROTO] = UAEPROTO;
7727     sys2et[EMULTIHOP] = UAEMULTIHOP;
7728     sys2et[EDOTDOT] = UAEDOTDOT;
7729     sys2et[EBADMSG] = UAEBADMSG;
7730     sys2et[EOVERFLOW] = UAEOVERFLOW;
7731     sys2et[ENOTUNIQ] = UAENOTUNIQ;
7732     sys2et[EBADFD] = UAEBADFD;
7733     sys2et[EREMCHG] = UAEREMCHG;
7734     sys2et[ELIBACC] = UAELIBACC;
7735     sys2et[ELIBBAD] = UAELIBBAD;
7736     sys2et[ELIBSCN] = UAELIBSCN;
7737     sys2et[ELIBMAX] = UAELIBMAX;
7738     sys2et[ELIBEXEC] = UAELIBEXEC;
7739     sys2et[EILSEQ] = UAEILSEQ;
7740     sys2et[ERESTART] = UAERESTART;
7741     sys2et[ESTRPIPE] = UAESTRPIPE;
7742     sys2et[EUSERS] = UAEUSERS;
7743     sys2et[ENOTSOCK] = UAENOTSOCK;
7744     sys2et[EDESTADDRREQ] = UAEDESTADDRREQ;
7745     sys2et[EMSGSIZE] = UAEMSGSIZE;
7746     sys2et[EPROTOTYPE] = UAEPROTOTYPE;
7747     sys2et[ENOPROTOOPT] = UAENOPROTOOPT;
7748     sys2et[EPROTONOSUPPORT] = UAEPROTONOSUPPORT;
7749     sys2et[ESOCKTNOSUPPORT] = UAESOCKTNOSUPPORT;
7750     sys2et[EOPNOTSUPP] = UAEOPNOTSUPP;
7751     sys2et[EPFNOSUPPORT] = UAEPFNOSUPPORT;
7752     sys2et[EAFNOSUPPORT] = UAEAFNOSUPPORT;
7753     sys2et[EADDRINUSE] = UAEADDRINUSE;
7754     sys2et[EADDRNOTAVAIL] = UAEADDRNOTAVAIL;
7755     sys2et[ENETDOWN] = UAENETDOWN;
7756     sys2et[ENETUNREACH] = UAENETUNREACH;
7757     sys2et[ENETRESET] = UAENETRESET;
7758     sys2et[ECONNABORTED] = UAECONNABORTED;
7759     sys2et[ECONNRESET] = UAECONNRESET;
7760     sys2et[ENOBUFS] = UAENOBUFS;
7761     sys2et[EISCONN] = UAEISCONN;
7762     sys2et[ENOTCONN] = UAENOTCONN;
7763     sys2et[ESHUTDOWN] = UAESHUTDOWN;
7764     sys2et[ETOOMANYREFS] = UAETOOMANYREFS;
7765     sys2et[ETIMEDOUT] = UAETIMEDOUT;
7766     sys2et[ECONNREFUSED] = UAECONNREFUSED;
7767     sys2et[EHOSTDOWN] = UAEHOSTDOWN;
7768     sys2et[EHOSTUNREACH] = UAEHOSTUNREACH;
7769     sys2et[EALREADY] = UAEALREADY;
7770     sys2et[EINPROGRESS] = UAEINPROGRESS;
7771     sys2et[ESTALE] = UAESTALE;
7772     sys2et[EUCLEAN] = UAEUCLEAN;
7773     sys2et[ENOTNAM] = UAENOTNAM;
7774     sys2et[ENAVAIL] = UAENAVAIL;
7775     sys2et[EISNAM] = UAEISNAM;
7776     sys2et[EREMOTEIO] = UAEREMOTEIO;
7777     sys2et[EDQUOT] = UAEDQUOT;
7778     sys2et[ENOMEDIUM] = UAENOMEDIUM;
7779     sys2et[EMEDIUMTYPE] = UAEMEDIUMTYPE;
7780
7781     sys2et[EIO] = UAEIO;
7782 }
7783
7784 /* NOTE:  2006-03-01
7785  *  SRXAFS_CallBackRxConnAddr should be re-written as follows:
7786  *  - pass back the connection, client, and host from CallPreamble
7787  *  - keep a ref on the client, which we don't now
7788  *  - keep a hold on the host, which we already do
7789  *  - pass the connection, client, and host down into SAFSS_*, and use
7790  *    them instead of independently discovering them via rx_ConnectionOf
7791  *    (safe) and rx_GetSpecific (not so safe)
7792  *  The idea being that we decide what client and host we're going to use
7793  *  when CallPreamble is called, and stay consistent throughout the call.
7794  *  This change is too invasive for 1.4.1 but should be made in 1.5.x.
7795  */
7796
7797 afs_int32
7798 SRXAFS_CallBackRxConnAddr (struct rx_call * acall, afs_int32 *addr)
7799 {
7800     Error errorCode = 0;
7801     struct rx_connection *tcon;
7802     struct host *tcallhost;
7803 #ifdef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7804     struct host *thost;
7805     struct client *tclient;
7806     static struct rx_securityClass *sc = 0;
7807     int i,j;
7808     struct rx_connection *conn;
7809 #endif
7810
7811     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &tcallhost)))
7812             goto Bad_CallBackRxConnAddr1;
7813
7814 #ifndef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7815     errorCode = 1;
7816 #else
7817     H_LOCK;
7818     tclient = h_FindClient_r(tcon);
7819     if (!tclient) {
7820         errorCode = VBUSY;
7821         goto Bad_CallBackRxConnAddr;
7822     }
7823     thost = tclient->host;
7824
7825     /* nothing more can be done */
7826     if ( !thost->interface )
7827         goto Bad_CallBackRxConnAddr;
7828
7829     /* the only address is the primary interface */
7830     /* can't change when there's only 1 address, anyway */
7831     if ( thost->interface->numberOfInterfaces <= 1 )
7832         goto Bad_CallBackRxConnAddr;
7833
7834     /* initialise a security object only once */
7835     if ( !sc )
7836         sc = (struct rx_securityClass *) rxnull_NewClientSecurityObject();
7837
7838     for ( i=0; i < thost->interface->numberOfInterfaces; i++)
7839     {
7840             if ( *addr == thost->interface->addr[i] ) {
7841                     break;
7842             }
7843     }
7844
7845     if ( *addr != thost->interface->addr[i] )
7846         goto Bad_CallBackRxConnAddr;
7847
7848     conn = rx_NewConnection (thost->interface->addr[i],
7849                              thost->port, 1, sc, 0);
7850     rx_SetConnDeadTime(conn, 2);
7851     rx_SetConnHardDeadTime(conn, AFS_HARDDEADTIME);
7852     H_UNLOCK;
7853     errorCode = RXAFSCB_Probe(conn);
7854     H_LOCK;
7855     if (!errorCode) {
7856         if ( thost->callback_rxcon )
7857             rx_DestroyConnection(thost->callback_rxcon);
7858         thost->callback_rxcon = conn;
7859         thost->host           = addr;
7860         rx_SetConnDeadTime(thost->callback_rxcon, 50);
7861         rx_SetConnHardDeadTime(thost->callback_rxcon, AFS_HARDDEADTIME);
7862         h_ReleaseClient_r(tclient);
7863         /* The hold on thost will be released by CallPostamble */
7864         H_UNLOCK;
7865         errorCode = CallPostamble(tcon, errorCode, tcallhost);
7866         return errorCode;
7867     } else {
7868         rx_DestroyConnection(conn);
7869     }
7870   Bad_CallBackRxConnAddr:
7871     h_ReleaseClient_r(tclient);
7872     /* The hold on thost will be released by CallPostamble */
7873     H_UNLOCK;
7874 #endif
7875
7876     errorCode = CallPostamble(tcon, errorCode, tcallhost);
7877  Bad_CallBackRxConnAddr1:
7878     return errorCode;          /* failure */
7879 }
7880
7881 afs_int32
7882 sys_error_to_et(afs_int32 in)
7883 {
7884     if (in == 0)
7885         return 0;
7886     if (in < 0 || in > 511)
7887         return in;
7888     if ((in >= VICE_SPECIAL_ERRORS && in <= VIO) || in == VRESTRICTED)
7889         return in;
7890     if (sys2et[in] != 0)
7891         return sys2et[in];
7892     return in;
7893 }