viced-avoid-tying-up-all-threads-20070730
[openafs.git] / src / viced / afsfileprocs.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*  afs_fileprocs.c - Complete File Server request routines              */
11 /*                                                                       */
12 /*  Information Technology Center                                        */
13 /*  Carnegie Mellon University                                           */
14 /*                                                                       */
15 /*  Date: 8/10/88                                                        */
16 /*                                                                       */
17 /*  Function    - A set of routines to handle the various file Server    */
18 /*                  requests; these routines are invoked by rxgen.       */
19 /*                                                                       */
20 /* ********************************************************************** */
21
22 /* 
23  * in Check_PermissionRights, certain privileges are afforded to the owner 
24  * of the volume, or the owner of a file.  Are these considered "use of 
25  * privilege"? 
26  */
27
28 #include <afsconfig.h>
29 #include <afs/param.h>
30
31 RCSID
32     ("$Header$");
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37 #ifdef  AFS_SGI_ENV
38 #undef SHARED                   /* XXX */
39 #endif
40 #ifdef AFS_NT40_ENV
41 #include <fcntl.h>
42 #else
43 #include <sys/param.h>
44 #include <sys/file.h>
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <netdb.h>
50
51 #ifdef HAVE_STRING_H
52 #include <string.h>
53 #else
54 #ifdef HAVE_STRINGS_H
55 #include <strings.h>
56 #endif
57 #endif
58
59 #ifndef AFS_LINUX20_ENV
60 #include <net/if.h>
61 #include <netinet/if_ether.h>
62 #endif
63 #endif
64 #ifdef AFS_HPUX_ENV
65 /* included early because of name conflict on IOPEN */
66 #include <sys/inode.h>
67 #ifdef IOPEN
68 #undef IOPEN
69 #endif
70 #endif /* AFS_HPUX_ENV */
71 #include <afs/stds.h>
72 #include <rx/xdr.h>
73 #include <afs/nfs.h>
74 #include <afs/assert.h>
75 #include <lwp.h>
76 #include <lock.h>
77 #include <afs/afsint.h>
78 #include <afs/vldbint.h>
79 #include <afs/errors.h>
80 #include <afs/ihandle.h>
81 #include <afs/vnode.h>
82 #include <afs/volume.h>
83 #include <afs/ptclient.h>
84 #include <afs/ptuser.h>
85 #include <afs/prs_fs.h>
86 #include <afs/acl.h>
87 #include <rx/rx.h>
88 #include <rx/rx_globals.h>
89 #include <sys/stat.h>
90 #if ! defined(AFS_SGI_ENV) && ! defined(AFS_AIX32_ENV) && ! defined(AFS_NT40_ENV) && ! defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
91 #include <sys/map.h>
92 #endif
93 #if !defined(AFS_NT40_ENV)
94 #include <unistd.h>
95 #endif
96 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
97 #ifdef  AFS_AIX_ENV
98 #include <sys/statfs.h>
99 #include <sys/lockf.h>
100 #else
101 #if !defined(AFS_SUN5_ENV) && !defined(AFS_LINUX20_ENV) && !defined(AFS_DARWIN_ENV) && !defined(AFS_XBSD_ENV)
102 #include <sys/dk.h>
103 #endif
104 #endif
105 #endif
106 #include <afs/cellconfig.h>
107 #include <afs/keys.h>
108
109 #include <signal.h>
110 #include <afs/partition.h>
111 #include "viced_prototypes.h"
112 #include "viced.h"
113 #include "host.h"
114 #include "callback.h"
115 #include <afs/unified_afs.h>
116 #include <afs/audit.h>
117 #include <afs/afsutil.h>
118 #include <afs/dir.h>
119
120 extern void SetDirHandle(register DirHandle * dir, register Vnode * vnode);
121 extern void FidZap(DirHandle * file);
122 extern void FidZero(DirHandle * file);
123
124 #ifdef AFS_PTHREAD_ENV
125 pthread_mutex_t fileproc_glock_mutex;
126 #endif /* AFS_PTHREAD_ENV */
127
128 #ifdef O_LARGEFILE
129 #define afs_stat        stat64
130 #define afs_fstat       fstat64
131 #define afs_open        open64
132 #else /* !O_LARGEFILE */
133 #define afs_stat        stat
134 #define afs_fstat       fstat
135 #define afs_open        open
136 #endif /* !O_LARGEFILE */
137
138
139 /* Useful local defines used by this module */
140
141 #define DONTCHECK       0
142 #define MustNOTBeDIR    1
143 #define MustBeDIR       2
144
145 #define TVS_SDATA       1
146 #define TVS_SSTATUS     2
147 #define TVS_CFILE       4
148 #define TVS_SLINK       8
149 #define TVS_MKDIR       0x10
150
151 #define CHK_FETCH       0x10
152 #define CHK_FETCHDATA   0x10
153 #define CHK_FETCHACL    0x11
154 #define CHK_FETCHSTATUS 0x12
155 #define CHK_STOREDATA   0x00
156 #define CHK_STOREACL    0x01
157 #define CHK_STORESTATUS 0x02
158
159 #define OWNERREAD       0400
160 #define OWNERWRITE      0200
161 #define OWNEREXEC       0100
162 #ifdef USE_GROUP_PERMS
163 #define GROUPREAD       0040
164 #define GROUPWRITE      0020
165 #define GROUPREXEC      0010
166 #endif
167
168 /* The following errors were not defined in NT. They are given unique
169  * names here to avoid any potential collision.
170  */
171 #define FSERR_ELOOP              90
172 #define FSERR_EOPNOTSUPP        122
173 #define FSERR_ECONNREFUSED      130
174
175 #define NOTACTIVECALL   0
176 #define ACTIVECALL      1
177
178 #define CREATE_SGUID_ADMIN_ONLY 1
179
180 extern struct afsconf_dir *confDir;
181 extern afs_int32 dataVersionHigh;
182
183 extern int SystemId;
184 static struct AFSCallStatistics AFSCallStats;
185 #if FS_STATS_DETAILED
186 struct fs_stats_FullPerfStats afs_FullPerfStats;
187 extern int AnonymousID;
188 #endif /* FS_STATS_DETAILED */
189 #if OPENAFS_VOL_STATS
190 static const char nullString[] = "";
191 #endif /* OPENAFS_VOL_STATS */
192
193 struct afs_FSStats {
194     afs_int32 NothingYet;
195 };
196
197 struct afs_FSStats afs_fsstats;
198
199 void ResetDebug(), SetDebug(), Terminate();
200
201 int LogLevel = 0;
202 int supported = 1;
203 int Console = 0;
204 afs_int32 BlocksSpare = 1024;   /* allow 1 MB overruns */
205 afs_int32 PctSpare;
206 extern afs_int32 implicitAdminRights;
207 extern afs_int32 readonlyServer;
208
209 /*
210  * Externals used by the xstat code.
211  */
212 extern VolPkgStats VStats;
213 extern int CEs, CEBlocks;
214
215 extern int HTs, HTBlocks;
216
217 afs_int32 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
218                             register struct rx_call *Call, afs_sfsize_t Pos,
219                             afs_sfsize_t Len, afs_int32 Int64Mode,
220 #if FS_STATS_DETAILED
221                             afs_sfsize_t * a_bytesToFetchP,
222                             afs_sfsize_t * a_bytesFetchedP
223 #endif                          /* FS_STATS_DETAILED */
224     );
225
226 afs_int32 StoreData_RXStyle(Volume * volptr, Vnode * targetptr,
227                             struct AFSFid *Fid, struct client *client,
228                             register struct rx_call *Call, afs_fsize_t Pos,
229                             afs_fsize_t Length, afs_fsize_t FileLength,
230                             int sync,
231 #if FS_STATS_DETAILED
232                             afs_sfsize_t * a_bytesToStoreP,
233                             afs_sfsize_t * a_bytesStoredP
234 #endif                          /* FS_STATS_DETAILED */
235     );
236
237 #ifdef AFS_SGI_XFS_IOPS_ENV
238 #include <afs/xfsattrs.h>
239 static int
240 GetLinkCount(Volume * avp, struct stat *astat)
241 {
242     if (!strcmp("xfs", astat->st_fstype)) {
243         return (astat->st_mode & AFS_XFS_MODE_LINK_MASK);
244     } else
245         return astat->st_nlink;
246 }
247 #else
248 #define GetLinkCount(V, S) (S)->st_nlink
249 #endif
250
251 afs_int32
252 SpareComp(Volume * avolp)
253 {
254     register afs_int32 temp;
255
256     FS_LOCK;
257     if (PctSpare) {
258         temp = V_maxquota(avolp);
259         if (temp == 0) {
260             /* no matter; doesn't check in this case */
261             FS_UNLOCK;
262             return 0;
263         }
264         temp = (temp * PctSpare) / 100;
265         FS_UNLOCK;
266         return temp;
267     } else {
268         FS_UNLOCK;
269         return BlocksSpare;
270     }
271
272 }                               /*SpareComp */
273
274 /*
275  * Set the volume synchronization parameter for this volume.  If it changes,
276  * the Cache Manager knows that the volume must be purged from the stat cache.
277  */
278 static void
279 SetVolumeSync(register struct AFSVolSync *async, register Volume * avol)
280 {
281     FS_LOCK;
282     /* date volume instance was created */
283     if (async) {
284         if (avol)
285             async->spare1 = avol->header->diskstuff.creationDate;
286         else
287             async->spare1 = 0;
288         async->spare2 = 0;
289         async->spare3 = 0;
290         async->spare4 = 0;
291         async->spare5 = 0;
292         async->spare6 = 0;
293     }
294     FS_UNLOCK;
295 }                               /*SetVolumeSync */
296
297 /*
298  * Note that this function always returns a held host, so
299  * that CallPostamble can block without the host's disappearing.
300  * Call returns rx connection in passed in *tconn
301  */
302 static int
303 CallPreamble(register struct rx_call *acall, int activecall,
304              struct rx_connection **tconn, struct host **ahostp)
305 {
306     struct host *thost;
307     struct client *tclient;
308     int retry_flag = 1;
309     int code = 0;
310     char hoststr[16], hoststr2[16];
311     struct ubik_client *uclient;
312
313     *ahostp = NULL;
314
315     if (!tconn) {
316         ViceLog(0, ("CallPreamble: unexpected null tconn!\n"));
317         return -1;
318     }
319     *tconn = rx_ConnectionOf(acall);
320
321     H_LOCK;
322   retry:
323     tclient = h_FindClient_r(*tconn);
324     if (!tclient) {
325         ViceLog(0, ("CallPreamble: Couldn't get CPS. Too many lockers\n"));
326         H_UNLOCK;
327         return VBUSY;
328     }
329     thost = tclient->host;
330     if (tclient->prfail == 1) { /* couldn't get the CPS */
331         if (!retry_flag) {
332             h_ReleaseClient_r(tclient);
333             h_Release_r(thost);
334             ViceLog(0, ("CallPreamble: Couldn't get CPS. Fail\n"));
335             H_UNLOCK;
336             return -1001;
337         }
338         retry_flag = 0;         /* Retry once */
339
340         /* Take down the old connection and re-read the key file */
341         ViceLog(0,
342                 ("CallPreamble: Couldn't get CPS. Reconnect to ptserver\n"));
343 #ifdef AFS_PTHREAD_ENV
344         uclient = (struct ubik_client *)pthread_getspecific(viced_uclient_key);
345
346         /* Is it still necessary to drop this? We hit the net, we should... */
347         H_UNLOCK;
348         if (uclient) 
349             hpr_End(uclient);
350         code = hpr_Initialize(&uclient);
351
352         assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
353         H_LOCK;
354 #else
355         code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
356 #endif
357         if (code) {
358             h_ReleaseClient_r(tclient);
359             h_Release_r(thost);
360             H_UNLOCK;
361             ViceLog(0, ("CallPreamble: couldn't reconnect to ptserver\n"));
362             return -1001;
363         }
364
365         tclient->prfail = 2;    /* Means re-eval client's cps */
366         h_ReleaseClient_r(tclient);
367         h_Release_r(thost);
368         goto retry;
369     }
370
371     tclient->LastCall = thost->LastCall = FT_ApproxTime();
372     if (activecall)             /* For all but "GetTime", "GetStats", and "GetCaps" calls */
373         thost->ActiveCall = thost->LastCall;
374
375     h_Lock_r(thost);
376     if (thost->hostFlags & HOSTDELETED) {
377         ViceLog(3,
378                 ("Discarded a packet for deleted host %s:%d\n",
379                  afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port)));
380         code = VBUSY;           /* raced, so retry */
381     } else if ((thost->hostFlags & VENUSDOWN)
382                || (thost->hostFlags & HFE_LATER)) {
383         if (BreakDelayedCallBacks_r(thost)) {
384             ViceLog(0,
385                     ("BreakDelayedCallbacks FAILED for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
386                      afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2), 
387                      ntohs(rxr_PortOf(*tconn))));
388             if (MultiProbeAlternateAddress_r(thost)) {
389                 ViceLog(0,
390                         ("MultiProbe failed to find new address for host %s:%d\n",
391                          afs_inet_ntoa_r(thost->host, hoststr),
392                          ntohs(thost->port)));
393                 code = -1;
394             } else {
395                 ViceLog(0,
396                         ("MultiProbe found new address for host %s:%d\n",
397                          afs_inet_ntoa_r(thost->host, hoststr),
398                          ntohs(thost->port)));
399                 if (BreakDelayedCallBacks_r(thost)) {
400                     ViceLog(0,
401                             ("BreakDelayedCallbacks FAILED AGAIN for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
402                               afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2), 
403                               ntohs(rxr_PortOf(*tconn))));
404                     code = -1;
405                 }
406             }
407         }
408     } else {
409         code = 0;
410     }
411
412     h_ReleaseClient_r(tclient);
413     h_Unlock_r(thost);
414     H_UNLOCK;
415     *ahostp = thost;
416     return code;
417
418 }                               /*CallPreamble */
419
420
421 static afs_int32
422 CallPostamble(register struct rx_connection *aconn, afs_int32 ret,
423               struct host *ahost)
424 {
425     struct host *thost;
426     struct client *tclient;
427     int translate = 0;
428     int held;
429
430     H_LOCK;
431     tclient = h_FindClient_r(aconn);
432     if (!tclient) 
433         goto busyout;
434     thost = tclient->host;
435     if (thost->hostFlags & HERRORTRANS)
436         translate = 1;
437     h_ReleaseClient_r(tclient);
438     held = h_Held_r(thost);
439     if (held)
440         h_Release_r(thost);
441     if (ahost && ahost != thost) {
442         char hoststr[16], hoststr2[16]; 
443         ViceLog(0, ("CallPostamble: ahost %s:%d (%x) != thost %s:%d (%x)\n",
444                 afs_inet_ntoa_r(ahost->host, hoststr), ntohs(ahost->port),
445                 ahost, 
446                 afs_inet_ntoa_r(thost->host, hoststr2), ntohs(thost->port),
447                 thost));
448         h_Release_r(ahost);
449     } else if (!ahost) {
450         char hoststr[16];       
451         ViceLog(0, ("CallPostamble: null ahost for thost %s:%d (%x)\n",
452                 afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port),
453                 thost));
454     }
455  busyout:
456     H_UNLOCK;
457     return (translate ? sys_error_to_et(ret) : ret);
458 }                               /*CallPostamble */
459
460 /*
461  * Returns the volume and vnode pointers associated with file Fid; the lock
462  * type on the vnode is set to lock. Note that both volume/vnode's ref counts
463  * are incremented and they must be eventualy released.
464  */
465 static afs_int32
466 CheckVnode(AFSFid * fid, Volume ** volptr, Vnode ** vptr, int lock)
467 {
468     int fileCode = 0;
469     afs_int32 local_errorCode, errorCode = -1;
470     static struct timeval restartedat = { 0, 0 };
471
472     if (fid->Volume == 0 || fid->Vnode == 0)    /* not: || fid->Unique == 0) */
473         return (EINVAL);
474     if ((*volptr) == 0) {
475         extern int VInit;
476
477         while (1) {
478             errorCode = 0;
479             *volptr = VGetVolume(&local_errorCode, &errorCode, (afs_int32) fid->Volume);
480             if (!errorCode) {
481                 assert(*volptr);
482                 break;
483             }
484             if ((errorCode == VOFFLINE) && (VInit < 2)) {
485                 /* The volume we want may not be attached yet because
486                  * the volume initialization is not yet complete.
487                  * We can do several things: 
488                  *     1.  return -1, which will cause users to see
489                  *         "connection timed out".  This is more or
490                  *         less the same as always, except that the servers
491                  *         may appear to bounce up and down while they
492                  *         are actually restarting.
493                  *     2.  return VBUSY which will cause clients to 
494                  *         sleep and retry for 6.5 - 15 minutes, depending
495                  *         on what version of the CM they are running.  If
496                  *         the file server takes longer than that interval 
497                  *         to attach the desired volume, then the application
498                  *         will see an ENODEV or EIO.  This approach has 
499                  *         the advantage that volumes which have been attached
500                  *         are immediately available, it keeps the server's
501                  *         immediate backlog low, and the call is interruptible
502                  *         by the user.  Users see "waiting for busy volume."
503                  *     3.  sleep here and retry.  Some people like this approach
504                  *         because there is no danger of seeing errors.  However, 
505                  *         this approach only works with a bounded number of 
506                  *         clients, since the pending queues will grow without
507                  *         stopping.  It might be better to find a way to take
508                  *         this call and stick it back on a queue in order to
509                  *         recycle this thread for a different request.    
510                  *     4.  Return a new error code, which new cache managers will
511                  *         know enough to interpret as "sleep and retry", without
512                  *         the upper bound of 6-15 minutes that is imposed by the
513                  *         VBUSY handling.  Users will see "waiting for
514                  *         busy volume," so they know that something is
515                  *         happening.  Old cache managers must be able to do  
516                  *         something reasonable with this, for instance, mark the
517                  *         server down.  Fortunately, any error code < 0
518                  *         will elicit that behavior. See #1.
519                  *     5.  Some combination of the above.  I like doing #2 for 10
520                  *         minutes, followed by #4.  3.1b and 3.2 cache managers
521                  *         will be fine as long as the restart period is
522                  *         not longer than 6.5 minutes, otherwise they may
523                  *         return ENODEV to users.  3.3 cache managers will be
524                  *         fine for 10 minutes, then will return
525                  *         ETIMEDOUT.  3.4 cache managers will just wait
526                  *         until the call works or fails definitively.
527                  *  NB. The problem with 2,3,4,5 is that old clients won't
528                  *  fail over to an alternate read-only replica while this
529                  *  server is restarting.  3.4 clients will fail over right away.
530                  */
531                 if (restartedat.tv_sec == 0) {
532                     /* I'm not really worried about when we restarted, I'm   */
533                     /* just worried about when the first VBUSY was returned. */
534                     TM_GetTimeOfDay(&restartedat, 0);
535                     if (busyonrst) {
536                         FS_LOCK;
537                         afs_perfstats.fs_nBusies++;
538                         FS_UNLOCK;
539                     }
540                     return (busyonrst ? VBUSY : VRESTARTING);
541                 } else {
542                     struct timeval now;
543                     TM_GetTimeOfDay(&now, 0);
544                     if ((now.tv_sec - restartedat.tv_sec) < (11 * 60)) {
545                         if (busyonrst) {
546                             FS_LOCK;
547                             afs_perfstats.fs_nBusies++;
548                             FS_UNLOCK;
549                         }
550                         return (busyonrst ? VBUSY : VRESTARTING);
551                     } else {
552                         return (VRESTARTING);
553                     }
554                 }
555             }
556             /* allow read operations on busy volume. 
557              * must check local_errorCode because demand attach fs
558              * can have local_errorCode == VSALVAGING, errorCode == VBUSY */
559             else if (local_errorCode == VBUSY && lock == READ_LOCK) {
560                 errorCode = 0;
561                 break;
562             } else if (errorCode)
563                 return (errorCode);
564         }
565     }
566     assert(*volptr);
567
568     /* get the vnode  */
569     *vptr = VGetVnode(&errorCode, *volptr, fid->Vnode, lock);
570     if (errorCode)
571         return (errorCode);
572     if ((*vptr)->disk.uniquifier != fid->Unique) {
573         VPutVnode(&fileCode, *vptr);
574         assert(fileCode == 0);
575         *vptr = 0;
576         return (VNOVNODE);      /* return the right error code, at least */
577     }
578     return (0);
579 }                               /*CheckVnode */
580
581 /*
582  * This routine returns the ACL associated with the targetptr. If the
583  * targetptr isn't a directory, we access its parent dir and get the ACL
584  * thru the parent; in such case the parent's vnode is returned in
585  * READ_LOCK mode.
586  */
587 static afs_int32
588 SetAccessList(Vnode ** targetptr, Volume ** volume,
589               struct acl_accessList **ACL, int *ACLSize, Vnode ** parent,
590               AFSFid * Fid, int Lock)
591 {
592     if ((*targetptr)->disk.type == vDirectory) {
593         *parent = 0;
594         *ACL = VVnodeACL(*targetptr);
595         *ACLSize = VAclSize(*targetptr);
596         return (0);
597     } else {
598         assert(Fid != 0);
599         while (1) {
600             VnodeId parentvnode;
601             int errorCode = 0;
602
603             parentvnode = (*targetptr)->disk.parent;
604             VPutVnode(&errorCode, *targetptr);
605             *targetptr = 0;
606             if (errorCode)
607                 return (errorCode);
608             *parent = VGetVnode(&errorCode, *volume, parentvnode, READ_LOCK);
609             if (errorCode)
610                 return (errorCode);
611             *ACL = VVnodeACL(*parent);
612             *ACLSize = VAclSize(*parent);
613             if ((errorCode = CheckVnode(Fid, volume, targetptr, Lock)) != 0)
614                 return (errorCode);
615             if ((*targetptr)->disk.parent != parentvnode) {
616                 VPutVnode(&errorCode, *parent);
617                 *parent = 0;
618                 if (errorCode)
619                     return (errorCode);
620             } else
621                 return (0);
622         }
623     }
624
625 }                               /*SetAccessList */
626
627 /* Must not be called with H_LOCK held */
628 static void
629 client_CheckRights(struct client *client, struct acl_accessList *ACL, 
630                    afs_int32 *rights)
631 {
632     *rights = 0;
633     ObtainReadLock(&client->lock);
634     if (client->CPS.prlist_len > 0 && !client->deleted &&
635         client->host && !(client->host->hostFlags & HOSTDELETED))
636         acl_CheckRights(ACL, &client->CPS, rights);
637     ReleaseReadLock(&client->lock);
638 }
639
640 /* Must not be called with H_LOCK held */
641 static afs_int32
642 client_HasAsMember(struct client *client, afs_int32 id)
643 {
644     afs_int32 code = 0;
645
646     ObtainReadLock(&client->lock);
647     if (client->CPS.prlist_len > 0 && !client->deleted && 
648         client->host && !(client->host->hostFlags & HOSTDELETED))
649         code = acl_IsAMember(id, &client->CPS);
650     ReleaseReadLock(&client->lock);
651     return code;
652 }
653
654 /*
655  * Compare the directory's ACL with the user's access rights in the client
656  * connection and return the user's and everybody else's access permissions
657  * in rights and anyrights, respectively
658  */
659 static afs_int32
660 GetRights(struct client *client, struct acl_accessList *ACL,
661           afs_int32 * rights, afs_int32 * anyrights)
662 {
663     extern prlist SystemAnyUserCPS;
664     afs_int32 hrights = 0;
665 #ifndef AFS_PTHREAD_ENV
666     int code;
667 #endif
668
669     if (acl_CheckRights(ACL, &SystemAnyUserCPS, anyrights) != 0) {
670         ViceLog(0, ("CheckRights failed\n"));
671         *anyrights = 0;
672     }
673     *rights = 0;
674
675     client_CheckRights(client, ACL, rights);
676
677     /* wait if somebody else is already doing the getCPS call */
678     H_LOCK;
679     while (client->host->hostFlags & HCPS_INPROGRESS) {
680         client->host->hostFlags |= HCPS_WAITING;        /* I am waiting */
681 #ifdef AFS_PTHREAD_ENV
682         pthread_cond_wait(&client->host->cond, &host_glock_mutex);
683 #else /* AFS_PTHREAD_ENV */
684         if ((code =
685              LWP_WaitProcess(&(client->host->hostFlags))) != LWP_SUCCESS)
686             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
687 #endif /* AFS_PTHREAD_ENV */
688     }
689
690     if (!client->host->hcps.prlist_len || !client->host->hcps.prlist_val) {
691         char hoststr[16];
692         ViceLog(5,
693                 ("CheckRights: len=%u, for host=%s:%d\n",
694                  client->host->hcps.prlist_len, 
695                  afs_inet_ntoa_r(client->host->host, hoststr),
696                  ntohs(client->host->port)));
697     } else
698         acl_CheckRights(ACL, &client->host->hcps, &hrights);
699     H_UNLOCK;
700     /* Allow system:admin the rights given with the -implicit option */
701     if (client_HasAsMember(client, SystemId))
702         *rights |= implicitAdminRights;
703
704     *rights |= hrights;
705     *anyrights |= hrights;
706
707     return (0);
708
709 }                               /*GetRights */
710
711 /*
712  * VanillaUser returns 1 (true) if the user is a vanilla user (i.e., not
713  * a System:Administrator)
714  */
715 static afs_int32
716 VanillaUser(struct client *client)
717 {
718     if (client_HasAsMember(client, SystemId))
719         return (0);             /* not a system administrator, then you're "vanilla" */
720     return (1);
721
722 }                               /*VanillaUser */
723
724
725 /*
726  * This unusual afs_int32-parameter routine encapsulates all volume package related
727  * operations together in a single function; it's called by almost all AFS
728  * interface calls.
729  */
730 static afs_int32
731 GetVolumePackage(struct rx_connection *tcon, AFSFid * Fid, Volume ** volptr,
732                  Vnode ** targetptr, int chkforDir, Vnode ** parent,
733                  struct client **client, int locktype, afs_int32 * rights,
734                  afs_int32 * anyrights)
735 {
736     struct acl_accessList *aCL; /* Internal access List */
737     int aCLSize;                /* size of the access list */
738     int errorCode = 0;          /* return code to caller */
739
740     if ((errorCode = CheckVnode(Fid, volptr, targetptr, locktype)))
741         return (errorCode);
742     if (chkforDir) {
743         if (chkforDir == MustNOTBeDIR
744             && ((*targetptr)->disk.type == vDirectory))
745             return (EISDIR);
746         else if (chkforDir == MustBeDIR
747                  && ((*targetptr)->disk.type != vDirectory))
748             return (ENOTDIR);
749     }
750     if ((errorCode =
751          SetAccessList(targetptr, volptr, &aCL, &aCLSize, parent,
752                        (chkforDir == MustBeDIR ? (AFSFid *) 0 : Fid),
753                        (chkforDir == MustBeDIR ? 0 : locktype))) != 0)
754         return (errorCode);
755     if (chkforDir == MustBeDIR)
756         assert((*parent) == 0);
757     if (!(*client)) {
758         if ((errorCode = GetClient(tcon, client)) != 0)
759             return (errorCode);
760         if (!(*client))
761             return (EINVAL);
762     }
763     GetRights(*client, aCL, rights, anyrights);
764     /* ok, if this is not a dir, set the PRSFS_ADMINISTER bit iff we're the owner */
765     if ((*targetptr)->disk.type != vDirectory) {
766         /* anyuser can't be owner, so only have to worry about rights, not anyrights */
767         if ((*targetptr)->disk.owner == (*client)->ViceId)
768             (*rights) |= PRSFS_ADMINISTER;
769         else
770             (*rights) &= ~PRSFS_ADMINISTER;
771     }
772 #ifdef ADMIN_IMPLICIT_LOOKUP
773     /* admins get automatic lookup on everything */
774     if (!VanillaUser(*client))
775         (*rights) |= PRSFS_LOOKUP;
776 #endif /* ADMIN_IMPLICIT_LOOKUP */
777     return errorCode;
778
779 }                               /*GetVolumePackage */
780
781
782 /*
783  * This is the opposite of GetVolumePackage(), and is always used at the end of
784  * AFS calls to put back all used vnodes and the volume in the proper order!
785  */
786 static void
787 PutVolumePackage(Vnode * parentwhentargetnotdir, Vnode * targetptr,
788                  Vnode * parentptr, Volume * volptr, struct client **client)
789 {
790     int fileCode = 0;           /* Error code returned by the volume package */
791
792     if (parentwhentargetnotdir) {
793         VPutVnode(&fileCode, parentwhentargetnotdir);
794         assert(!fileCode || (fileCode == VSALVAGE));
795     }
796     if (targetptr) {
797         VPutVnode(&fileCode, targetptr);
798         assert(!fileCode || (fileCode == VSALVAGE));
799     }
800     if (parentptr) {
801         VPutVnode(&fileCode, parentptr);
802         assert(!fileCode || (fileCode == VSALVAGE));
803     }
804     if (volptr) {
805         VPutVolume(volptr);
806     }
807     if (*client) {
808         PutClient(client);
809     }
810 }                               /*PutVolumePackage */
811
812 static int
813 VolumeOwner(register struct client *client, register Vnode * targetptr)
814 {
815     afs_int32 owner = V_owner(targetptr->volumePtr);    /* get volume owner */
816
817     if (owner >= 0)
818         return (client->ViceId == owner);
819     else {
820         /* 
821          * We don't have to check for host's cps since only regular
822          * viceid are volume owners.
823          */
824         return (client_HasAsMember(client, owner));
825     }
826
827 }                               /*VolumeOwner */
828
829 static int
830 VolumeRootVnode(Vnode * targetptr)
831 {
832     return ((targetptr->vnodeNumber == ROOTVNODE)
833             && (targetptr->disk.uniquifier == 1));
834
835 }                               /*VolumeRootVnode */
836
837 /*
838  * Check if target file has the proper access permissions for the Fetch
839  * (FetchData, FetchACL, FetchStatus) and Store (StoreData, StoreACL,
840  * StoreStatus) related calls
841  */
842 /* this code should probably just set a "priv" flag where all the audit events
843  * are now, and only generate the audit event once at the end of the routine, 
844  * thus only generating the event if all the checks succeed, but only because
845  * of the privilege       XXX
846  */
847 static afs_int32
848 Check_PermissionRights(Vnode * targetptr, struct client *client,
849                        afs_int32 rights, int CallingRoutine,
850                        AFSStoreStatus * InStatus)
851 {
852     int errorCode = 0;
853 #define OWNSp(client, target) ((client)->ViceId == (target)->disk.owner)
854 #define CHOWN(i,t) (((i)->Mask & AFS_SETOWNER) &&((i)->Owner != (t)->disk.owner))
855 #define CHGRP(i,t) (((i)->Mask & AFS_SETGROUP) &&((i)->Group != (t)->disk.group))
856
857     if (CallingRoutine & CHK_FETCH) {
858         if (CallingRoutine == CHK_FETCHDATA || VanillaUser(client)) {
859             if (targetptr->disk.type == vDirectory
860                 || targetptr->disk.type == vSymlink) {
861                 if (!(rights & PRSFS_LOOKUP)
862 #ifdef ADMIN_IMPLICIT_LOOKUP
863                     /* grant admins fetch on all directories */
864                     && VanillaUser(client)
865 #endif /* ADMIN_IMPLICIT_LOOKUP */
866                     && !VolumeOwner(client, targetptr))
867                     return (EACCES);
868             } else {            /* file */
869                 /* must have read access, or be owner and have insert access */
870                 if (!(rights & PRSFS_READ)
871                     && !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)))
872                     return (EACCES);
873             }
874             if (CallingRoutine == CHK_FETCHDATA
875                 && targetptr->disk.type == vFile)
876 #ifdef USE_GROUP_PERMS
877                 if (!OWNSp(client, targetptr)
878                     && !client_HasAsMember(client, targetptr->disk.owner)) {
879                     errorCode =
880                         (((GROUPREAD | GROUPEXEC) & targetptr->disk.modeBits)
881                          ? 0 : EACCES);
882                 } else {
883                     errorCode =
884                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.modeBits)
885                          ? 0 : EACCES);
886                 }
887 #else
888                 /*
889                  * The check with the ownership below is a kludge to allow
890                  * reading of files created with no read permission. The owner
891                  * of the file is always allowed to read it.
892                  */
893                 if ((client->ViceId != targetptr->disk.owner)
894                     && VanillaUser(client))
895                     errorCode =
896                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.
897                           modeBits) ? 0 : EACCES);
898 #endif
899         } else {                /*  !VanillaUser(client) && !FetchData */
900
901             osi_audit(PrivilegeEvent, 0, AUD_ID,
902                       (client ? client->ViceId : 0), AUD_INT, CallingRoutine,
903                       AUD_END);
904         }
905     } else {                    /* a store operation */
906         if ((rights & PRSFS_INSERT) && OWNSp(client, targetptr)
907             && (CallingRoutine != CHK_STOREACL)
908             && (targetptr->disk.type == vFile)) {
909             /* bypass protection checks on first store after a create
910              * for the creator; also prevent chowns during this time
911              * unless you are a system administrator */
912           /******  InStatus->Owner && UnixModeBits better be SET!! */
913             if (CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
914                 if (readonlyServer)
915                     return (VREADONLY);
916                 else if (VanillaUser(client))
917                     return (EPERM);     /* Was EACCES */
918                 else
919                     osi_audit(PrivilegeEvent, 0, AUD_ID,
920                               (client ? client->ViceId : 0), AUD_INT,
921                               CallingRoutine, AUD_END);
922             }
923         } else {
924             if (CallingRoutine != CHK_STOREDATA && !VanillaUser(client)) {
925                 osi_audit(PrivilegeEvent, 0, AUD_ID,
926                           (client ? client->ViceId : 0), AUD_INT,
927                           CallingRoutine, AUD_END);
928             } else {
929                 if (readonlyServer) {
930                     return (VREADONLY);
931                 }
932                 if (CallingRoutine == CHK_STOREACL) {
933                     if (!(rights & PRSFS_ADMINISTER)
934                         && !VolumeOwner(client, targetptr))
935                         return (EACCES);
936                 } else {        /* store data or status */
937                     /* watch for chowns and chgrps */
938                     if (CHOWN(InStatus, targetptr)
939                         || CHGRP(InStatus, targetptr)) {
940                         if (readonlyServer)
941                             return (VREADONLY);
942                         else if (VanillaUser(client))
943                             return (EPERM);     /* Was EACCES */
944                         else
945                             osi_audit(PrivilegeEvent, 0, AUD_ID,
946                                       (client ? client->ViceId : 0), AUD_INT,
947                                       CallingRoutine, AUD_END);
948                     }
949                     /* must be sysadmin to set suid/sgid bits */
950                     if ((InStatus->Mask & AFS_SETMODE) &&
951 #ifdef AFS_NT40_ENV
952                         (InStatus->UnixModeBits & 0xc00) != 0) {
953 #else
954                         (InStatus->UnixModeBits & (S_ISUID | S_ISGID)) != 0) {
955 #endif
956                         if (readonlyServer)
957                             return (VREADONLY);
958                         if (VanillaUser(client))
959                             return (EACCES);
960                         else
961                             osi_audit(PrivSetID, 0, AUD_ID,
962                                       (client ? client->ViceId : 0), AUD_INT,
963                                       CallingRoutine, AUD_END);
964                     }
965                     if (CallingRoutine == CHK_STOREDATA) {
966                         if (readonlyServer)
967                             return (VREADONLY);
968                         if (!(rights & PRSFS_WRITE))
969                             return (EACCES);
970                         /* Next thing is tricky.  We want to prevent people
971                          * from writing files sans 0200 bit, but we want
972                          * creating new files with 0444 mode to work.  We
973                          * don't check the 0200 bit in the "you are the owner"
974                          * path above, but here we check the bit.  However, if
975                          * you're a system administrator, we ignore the 0200
976                          * bit anyway, since you may have fchowned the file,
977                          * too */
978 #ifdef USE_GROUP_PERMS
979                         if ((targetptr->disk.type == vFile)
980                             && VanillaUser(client)) {
981                             if (!OWNSp(client, targetptr)
982                                 && !client_HasAsMember(client, targetptr->disk.owner)) {
983                                 errorCode =
984                                     ((GROUPWRITE & targetptr->disk.modeBits)
985                                      ? 0 : EACCES);
986                             } else {
987                                 errorCode =
988                                     ((OWNERWRITE & targetptr->disk.modeBits)
989                                      ? 0 : EACCES);
990                             }
991                         } else
992 #endif
993                             if ((targetptr->disk.type != vDirectory)
994                                 && (!(targetptr->disk.modeBits & OWNERWRITE))) {
995                             if (readonlyServer)
996                                 return (VREADONLY);
997                             if (VanillaUser(client))
998                                 return (EACCES);
999                             else
1000                                 osi_audit(PrivilegeEvent, 0, AUD_ID,
1001                                           (client ? client->ViceId : 0),
1002                                           AUD_INT, CallingRoutine, AUD_END);
1003                         }
1004                     } else {    /* a status store */
1005                         if (readonlyServer)
1006                             return (VREADONLY);
1007                         if (targetptr->disk.type == vDirectory) {
1008                             if (!(rights & PRSFS_DELETE)
1009                                 && !(rights & PRSFS_INSERT))
1010                                 return (EACCES);
1011                         } else {        /* a file  or symlink */
1012                             if (!(rights & PRSFS_WRITE))
1013                                 return (EACCES);
1014                         }
1015                     }
1016                 }
1017             }
1018         }
1019     }
1020     return (errorCode);
1021
1022 }                               /*Check_PermissionRights */
1023
1024
1025 /*
1026  * The Access List information is converted from its internal form in the
1027  * target's vnode buffer (or its parent vnode buffer if not a dir), to an
1028  * external form and returned back to the caller, via the AccessList
1029  * structure
1030  */
1031 static afs_int32
1032 RXFetch_AccessList(Vnode * targetptr, Vnode * parentwhentargetnotdir,
1033                    struct AFSOpaque *AccessList)
1034 {
1035     char *eACL;                 /* External access list placeholder */
1036
1037     if (acl_Externalize
1038         ((targetptr->disk.type ==
1039           vDirectory ? VVnodeACL(targetptr) :
1040           VVnodeACL(parentwhentargetnotdir)), &eACL) != 0) {
1041         return EIO;
1042     }
1043     if ((strlen(eACL) + 1) > AFSOPAQUEMAX) {
1044         acl_FreeExternalACL(&eACL);
1045         return (E2BIG);
1046     } else {
1047         strcpy((char *)(AccessList->AFSOpaque_val), (char *)eACL);
1048         AccessList->AFSOpaque_len = strlen(eACL) + 1;
1049     }
1050     acl_FreeExternalACL(&eACL);
1051     return (0);
1052
1053 }                               /*RXFetch_AccessList */
1054
1055
1056 /*
1057  * The Access List information is converted from its external form in the
1058  * input AccessList structure to the internal representation and copied into
1059  * the target dir's vnode storage.
1060  */
1061 static afs_int32
1062 RXStore_AccessList(Vnode * targetptr, struct AFSOpaque *AccessList)
1063 {
1064     struct acl_accessList *newACL;      /* PlaceHolder for new access list */
1065
1066     if (acl_Internalize(AccessList->AFSOpaque_val, &newACL) != 0)
1067         return (EINVAL);
1068     if ((newACL->size + 4) > VAclSize(targetptr))
1069         return (E2BIG);
1070     memcpy((char *)VVnodeACL(targetptr), (char *)newACL, (int)(newACL->size));
1071     acl_FreeACL(&newACL);
1072     return (0);
1073
1074 }                               /*RXStore_AccessList */
1075
1076
1077 /* In our current implementation, each successive data store (new file
1078  * data version) creates a new inode. This function creates the new
1079  * inode, copies the old inode's contents to the new one, remove the old
1080  * inode (i.e. decrement inode count -- if it's currently used the delete
1081  * will be delayed), and modify some fields (i.e. vnode's
1082  * disk.inodeNumber and cloned)
1083  */
1084 #define COPYBUFFSIZE    8192
1085 static int
1086 CopyOnWrite(Vnode * targetptr, Volume * volptr)
1087 {
1088     Inode ino, nearInode;
1089     int rdlen;
1090     int wrlen;
1091     register afs_fsize_t size;
1092     register int length;
1093     char *buff;
1094     int rc;                     /* return code */
1095     IHandle_t *newH;            /* Use until finished copying, then cp to vnode. */
1096     FdHandle_t *targFdP;        /* Source Inode file handle */
1097     FdHandle_t *newFdP;         /* Dest Inode file handle */
1098
1099     if (targetptr->disk.type == vDirectory)
1100         DFlush();               /* just in case? */
1101
1102     VN_GET_LEN(size, targetptr);
1103     buff = (char *)malloc(COPYBUFFSIZE);
1104     if (buff == NULL) {
1105         return EIO;
1106     }
1107
1108     ino = VN_GET_INO(targetptr);
1109     if (!VALID_INO(ino)) {
1110         free(buff);
1111         VTakeOffline(volptr);
1112         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
1113                     volptr->hashid));
1114         return EIO;
1115     }    
1116     targFdP = IH_OPEN(targetptr->handle);
1117     if (targFdP == NULL) {
1118         rc = errno;
1119         ViceLog(0,
1120                 ("CopyOnWrite failed: Failed to open target vnode %u in volume %u (errno = %d)\n",
1121                  targetptr->vnodeNumber, V_id(volptr), rc));
1122         free(buff);
1123         VTakeOffline(volptr);
1124         return rc;
1125     }
1126
1127     nearInode = VN_GET_INO(targetptr);
1128     ino =
1129         IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1130                   VPartitionPath(V_partition(volptr)), nearInode,
1131                   V_id(volptr), targetptr->vnodeNumber,
1132                   targetptr->disk.uniquifier,
1133                   (int)targetptr->disk.dataVersion);
1134     if (!VALID_INO(ino)) {
1135         ViceLog(0,
1136                 ("CopyOnWrite failed: Partition %s that contains volume %u may be out of free inodes(errno = %d)\n",
1137                  volptr->partition->name, V_id(volptr), errno));
1138         FDH_CLOSE(targFdP);
1139         free(buff);
1140         return ENOSPC;
1141     }
1142     IH_INIT(newH, V_device(volptr), V_id(volptr), ino);
1143     newFdP = IH_OPEN(newH);
1144     assert(newFdP != NULL);
1145
1146     while (size > 0) {
1147         if (size > COPYBUFFSIZE) {      /* more than a buffer */
1148             length = COPYBUFFSIZE;
1149             size -= COPYBUFFSIZE;
1150         } else {
1151             length = (int)size;
1152             size = 0;
1153         }
1154         rdlen = FDH_READ(targFdP, buff, length);
1155         if (rdlen == length)
1156             wrlen = FDH_WRITE(newFdP, buff, length);
1157         else
1158             wrlen = 0;
1159         /*  Callers of this function are not prepared to recover
1160          *  from error that put the filesystem in an inconsistent
1161          *  state. Make sure that we force the volume off-line if
1162          *  we some error other than ENOSPC - 4.29.99)
1163          *
1164          *  In case we are unable to write the required bytes, and the
1165          *  error code indicates that the disk is full, we roll-back to
1166          *  the initial state.
1167          */
1168         if ((rdlen != length) || (wrlen != length))
1169             if ((wrlen < 0) && (errno == ENOSPC)) {     /* disk full */
1170                 ViceLog(0,
1171                         ("CopyOnWrite failed: Partition %s containing volume %u is full\n",
1172                          volptr->partition->name, V_id(volptr)));
1173                 /* remove destination inode which was partially copied till now */
1174                 FDH_REALLYCLOSE(newFdP);
1175                 IH_RELEASE(newH);
1176                 FDH_REALLYCLOSE(targFdP);
1177                 rc = IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1178                 if (!rc) {
1179                     ViceLog(0,
1180                             ("CopyOnWrite failed: error %u after i_dec on disk full, volume %u in partition %s needs salvage\n",
1181                              rc, V_id(volptr), volptr->partition->name));
1182                     VTakeOffline(volptr);
1183                 }
1184                 free(buff);
1185                 return ENOSPC;
1186             } else {
1187                 ViceLog(0,
1188                         ("CopyOnWrite failed: volume %u in partition %s  (tried reading %u, read %u, wrote %u, errno %u) volume needs salvage\n",
1189                          V_id(volptr), volptr->partition->name, length, rdlen,
1190                          wrlen, errno));
1191 #if defined(AFS_DEMAND_ATTACH_FS)
1192                 ViceLog(0, ("CopyOnWrite failed: requesting salvage\n"));
1193 #else
1194                 ViceLog(0, ("CopyOnWrite failed: taking volume offline\n"));
1195 #endif
1196                 /* Decrement this inode so salvager doesn't find it. */
1197                 FDH_REALLYCLOSE(newFdP);
1198                 IH_RELEASE(newH);
1199                 FDH_REALLYCLOSE(targFdP);
1200                 rc = IH_DEC(V_linkHandle(volptr), ino, V_parentId(volptr));
1201                 free(buff);
1202                 VTakeOffline(volptr);
1203                 return EIO;
1204             }
1205 #ifndef AFS_PTHREAD_ENV
1206         IOMGR_Poll();
1207 #endif /* !AFS_PTHREAD_ENV */
1208     }
1209     FDH_REALLYCLOSE(targFdP);
1210     rc = IH_DEC(V_linkHandle(volptr), VN_GET_INO(targetptr),
1211                 V_parentId(volptr));
1212     assert(!rc);
1213     IH_RELEASE(targetptr->handle);
1214
1215     rc = FDH_SYNC(newFdP);
1216     assert(rc == 0);
1217     FDH_CLOSE(newFdP);
1218     targetptr->handle = newH;
1219     VN_SET_INO(targetptr, ino);
1220     targetptr->disk.cloned = 0;
1221     /* Internal change to vnode, no user level change to volume - def 5445 */
1222     targetptr->changed_oldTime = 1;
1223     free(buff);
1224     return 0;                   /* success */
1225 }                               /*CopyOnWrite */
1226
1227
1228 /*
1229  * Common code to handle with removing the Name (file when it's called from
1230  * SAFS_RemoveFile() or an empty dir when called from SAFS_rmdir()) from a
1231  * given directory, parentptr.
1232  */
1233 int DT1 = 0, DT0 = 0;
1234 static afs_int32
1235 DeleteTarget(Vnode * parentptr, Volume * volptr, Vnode ** targetptr,
1236              DirHandle * dir, AFSFid * fileFid, char *Name, int ChkForDir)
1237 {
1238     DirHandle childdir;         /* Handle for dir package I/O */
1239     int errorCode = 0;
1240     int code;
1241
1242     /* watch for invalid names */
1243     if (!strcmp(Name, ".") || !strcmp(Name, ".."))
1244         return (EINVAL);
1245     if (parentptr->disk.cloned) {
1246         ViceLog(25, ("DeleteTarget : CopyOnWrite called\n"));
1247         if ((errorCode = CopyOnWrite(parentptr, volptr))) {
1248             ViceLog(20,
1249                     ("DeleteTarget %s: CopyOnWrite failed %d\n", Name,
1250                      errorCode));
1251             return errorCode;
1252         }
1253     }
1254
1255     /* check that the file is in the directory */
1256     SetDirHandle(dir, parentptr);
1257     if (Lookup(dir, Name, fileFid))
1258         return (ENOENT);
1259     fileFid->Volume = V_id(volptr);
1260
1261     /* just-in-case check for something causing deadlock */
1262     if (fileFid->Vnode == parentptr->vnodeNumber)
1263         return (EINVAL);
1264
1265     *targetptr = VGetVnode(&errorCode, volptr, fileFid->Vnode, WRITE_LOCK);
1266     if (errorCode) {
1267         return (errorCode);
1268     }
1269     if (ChkForDir == MustBeDIR) {
1270         if ((*targetptr)->disk.type != vDirectory)
1271             return (ENOTDIR);
1272     } else if ((*targetptr)->disk.type == vDirectory)
1273         return (EISDIR);
1274
1275     /*assert((*targetptr)->disk.uniquifier == fileFid->Unique); */
1276     /**
1277       * If the uniquifiers dont match then instead of asserting
1278       * take the volume offline and return VSALVAGE
1279       */
1280     if ((*targetptr)->disk.uniquifier != fileFid->Unique) {
1281         VTakeOffline(volptr);
1282         ViceLog(0,
1283                 ("Volume %u now offline, must be salvaged.\n",
1284                  volptr->hashid));
1285         errorCode = VSALVAGE;
1286         return errorCode;
1287     }
1288
1289     if (ChkForDir == MustBeDIR) {
1290         SetDirHandle(&childdir, *targetptr);
1291         if (IsEmpty(&childdir) != 0)
1292             return (EEXIST);
1293         DZap(&childdir);
1294         (*targetptr)->delete = 1;
1295     } else if ((--(*targetptr)->disk.linkCount) == 0)
1296         (*targetptr)->delete = 1;
1297     if ((*targetptr)->delete) {
1298         if (VN_GET_INO(*targetptr)) {
1299             DT0++;
1300             IH_REALLYCLOSE((*targetptr)->handle);
1301             errorCode =
1302                 IH_DEC(V_linkHandle(volptr), VN_GET_INO(*targetptr),
1303                        V_parentId(volptr));
1304             IH_RELEASE((*targetptr)->handle);
1305             if (errorCode == -1) {
1306                 ViceLog(0,
1307                         ("DT: inode=%s, name=%s, errno=%d\n",
1308                          PrintInode(NULL, VN_GET_INO(*targetptr)), Name,
1309                          errno));
1310                 if (errno != ENOENT)
1311                 {
1312                     VTakeOffline(volptr);
1313                     ViceLog(0,
1314                             ("Volume %u now offline, must be salvaged.\n",
1315                              volptr->hashid));
1316                     return (EIO);
1317                 }
1318                 DT1++;
1319                 errorCode = 0;
1320             }
1321         }
1322         VN_SET_INO(*targetptr, (Inode) 0);
1323         {
1324             afs_fsize_t adjLength;
1325             VN_GET_LEN(adjLength, *targetptr);
1326             VAdjustDiskUsage(&errorCode, volptr, -(int)nBlocks(adjLength), 0);
1327         }
1328     }
1329
1330     (*targetptr)->changed_newTime = 1;  /* Status change of deleted file/dir */
1331
1332     code = Delete(dir, (char *)Name);
1333     if (code) {
1334         ViceLog(0,
1335                 ("Error %d deleting %s\n", code,
1336                  (((*targetptr)->disk.type ==
1337                    Directory) ? "directory" : "file")));
1338         VTakeOffline(volptr);
1339         ViceLog(0,
1340                 ("Volume %u now offline, must be salvaged.\n",
1341                  volptr->hashid));
1342         if (!errorCode)
1343             errorCode = code;
1344     }
1345
1346     DFlush();
1347     return (errorCode);
1348
1349 }                               /*DeleteTarget */
1350
1351
1352 /*
1353  * This routine updates the parent directory's status block after the
1354  * specified operation (i.e. RemoveFile(), CreateFile(), Rename(),
1355  * SymLink(), Link(), MakeDir(), RemoveDir()) on one of its children has
1356  * been performed.
1357  */
1358 static void
1359 Update_ParentVnodeStatus(Vnode * parentptr, Volume * volptr, DirHandle * dir,
1360                          int author, int linkcount,
1361 #if FS_STATS_DETAILED
1362                          char a_inSameNetwork
1363 #endif                          /* FS_STATS_DETAILED */
1364     )
1365 {
1366     afs_fsize_t newlength;      /* Holds new directory length */
1367     afs_fsize_t parentLength;
1368     int errorCode;
1369 #if FS_STATS_DETAILED
1370     Date currDate;              /*Current date */
1371     int writeIdx;               /*Write index to bump */
1372     int timeIdx;                /*Authorship time index to bump */
1373 #endif /* FS_STATS_DETAILED */
1374
1375     parentptr->disk.dataVersion++;
1376     newlength = (afs_fsize_t) Length(dir);
1377     /* 
1378      * This is a called on both dir removals (i.e. remove, removedir, rename) but also in dir additions
1379      * (create, symlink, link, makedir) so we need to check if we have enough space
1380      * XXX But we still don't check the error since we're dealing with dirs here and really the increase
1381      * of a new entry would be too tiny to worry about failures (since we have all the existing cushion)
1382      */
1383     VN_GET_LEN(parentLength, parentptr);
1384     if (nBlocks(newlength) != nBlocks(parentLength)) {
1385         VAdjustDiskUsage(&errorCode, volptr,
1386                          (nBlocks(newlength) - nBlocks(parentLength)),
1387                          (nBlocks(newlength) - nBlocks(parentLength)));
1388     }
1389     VN_SET_LEN(parentptr, newlength);
1390
1391 #if FS_STATS_DETAILED
1392     /*
1393      * Update directory write stats for this volume.  Note that the auth
1394      * counter is located immediately after its associated ``distance''
1395      * counter.
1396      */
1397     if (a_inSameNetwork)
1398         writeIdx = VOL_STATS_SAME_NET;
1399     else
1400         writeIdx = VOL_STATS_DIFF_NET;
1401     V_stat_writes(volptr, writeIdx)++;
1402     if (author != AnonymousID) {
1403         V_stat_writes(volptr, writeIdx + 1)++;
1404     }
1405
1406     /*
1407      * Update the volume's authorship information in response to this
1408      * directory operation.  Get the current time, decide to which time
1409      * slot this operation belongs, and bump the appropriate slot.
1410      */
1411     currDate = (FT_ApproxTime() - parentptr->disk.unixModifyTime);
1412     timeIdx =
1413         (currDate < VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 : currDate <
1414          VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 : currDate <
1415          VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 : currDate <
1416          VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 : currDate <
1417          VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 : VOL_STATS_TIME_IDX_5);
1418     if (parentptr->disk.author == author) {
1419         V_stat_dirSameAuthor(volptr, timeIdx)++;
1420     } else {
1421         V_stat_dirDiffAuthor(volptr, timeIdx)++;
1422     }
1423 #endif /* FS_STATS_DETAILED */
1424
1425     parentptr->disk.author = author;
1426     parentptr->disk.linkCount = linkcount;
1427     parentptr->disk.unixModifyTime = FT_ApproxTime();   /* This should be set from CLIENT!! */
1428     parentptr->disk.serverModifyTime = FT_ApproxTime();
1429     parentptr->changed_newTime = 1;     /* vnode changed, write it back. */
1430 }
1431
1432
1433 /*
1434  * Update the target file's (or dir's) status block after the specified
1435  * operation is complete. Note that some other fields maybe updated by
1436  * the individual module.
1437  */
1438
1439 /* XXX INCOMPLETE - More attention is needed here! */
1440 static void
1441 Update_TargetVnodeStatus(Vnode * targetptr, afs_uint32 Caller,
1442                          struct client *client, AFSStoreStatus * InStatus,
1443                          Vnode * parentptr, Volume * volptr,
1444                          afs_fsize_t length)
1445 {
1446 #if FS_STATS_DETAILED
1447     Date currDate;              /*Current date */
1448     int writeIdx;               /*Write index to bump */
1449     int timeIdx;                /*Authorship time index to bump */
1450 #endif /* FS_STATS_DETAILED */
1451
1452     if (Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR)) { /* initialize new file */
1453         targetptr->disk.parent = parentptr->vnodeNumber;
1454         VN_SET_LEN(targetptr, length);
1455         /* targetptr->disk.group =      0;  save some cycles */
1456         targetptr->disk.modeBits = 0777;
1457         targetptr->disk.owner = client->ViceId;
1458         targetptr->disk.dataVersion = 0;        /* consistent with the client */
1459         targetptr->disk.linkCount = (Caller & TVS_MKDIR ? 2 : 1);
1460         /* the inode was created in Alloc_NewVnode() */
1461     }
1462 #if FS_STATS_DETAILED
1463     /*
1464      * Update file write stats for this volume.  Note that the auth
1465      * counter is located immediately after its associated ``distance''
1466      * counter.
1467      */
1468     if (client->InSameNetwork)
1469         writeIdx = VOL_STATS_SAME_NET;
1470     else
1471         writeIdx = VOL_STATS_DIFF_NET;
1472     V_stat_writes(volptr, writeIdx)++;
1473     if (client->ViceId != AnonymousID) {
1474         V_stat_writes(volptr, writeIdx + 1)++;
1475     }
1476
1477     /*
1478      * We only count operations that DON'T involve creating new objects
1479      * (files, symlinks, directories) or simply setting status as
1480      * authorship-change operations.
1481      */
1482     if (!(Caller & (TVS_CFILE | TVS_SLINK | TVS_MKDIR | TVS_SSTATUS))) {
1483         /*
1484          * Update the volume's authorship information in response to this
1485          * file operation.  Get the current time, decide to which time
1486          * slot this operation belongs, and bump the appropriate slot.
1487          */
1488         currDate = (FT_ApproxTime() - targetptr->disk.unixModifyTime);
1489         timeIdx =
1490             (currDate <
1491              VOL_STATS_TIME_CAP_0 ? VOL_STATS_TIME_IDX_0 : currDate <
1492              VOL_STATS_TIME_CAP_1 ? VOL_STATS_TIME_IDX_1 : currDate <
1493              VOL_STATS_TIME_CAP_2 ? VOL_STATS_TIME_IDX_2 : currDate <
1494              VOL_STATS_TIME_CAP_3 ? VOL_STATS_TIME_IDX_3 : currDate <
1495              VOL_STATS_TIME_CAP_4 ? VOL_STATS_TIME_IDX_4 :
1496              VOL_STATS_TIME_IDX_5);
1497         if (targetptr->disk.author == client->ViceId) {
1498             V_stat_fileSameAuthor(volptr, timeIdx)++;
1499         } else {
1500             V_stat_fileDiffAuthor(volptr, timeIdx)++;
1501         }
1502     }
1503 #endif /* FS_STATS_DETAILED */
1504
1505     if (!(Caller & TVS_SSTATUS))
1506         targetptr->disk.author = client->ViceId;
1507     if (Caller & TVS_SDATA) {
1508         targetptr->disk.dataVersion++;
1509         if (VanillaUser(client)) {
1510             targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1511 #ifdef CREATE_SGUID_ADMIN_ONLY
1512             targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1513 #endif
1514         }
1515     }
1516     if (Caller & TVS_SSTATUS) { /* update time on non-status change */
1517         /* store status, must explicitly request to change the date */
1518         if (InStatus->Mask & AFS_SETMODTIME)
1519             targetptr->disk.unixModifyTime = InStatus->ClientModTime;
1520     } else {                    /* other: date always changes, but perhaps to what is specified by caller */
1521         targetptr->disk.unixModifyTime =
1522             (InStatus->Mask & AFS_SETMODTIME ? InStatus->
1523              ClientModTime : FT_ApproxTime());
1524     }
1525     if (InStatus->Mask & AFS_SETOWNER) {
1526         /* admin is allowed to do chmod, chown as well as chown, chmod. */
1527         if (VanillaUser(client)) {
1528             targetptr->disk.modeBits &= ~04000; /* turn off suid for file. */
1529 #ifdef CREATE_SGUID_ADMIN_ONLY
1530             targetptr->disk.modeBits &= ~02000; /* turn off sgid for file. */
1531 #endif
1532         }
1533         targetptr->disk.owner = InStatus->Owner;
1534         if (VolumeRootVnode(targetptr)) {
1535             Error errorCode = 0;        /* what should be done with this? */
1536
1537             V_owner(targetptr->volumePtr) = InStatus->Owner;
1538             VUpdateVolume(&errorCode, targetptr->volumePtr);
1539         }
1540     }
1541     if (InStatus->Mask & AFS_SETMODE) {
1542         int modebits = InStatus->UnixModeBits;
1543 #define CREATE_SGUID_ADMIN_ONLY 1
1544 #ifdef CREATE_SGUID_ADMIN_ONLY
1545         if (VanillaUser(client))
1546             modebits = modebits & 0777;
1547 #endif
1548         if (VanillaUser(client)) {
1549             targetptr->disk.modeBits = modebits;
1550         } else {
1551             targetptr->disk.modeBits = modebits;
1552             switch (Caller) {
1553             case TVS_SDATA:
1554                 osi_audit(PrivSetID, 0, AUD_ID, client->ViceId, AUD_INT,
1555                           CHK_STOREDATA, AUD_END);
1556                 break;
1557             case TVS_CFILE:
1558             case TVS_SSTATUS:
1559                 osi_audit(PrivSetID, 0, AUD_ID, client->ViceId, AUD_INT,
1560                           CHK_STORESTATUS, AUD_END);
1561                 break;
1562             default:
1563                 break;
1564             }
1565         }
1566     }
1567     targetptr->disk.serverModifyTime = FT_ApproxTime();
1568     if (InStatus->Mask & AFS_SETGROUP)
1569         targetptr->disk.group = InStatus->Group;
1570     /* vnode changed : to be written back by VPutVnode */
1571     targetptr->changed_newTime = 1;
1572
1573 }                               /*Update_TargetVnodeStatus */
1574
1575
1576 /*
1577  * Fills the CallBack structure with the expiration time and type of callback
1578  * structure. Warning: this function is currently incomplete.
1579  */
1580 static void
1581 SetCallBackStruct(afs_uint32 CallBackTime, struct AFSCallBack *CallBack)
1582 {
1583     /* CallBackTime could not be 0 */
1584     if (CallBackTime == 0) {
1585         ViceLog(0, ("WARNING: CallBackTime == 0!\n"));
1586         CallBack->ExpirationTime = 0;
1587     } else
1588         CallBack->ExpirationTime = CallBackTime - FT_ApproxTime();
1589     CallBack->CallBackVersion = CALLBACK_VERSION;
1590     CallBack->CallBackType = CB_SHARED; /* The default for now */
1591
1592 }                               /*SetCallBackStruct */
1593
1594
1595 /*
1596  * Adjusts (Subtract) "length" number of blocks from the volume's disk
1597  * allocation; if some error occured (exceeded volume quota or partition
1598  * was full, or whatever), it frees the space back and returns the code.
1599  * We usually pre-adjust the volume space to make sure that there's
1600  * enough space before consuming some.
1601  */
1602 static afs_int32
1603 AdjustDiskUsage(Volume * volptr, afs_sfsize_t length,
1604                 afs_sfsize_t checkLength)
1605 {
1606     int rc;
1607     int nc;
1608
1609     VAdjustDiskUsage(&rc, volptr, length, checkLength);
1610     if (rc) {
1611         VAdjustDiskUsage(&nc, volptr, -length, 0);
1612         if (rc == VOVERQUOTA) {
1613             ViceLog(2,
1614                     ("Volume %u (%s) is full\n", V_id(volptr),
1615                      V_name(volptr)));
1616             return (rc);
1617         }
1618         if (rc == VDISKFULL) {
1619             ViceLog(0,
1620                     ("Partition %s that contains volume %u is full\n",
1621                      volptr->partition->name, V_id(volptr)));
1622             return (rc);
1623         }
1624         ViceLog(0, ("Got error return %d from VAdjustDiskUsage\n", rc));
1625         return (rc);
1626     }
1627     return (0);
1628
1629 }                               /*AdjustDiskUsage */
1630
1631 /*
1632  * Common code that handles the creation of a new file (SAFS_CreateFile and
1633  * SAFS_Symlink) or a new dir (SAFS_MakeDir)
1634  */
1635 static afs_int32
1636 Alloc_NewVnode(Vnode * parentptr, DirHandle * dir, Volume * volptr,
1637                Vnode ** targetptr, char *Name, struct AFSFid *OutFid,
1638                int FileType, afs_sfsize_t BlocksPreallocatedForVnode)
1639 {
1640     int errorCode = 0;          /* Error code returned back */
1641     int temp;
1642     Inode inode = 0;
1643     Inode nearInode;            /* hint for inode allocation in solaris */
1644
1645     if ((errorCode =
1646          AdjustDiskUsage(volptr, BlocksPreallocatedForVnode,
1647                          BlocksPreallocatedForVnode))) {
1648         ViceLog(25,
1649                 ("Insufficient space to allocate %lld blocks\n",
1650                  (afs_intmax_t) BlocksPreallocatedForVnode));
1651         return (errorCode);
1652     }
1653
1654     *targetptr = VAllocVnode(&errorCode, volptr, FileType);
1655     if (errorCode != 0) {
1656         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1657         return (errorCode);
1658     }
1659     OutFid->Volume = V_id(volptr);
1660     OutFid->Vnode = (*targetptr)->vnodeNumber;
1661     OutFid->Unique = (*targetptr)->disk.uniquifier;
1662
1663     nearInode = VN_GET_INO(parentptr);  /* parent is also in same vol */
1664
1665     /* create the inode now itself */
1666     inode =
1667         IH_CREATE(V_linkHandle(volptr), V_device(volptr),
1668                   VPartitionPath(V_partition(volptr)), nearInode,
1669                   V_id(volptr), (*targetptr)->vnodeNumber,
1670                   (*targetptr)->disk.uniquifier, 1);
1671
1672     /* error in creating inode */
1673     if (!VALID_INO(inode)) {
1674         ViceLog(0,
1675                 ("Volume : %u vnode = %u Failed to create inode: errno = %d\n",
1676                  (*targetptr)->volumePtr->header->diskstuff.id,
1677                  (*targetptr)->vnodeNumber, errno));
1678         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1679         (*targetptr)->delete = 1;       /* delete vnode */
1680         return ENOSPC;
1681     }
1682     VN_SET_INO(*targetptr, inode);
1683     IH_INIT(((*targetptr)->handle), V_device(volptr), V_id(volptr), inode);
1684
1685     /* copy group from parent dir */
1686     (*targetptr)->disk.group = parentptr->disk.group;
1687
1688     if (parentptr->disk.cloned) {
1689         ViceLog(25, ("Alloc_NewVnode : CopyOnWrite called\n"));
1690         if ((errorCode = CopyOnWrite(parentptr, volptr))) {     /* disk full */
1691             ViceLog(25, ("Alloc_NewVnode : CopyOnWrite failed\n"));
1692             /* delete the vnode previously allocated */
1693             (*targetptr)->delete = 1;
1694             VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1695             IH_REALLYCLOSE((*targetptr)->handle);
1696             if (IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1697                 ViceLog(0,
1698                         ("Alloc_NewVnode: partition %s idec %s failed\n",
1699                          volptr->partition->name, PrintInode(NULL, inode)));
1700             IH_RELEASE((*targetptr)->handle);
1701
1702             return errorCode;
1703         }
1704     }
1705
1706     /* add the name to the directory */
1707     SetDirHandle(dir, parentptr);
1708     if ((errorCode = Create(dir, (char *)Name, OutFid))) {
1709         (*targetptr)->delete = 1;
1710         VAdjustDiskUsage(&temp, volptr, -BlocksPreallocatedForVnode, 0);
1711         IH_REALLYCLOSE((*targetptr)->handle);
1712         if (IH_DEC(V_linkHandle(volptr), inode, V_parentId(volptr)))
1713             ViceLog(0,
1714                     ("Alloc_NewVnode: partition %s idec %s failed\n",
1715                      volptr->partition->name, PrintInode(NULL, inode)));
1716         IH_RELEASE((*targetptr)->handle);
1717         return (errorCode);
1718     }
1719     DFlush();
1720     return (0);
1721
1722 }                               /*Alloc_NewVnode */
1723
1724
1725 /*
1726  * Handle all the lock-related code (SAFS_SetLock, SAFS_ExtendLock and
1727  * SAFS_ReleaseLock)
1728  */
1729 static afs_int32
1730 HandleLocking(Vnode * targetptr, struct client *client, afs_int32 rights, ViceLockType LockingType)
1731 {
1732     int Time;                   /* Used for time */
1733     int writeVnode = targetptr->changed_oldTime;        /* save original status */
1734
1735     targetptr->changed_oldTime = 1;     /* locking doesn't affect any time stamp */
1736     Time = FT_ApproxTime();
1737     switch (LockingType) {
1738     case LockRead:
1739     case LockWrite:
1740         if (Time > targetptr->disk.lock.lockTime)
1741             targetptr->disk.lock.lockTime = targetptr->disk.lock.lockCount =
1742                 0;
1743         Time += AFS_LOCKWAIT;
1744         if (LockingType == LockRead) {
1745             if ( !(rights & PRSFS_LOCK) && 
1746                  !(rights & PRSFS_WRITE) &&
1747                  !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)) )
1748                     return(EACCES);
1749             return(EACCES);
1750
1751             if (targetptr->disk.lock.lockCount >= 0) {
1752                 ++(targetptr->disk.lock.lockCount);
1753                 targetptr->disk.lock.lockTime = Time;
1754             } else
1755                 return (EAGAIN);
1756         } else if (LockingType == LockWrite) {
1757             if ( !(rights & PRSFS_WRITE) && 
1758                  !(OWNSp(client, targetptr) && (rights & PRSFS_INSERT)) )
1759                 return(EACCES);
1760
1761             if (targetptr->disk.lock.lockCount == 0) {
1762                 targetptr->disk.lock.lockCount = -1;
1763                 targetptr->disk.lock.lockTime = Time;
1764             } else
1765                 return (EAGAIN);
1766         }
1767         break;
1768     case LockExtend:
1769         Time += AFS_LOCKWAIT;
1770         if (targetptr->disk.lock.lockCount != 0)
1771             targetptr->disk.lock.lockTime = Time;
1772         else
1773             return (EINVAL);
1774         break;
1775     case LockRelease:
1776         if ((--targetptr->disk.lock.lockCount) <= 0)
1777             targetptr->disk.lock.lockCount = targetptr->disk.lock.lockTime =
1778                 0;
1779         break;
1780     default:
1781         targetptr->changed_oldTime = writeVnode;        /* restore old status */
1782         ViceLog(0, ("Illegal Locking type %d\n", LockingType));
1783     }
1784     return (0);
1785 }                               /*HandleLocking */
1786
1787 /* Checks if caller has the proper AFS and Unix (WRITE) access permission to the target directory; Prfs_Mode refers to the AFS Mode operation while rights contains the caller's access permissions to the directory. */
1788
1789 static afs_int32
1790 CheckWriteMode(Vnode * targetptr, afs_int32 rights, int Prfs_Mode)
1791 {
1792     if (readonlyServer)
1793         return (VREADONLY);
1794     if (!(rights & Prfs_Mode))
1795         return (EACCES);
1796     if ((targetptr->disk.type != vDirectory)
1797         && (!(targetptr->disk.modeBits & OWNERWRITE)))
1798         return (EACCES);
1799     return (0);
1800 }
1801
1802 /*
1803  * If some flags (i.e. min or max quota) are set, the volume's in disk
1804  * label is updated; Name, OfflineMsg, and Motd are also reflected in the
1805  * update, if applicable.
1806  */
1807 static afs_int32
1808 RXUpdate_VolumeStatus(Volume * volptr, AFSStoreVolumeStatus * StoreVolStatus,
1809                       char *Name, char *OfflineMsg, char *Motd)
1810 {
1811     Error errorCode = 0;
1812
1813     if (StoreVolStatus->Mask & AFS_SETMINQUOTA)
1814         V_minquota(volptr) = StoreVolStatus->MinQuota;
1815     if (StoreVolStatus->Mask & AFS_SETMAXQUOTA)
1816         V_maxquota(volptr) = StoreVolStatus->MaxQuota;
1817     if (strlen(OfflineMsg) > 0) {
1818         strcpy(V_offlineMessage(volptr), OfflineMsg);
1819     }
1820     if (strlen(Name) > 0) {
1821         strcpy(V_name(volptr), Name);
1822     }
1823 #if OPENAFS_VOL_STATS
1824     /*
1825      * We don't overwrite the motd field, since it's now being used
1826      * for stats
1827      */
1828 #else
1829     if (strlen(Motd) > 0) {
1830         strcpy(V_motd(volptr), Motd);
1831     }
1832 #endif /* FS_STATS_DETAILED */
1833     VUpdateVolume(&errorCode, volptr);
1834     return (errorCode);
1835
1836 }                               /*RXUpdate_VolumeStatus */
1837
1838
1839 static afs_int32
1840 RXGetVolumeStatus(AFSFetchVolumeStatus * status, char **name, char **offMsg,
1841                   char **motd, Volume * volptr)
1842 {
1843     int temp;
1844
1845     status->Vid = V_id(volptr);
1846     status->ParentId = V_parentId(volptr);
1847     status->Online = V_inUse(volptr);
1848     status->InService = V_inService(volptr);
1849     status->Blessed = V_blessed(volptr);
1850     status->NeedsSalvage = V_needsSalvaged(volptr);
1851     if (VolumeWriteable(volptr))
1852         status->Type = ReadWrite;
1853     else
1854         status->Type = ReadOnly;
1855     status->MinQuota = V_minquota(volptr);
1856     status->MaxQuota = V_maxquota(volptr);
1857     status->BlocksInUse = V_diskused(volptr);
1858     status->PartBlocksAvail = volptr->partition->free;
1859     status->PartMaxBlocks = volptr->partition->totalUsable;
1860
1861     /* now allocate and copy these things; they're freed by the RXGEN stub */
1862     temp = strlen(V_name(volptr)) + 1;
1863     *name = malloc(temp);
1864     if (!*name) {
1865         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1866         assert(0);
1867     }
1868     strcpy(*name, V_name(volptr));
1869     temp = strlen(V_offlineMessage(volptr)) + 1;
1870     *offMsg = malloc(temp);
1871     if (!*offMsg) {
1872         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1873         assert(0);
1874     }
1875     strcpy(*offMsg, V_offlineMessage(volptr));
1876 #if OPENAFS_VOL_STATS
1877     *motd = malloc(1);
1878     if (!*motd) {
1879         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1880         assert(0);
1881     }
1882     strcpy(*motd, nullString);
1883 #else
1884     temp = strlen(V_motd(volptr)) + 1;
1885     *motd = malloc(temp);
1886     if (!*motd) {
1887         ViceLog(0, ("Failed malloc in RXGetVolumeStatus\n"));
1888         assert(0);
1889     }
1890     strcpy(*motd, V_motd(volptr));
1891 #endif /* FS_STATS_DETAILED */
1892     return 0;
1893 }                               /*RXGetVolumeStatus */
1894
1895
1896 static afs_int32
1897 FileNameOK(register char *aname)
1898 {
1899     register afs_int32 i, tc;
1900     i = strlen(aname);
1901     if (i >= 4) {
1902         /* watch for @sys on the right */
1903         if (strcmp(aname + i - 4, "@sys") == 0)
1904             return 0;
1905     }
1906     while ((tc = *aname++)) {
1907         if (tc == '/')
1908             return 0;           /* very bad character to encounter */
1909     }
1910     return 1;                   /* file name is ok */
1911
1912 }                               /*FileNameOK */
1913
1914
1915 /*
1916  * This variant of symlink is expressly to support the AFS/DFS translator
1917  * and is not supported by the AFS fileserver. We just return EINVAL.
1918  * The cache manager should not generate this call to an AFS cache manager.
1919  */
1920 afs_int32
1921 SRXAFS_DFSSymlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
1922                   char *LinkContents, struct AFSStoreStatus *InStatus,
1923                   struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
1924                   struct AFSFetchStatus *OutDirStatus,
1925                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
1926 {
1927     return EINVAL;
1928 }
1929
1930 afs_int32
1931 SRXAFS_ResidencyCmd(struct rx_call * acall, struct AFSFid * Fid,
1932                     struct ResidencyCmdInputs * Inputs,
1933                     struct ResidencyCmdOutputs * Outputs)
1934 {
1935     return EINVAL;
1936 }
1937
1938 #ifdef AFS_NT40_ENV
1939 static struct afs_buffer {
1940     struct afs_buffer *next;
1941 } *freeBufferList = 0;
1942 static int afs_buffersAlloced = 0;
1943
1944 static
1945 FreeSendBuffer(register struct afs_buffer *adata)
1946 {
1947     FS_LOCK;
1948     afs_buffersAlloced--;
1949     adata->next = freeBufferList;
1950     freeBufferList = adata;
1951     FS_UNLOCK;
1952     return 0;
1953
1954 }                               /*FreeSendBuffer */
1955
1956 /* allocate space for sender */
1957 static char *
1958 AllocSendBuffer()
1959 {
1960     register struct afs_buffer *tp;
1961
1962     FS_LOCK;
1963     afs_buffersAlloced++;
1964     if (!freeBufferList) {
1965         char *tmp;
1966         FS_UNLOCK;
1967         tmp = malloc(sendBufSize);
1968         if (!tmp) {
1969             ViceLog(0, ("Failed malloc in AllocSendBuffer\n"));
1970             assert(0);
1971         }
1972         return tmp;
1973     }
1974     tp = freeBufferList;
1975     freeBufferList = tp->next;
1976     FS_UNLOCK;
1977     return (char *)tp;
1978
1979 }                               /*AllocSendBuffer */
1980 #endif /* AFS_NT40_ENV */
1981
1982 /*
1983  * This routine returns the status info associated with the targetptr vnode
1984  * in the AFSFetchStatus structure.  Some of the newer fields, such as
1985  * SegSize and Group are not yet implemented
1986  */
1987 static
1988     void
1989 GetStatus(Vnode * targetptr, AFSFetchStatus * status, afs_int32 rights,
1990           afs_int32 anyrights, Vnode * parentptr)
1991 {
1992     /* initialize return status from a vnode  */
1993     status->InterfaceVersion = 1;
1994     status->SyncCounter = status->dataVersionHigh = status->lockCount =
1995         status->errorCode = 0;
1996     status->ResidencyMask = 1;  /* means for MR-AFS: file in /vicepr-partition */
1997     if (targetptr->disk.type == vFile)
1998         status->FileType = File;
1999     else if (targetptr->disk.type == vDirectory)
2000         status->FileType = Directory;
2001     else if (targetptr->disk.type == vSymlink)
2002         status->FileType = SymbolicLink;
2003     else
2004         status->FileType = Invalid;     /*invalid type field */
2005     status->LinkCount = targetptr->disk.linkCount;
2006     {
2007         afs_fsize_t targetLen;
2008         VN_GET_LEN(targetLen, targetptr);
2009         SplitOffsetOrSize(targetLen, status->Length_hi, status->Length);
2010     }
2011     status->DataVersion = targetptr->disk.dataVersion;
2012     status->Author = targetptr->disk.author;
2013     status->Owner = targetptr->disk.owner;
2014     status->CallerAccess = rights;
2015     status->AnonymousAccess = anyrights;
2016     status->UnixModeBits = targetptr->disk.modeBits;
2017     status->ClientModTime = targetptr->disk.unixModifyTime;     /* This might need rework */
2018     status->ParentVnode =
2019         (status->FileType ==
2020          Directory ? targetptr->vnodeNumber : parentptr->vnodeNumber);
2021     status->ParentUnique =
2022         (status->FileType ==
2023          Directory ? targetptr->disk.uniquifier : parentptr->disk.uniquifier);
2024     status->ServerModTime = targetptr->disk.serverModifyTime;
2025     status->Group = targetptr->disk.group;
2026     status->lockCount = targetptr->disk.lock.lockCount;
2027     status->errorCode = 0;
2028
2029 }                               /*GetStatus */
2030
2031 static
2032   afs_int32
2033 common_FetchData64(struct rx_call *acall, struct AFSFid *Fid,
2034                    afs_sfsize_t Pos, afs_sfsize_t Len,
2035                    struct AFSFetchStatus *OutStatus,
2036                    struct AFSCallBack *CallBack, struct AFSVolSync *Sync,
2037                    int type)
2038 {
2039     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2040     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if vptr is a file */
2041     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2042     int errorCode = 0;          /* return code to caller */
2043     int fileCode = 0;           /* return code from vol package */
2044     Volume *volptr = 0;         /* pointer to the volume */
2045     struct client *client = 0;  /* pointer to the client data */
2046     struct rx_connection *tcon; /* the connection we're part of */
2047     struct host *thost;
2048     afs_int32 rights, anyrights;        /* rights for this and any user */
2049     struct client *t_client = NULL;     /* tmp ptr to client data */
2050     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2051 #if FS_STATS_DETAILED
2052     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2053     struct fs_stats_xferData *xferP;    /* Ptr to this op's byte size struct */
2054     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2055     struct timeval xferStartTime, xferStopTime; /* Start/stop times for xfer portion */
2056     struct timeval elapsedTime; /* Transfer time */
2057     afs_sfsize_t bytesToXfer;   /* # bytes to xfer */
2058     afs_sfsize_t bytesXferred;  /* # bytes actually xferred */
2059     int readIdx;                /* Index of read stats array to bump */
2060     static afs_int32 tot_bytesXferred;  /* shared access protected by FS_LOCK */
2061
2062     /*
2063      * Set our stats pointers, remember when the RPC operation started, and
2064      * tally the operation.
2065      */
2066     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHDATA]);
2067     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_FETCHDATA]);
2068     FS_LOCK;
2069     (opP->numOps)++;
2070     FS_UNLOCK;
2071     TM_GetTimeOfDay(&opStartTime, 0);
2072 #endif /* FS_STATS_DETAILED */
2073
2074     ViceLog(1,
2075             ("SRXAFS_FetchData, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2076              Fid->Unique));
2077     FS_LOCK;
2078     AFSCallStats.FetchData++, AFSCallStats.TotalCalls++;
2079     FS_UNLOCK;
2080     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2081         goto Bad_FetchData;
2082
2083     /* Get ptr to client data for user Id for logging */
2084     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2085     logHostAddr.s_addr = rxr_HostOf(tcon);
2086     ViceLog(5,
2087             ("SRXAFS_FetchData, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2088              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2089              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2090     /*
2091      * Get volume/vnode for the fetched file; caller's access rights to
2092      * it are also returned
2093      */
2094     if ((errorCode =
2095          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2096                           &parentwhentargetnotdir, &client, READ_LOCK,
2097                           &rights, &anyrights)))
2098         goto Bad_FetchData;
2099
2100     SetVolumeSync(Sync, volptr);
2101
2102 #if FS_STATS_DETAILED
2103     /*
2104      * Remember that another read operation was performed.
2105      */
2106     FS_LOCK;
2107     if (client->InSameNetwork)
2108         readIdx = VOL_STATS_SAME_NET;
2109     else
2110         readIdx = VOL_STATS_DIFF_NET;
2111     V_stat_reads(volptr, readIdx)++;
2112     if (client->ViceId != AnonymousID) {
2113         V_stat_reads(volptr, readIdx + 1)++;
2114     }
2115     FS_UNLOCK;
2116 #endif /* FS_STATS_DETAILED */
2117     /* Check whether the caller has permission access to fetch the data */
2118     if ((errorCode =
2119          Check_PermissionRights(targetptr, client, rights, CHK_FETCHDATA, 0)))
2120         goto Bad_FetchData;
2121
2122     /*
2123      * Drop the read lock on the parent directory after saving the parent
2124      * vnode information we need to pass to GetStatus
2125      */
2126     if (parentwhentargetnotdir != NULL) {
2127         tparentwhentargetnotdir = *parentwhentargetnotdir;
2128         VPutVnode(&fileCode, parentwhentargetnotdir);
2129         assert(!fileCode || (fileCode == VSALVAGE));
2130         parentwhentargetnotdir = NULL;
2131     }
2132 #if FS_STATS_DETAILED
2133     /*
2134      * Remember when the data transfer started.
2135      */
2136     TM_GetTimeOfDay(&xferStartTime, 0);
2137 #endif /* FS_STATS_DETAILED */
2138
2139     /* actually do the data transfer */
2140 #if FS_STATS_DETAILED
2141     errorCode =
2142         FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type,
2143                           &bytesToXfer, &bytesXferred);
2144 #else
2145     if ((errorCode =
2146          FetchData_RXStyle(volptr, targetptr, acall, Pos, Len, type)))
2147         goto Bad_FetchData;
2148 #endif /* FS_STATS_DETAILED */
2149
2150 #if FS_STATS_DETAILED
2151     /*
2152      * At this point, the data transfer is done, for good or ill.  Remember
2153      * when the transfer ended, bump the number of successes/failures, and
2154      * integrate the transfer size and elapsed time into the stats.  If the
2155      * operation failed, we jump to the appropriate point.
2156      */
2157     TM_GetTimeOfDay(&xferStopTime, 0);
2158     FS_LOCK;
2159     (xferP->numXfers)++;
2160     if (!errorCode) {
2161         (xferP->numSuccesses)++;
2162
2163         /*
2164          * Bump the xfer sum by the number of bytes actually sent, NOT the
2165          * target number.
2166          */
2167         tot_bytesXferred += bytesXferred;
2168         (xferP->sumBytes) += (tot_bytesXferred >> 10);
2169         tot_bytesXferred &= 0x3FF;
2170         if (bytesXferred < xferP->minBytes)
2171             xferP->minBytes = bytesXferred;
2172         if (bytesXferred > xferP->maxBytes)
2173             xferP->maxBytes = bytesXferred;
2174
2175         /*
2176          * Tally the size of the object.  Note: we tally the actual size,
2177          * NOT the number of bytes that made it out over the wire.
2178          */
2179         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
2180             (xferP->count[0])++;
2181         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
2182             (xferP->count[1])++;
2183         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
2184             (xferP->count[2])++;
2185         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
2186             (xferP->count[3])++;
2187         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
2188             (xferP->count[4])++;
2189         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
2190             (xferP->count[5])++;
2191         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
2192             (xferP->count[6])++;
2193         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
2194             (xferP->count[7])++;
2195         else
2196             (xferP->count[8])++;
2197
2198         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
2199         fs_stats_AddTo((xferP->sumTime), elapsedTime);
2200         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
2201         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
2202             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
2203         }
2204         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
2205             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
2206         }
2207     }
2208     FS_UNLOCK;
2209     /*
2210      * Finally, go off to tell our caller the bad news in case the
2211      * fetch failed.
2212      */
2213     if (errorCode)
2214         goto Bad_FetchData;
2215 #endif /* FS_STATS_DETAILED */
2216
2217     /* write back  the OutStatus from the target vnode  */
2218     GetStatus(targetptr, OutStatus, rights, anyrights,
2219               &tparentwhentargetnotdir);
2220
2221     /* if a r/w volume, promise a callback to the caller */
2222     if (VolumeWriteable(volptr))
2223         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2224     else {
2225         struct AFSFid myFid;
2226         memset(&myFid, 0, sizeof(struct AFSFid));
2227         myFid.Volume = Fid->Volume;
2228         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2229     }
2230
2231   Bad_FetchData:
2232     /* Update and store volume/vnode and parent vnodes back */
2233     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2234                            volptr, &client);
2235     ViceLog(2, ("SRXAFS_FetchData returns %d\n", errorCode));
2236     errorCode = CallPostamble(tcon, errorCode, thost);
2237
2238 #if FS_STATS_DETAILED
2239     TM_GetTimeOfDay(&opStopTime, 0);
2240     if (errorCode == 0) {
2241         FS_LOCK;
2242         (opP->numSuccesses)++;
2243         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2244         fs_stats_AddTo((opP->sumTime), elapsedTime);
2245         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2246         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2247             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2248         }
2249         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2250             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2251         }
2252         FS_UNLOCK;
2253     }
2254 #endif /* FS_STATS_DETAILED */
2255
2256     osi_auditU(acall, FetchDataEvent, errorCode, 
2257                AUD_ID, t_client ? t_client->ViceId : 0,
2258                AUD_FID, Fid, AUD_END);
2259     return (errorCode);
2260
2261 }                               /*SRXAFS_FetchData */
2262
2263 afs_int32
2264 SRXAFS_FetchData(struct rx_call * acall, struct AFSFid * Fid, afs_int32 Pos,
2265                  afs_int32 Len, struct AFSFetchStatus * OutStatus,
2266                  struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2267 {
2268     return common_FetchData64(acall, Fid, Pos, Len, OutStatus, CallBack, 
2269                               Sync, 0);
2270 }
2271
2272 afs_int32
2273 SRXAFS_FetchData64(struct rx_call * acall, struct AFSFid * Fid, afs_int64 Pos,
2274                    afs_int64 Len, struct AFSFetchStatus * OutStatus,
2275                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2276 {
2277     int code;
2278     afs_sfsize_t tPos, tLen;
2279
2280 #ifdef AFS_64BIT_ENV
2281 #ifndef AFS_LARGEFILE_ENV
2282     if (Pos + Len > 0x7fffffff)
2283         return EFBIG;
2284 #endif /* !AFS_LARGEFILE_ENV */
2285     tPos = (afs_sfsize_t) Pos;
2286     tLen = (afs_sfsize_t) Len;
2287 #else /* AFS_64BIT_ENV */
2288     if (Pos.high || Len.high)
2289         return EFBIG;
2290     tPos = Pos.low;
2291     tLen = Len.low;
2292 #endif /* AFS_64BIT_ENV */
2293
2294     code =
2295         common_FetchData64(acall, Fid, tPos, tLen, OutStatus, CallBack, Sync,
2296                            1);
2297     return code;
2298 }
2299
2300 afs_int32
2301 SRXAFS_FetchACL(struct rx_call * acall, struct AFSFid * Fid,
2302                 struct AFSOpaque * AccessList,
2303                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
2304 {
2305     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2306     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2307     int errorCode = 0;          /* return error code to caller */
2308     Volume *volptr = 0;         /* pointer to the volume */
2309     struct client *client = 0;  /* pointer to the client data */
2310     afs_int32 rights, anyrights;        /* rights for this and any user */
2311     struct rx_connection *tcon = rx_ConnectionOf(acall);
2312     struct host *thost;
2313     struct client *t_client = NULL;     /* tmp ptr to client data */
2314     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2315 #if FS_STATS_DETAILED
2316     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2317     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2318     struct timeval elapsedTime; /* Transfer time */
2319
2320     /*
2321      * Set our stats pointer, remember when the RPC operation started, and
2322      * tally the operation.
2323      */
2324     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHACL]);
2325     FS_LOCK;
2326     (opP->numOps)++;
2327     FS_UNLOCK;
2328     TM_GetTimeOfDay(&opStartTime, 0);
2329 #endif /* FS_STATS_DETAILED */
2330
2331     ViceLog(1,
2332             ("SAFS_FetchACL, Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2333              Fid->Unique));
2334     FS_LOCK;
2335     AFSCallStats.FetchACL++, AFSCallStats.TotalCalls++;
2336     FS_UNLOCK;
2337     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2338         goto Bad_FetchACL;
2339
2340     /* Get ptr to client data for user Id for logging */
2341     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2342     logHostAddr.s_addr = rxr_HostOf(tcon);
2343     ViceLog(5,
2344             ("SAFS_FetchACL, Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2345              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2346              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2347
2348     AccessList->AFSOpaque_len = 0;
2349     AccessList->AFSOpaque_val = malloc(AFSOPAQUEMAX);
2350     if (!AccessList->AFSOpaque_val) {
2351         ViceLog(0, ("Failed malloc in SRXAFS_FetchACL\n"));
2352         assert(0);
2353     }
2354
2355     /*
2356      * Get volume/vnode for the fetched file; caller's access rights to it
2357      * are also returned
2358      */
2359     if ((errorCode =
2360          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2361                           &parentwhentargetnotdir, &client, READ_LOCK,
2362                           &rights, &anyrights)))
2363         goto Bad_FetchACL;
2364
2365     SetVolumeSync(Sync, volptr);
2366
2367     /* Check whether we have permission to fetch the ACL */
2368     if ((errorCode =
2369          Check_PermissionRights(targetptr, client, rights, CHK_FETCHACL, 0)))
2370         goto Bad_FetchACL;
2371
2372     /* Get the Access List from the dir's vnode */
2373     if ((errorCode =
2374          RXFetch_AccessList(targetptr, parentwhentargetnotdir, AccessList)))
2375         goto Bad_FetchACL;
2376
2377     /* Get OutStatus back From the target Vnode  */
2378     GetStatus(targetptr, OutStatus, rights, anyrights,
2379               parentwhentargetnotdir);
2380
2381   Bad_FetchACL:
2382     /* Update and store volume/vnode and parent vnodes back */
2383     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2384                            volptr, &client);
2385     ViceLog(2,
2386             ("SAFS_FetchACL returns %d (ACL=%s)\n", errorCode,
2387              AccessList->AFSOpaque_val));
2388     errorCode = CallPostamble(tcon, errorCode, thost);
2389
2390 #if FS_STATS_DETAILED
2391     TM_GetTimeOfDay(&opStopTime, 0);
2392     if (errorCode == 0) {
2393         FS_LOCK;
2394         (opP->numSuccesses)++;
2395         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2396         fs_stats_AddTo((opP->sumTime), elapsedTime);
2397         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2398         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2399             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2400         }
2401         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2402             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2403         }
2404         FS_UNLOCK;
2405     }
2406 #endif /* FS_STATS_DETAILED */
2407
2408     osi_auditU(acall, FetchACLEvent, errorCode, 
2409                AUD_ID, t_client ? t_client->ViceId : 0,
2410                AUD_FID, Fid, 
2411                AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
2412     return errorCode;
2413 }                               /*SRXAFS_FetchACL */
2414
2415
2416 /*
2417  * This routine is called exclusively by SRXAFS_FetchStatus(), and should be
2418  * merged into it when possible.
2419  */
2420 static
2421   afs_int32
2422 SAFSS_FetchStatus(struct rx_call *acall, struct AFSFid *Fid,
2423                   struct AFSFetchStatus *OutStatus,
2424                   struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
2425 {
2426     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2427     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2428     int errorCode = 0;          /* return code to caller */
2429     Volume *volptr = 0;         /* pointer to the volume */
2430     struct client *client = 0;  /* pointer to the client data */
2431     afs_int32 rights, anyrights;        /* rights for this and any user */
2432     struct client *t_client = NULL;     /* tmp ptr to client data */
2433     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2434     struct rx_connection *tcon = rx_ConnectionOf(acall);
2435
2436     /* Get ptr to client data for user Id for logging */
2437     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2438     logHostAddr.s_addr = rxr_HostOf(tcon);
2439     ViceLog(1,
2440             ("SAFS_FetchStatus,  Fid = %u.%u.%u, Host %s:%d, Id %d\n",
2441              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2442              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2443     FS_LOCK;
2444     AFSCallStats.FetchStatus++, AFSCallStats.TotalCalls++;
2445     FS_UNLOCK;
2446     /*
2447      * Get volume/vnode for the fetched file; caller's rights to it are
2448      * also returned
2449      */
2450     if ((errorCode =
2451          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
2452                           &parentwhentargetnotdir, &client, READ_LOCK,
2453                           &rights, &anyrights)))
2454         goto Bad_FetchStatus;
2455
2456     /* set volume synchronization information */
2457     SetVolumeSync(Sync, volptr);
2458
2459     /* Are we allowed to fetch Fid's status? */
2460     if (targetptr->disk.type != vDirectory) {
2461         if ((errorCode =
2462              Check_PermissionRights(targetptr, client, rights,
2463                                     CHK_FETCHSTATUS, 0))) {
2464             if (rx_GetCallAbortCode(acall) == errorCode)
2465                 rx_SetCallAbortCode(acall, 0);
2466             goto Bad_FetchStatus;
2467         }
2468     }
2469
2470     /* set OutStatus From the Fid  */
2471     GetStatus(targetptr, OutStatus, rights, anyrights,
2472               parentwhentargetnotdir);
2473
2474     /* If a r/w volume, also set the CallBack state */
2475     if (VolumeWriteable(volptr))
2476         SetCallBackStruct(AddCallBack(client->host, Fid), CallBack);
2477     else {
2478         struct AFSFid myFid;
2479         memset(&myFid, 0, sizeof(struct AFSFid));
2480         myFid.Volume = Fid->Volume;
2481         SetCallBackStruct(AddVolCallBack(client->host, &myFid), CallBack);
2482     }
2483
2484   Bad_FetchStatus:
2485     /* Update and store volume/vnode and parent vnodes back */
2486     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2487                            volptr, &client);
2488     ViceLog(2, ("SAFS_FetchStatus returns %d\n", errorCode));
2489     return errorCode;
2490
2491 }                               /*SAFSS_FetchStatus */
2492
2493
2494 afs_int32
2495 SRXAFS_BulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2496                   struct AFSBulkStats * OutStats, struct AFSCBs * CallBacks,
2497                   struct AFSVolSync * Sync)
2498 {
2499     register int i;
2500     afs_int32 nfiles;
2501     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2502     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2503     int errorCode = 0;          /* return code to caller */
2504     Volume *volptr = 0;         /* pointer to the volume */
2505     struct client *client = 0;  /* pointer to the client data */
2506     afs_int32 rights, anyrights;        /* rights for this and any user */
2507     register struct AFSFid *tfid;       /* file id we're dealing with now */
2508     struct rx_connection *tcon = rx_ConnectionOf(acall);
2509     struct host *thost;
2510     struct client *t_client = NULL;     /* tmp pointer to the client data */
2511 #if FS_STATS_DETAILED
2512     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2513     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2514     struct timeval elapsedTime; /* Transfer time */
2515
2516     /*
2517      * Set our stats pointer, remember when the RPC operation started, and
2518      * tally the operation.
2519      */
2520     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2521     FS_LOCK;
2522     (opP->numOps)++;
2523     FS_UNLOCK;
2524     TM_GetTimeOfDay(&opStartTime, 0);
2525 #endif /* FS_STATS_DETAILED */
2526
2527     ViceLog(1, ("SAFS_BulkStatus\n"));
2528     FS_LOCK;
2529     AFSCallStats.TotalCalls++;
2530     FS_UNLOCK;
2531     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2532     if (nfiles <= 0) {          /* Sanity check */
2533         errorCode = EINVAL;
2534         goto Audit_and_Return;
2535     }
2536
2537     /* allocate space for return output parameters */
2538     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2539         malloc(nfiles * sizeof(struct AFSFetchStatus));
2540     if (!OutStats->AFSBulkStats_val) {
2541         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2542         assert(0);
2543     }
2544     OutStats->AFSBulkStats_len = nfiles;
2545     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2546         malloc(nfiles * sizeof(struct AFSCallBack));
2547     if (!CallBacks->AFSCBs_val) {
2548         ViceLog(0, ("Failed malloc in SRXAFS_BulkStatus\n"));
2549         assert(0);
2550     }
2551     CallBacks->AFSCBs_len = nfiles;
2552
2553     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2554         goto Bad_BulkStatus;
2555
2556     tfid = Fids->AFSCBFids_val;
2557     for (i = 0; i < nfiles; i++, tfid++) {
2558         /*
2559          * Get volume/vnode for the fetched file; caller's rights to it
2560          * are also returned
2561          */
2562         if ((errorCode =
2563              GetVolumePackage(tcon, tfid, &volptr, &targetptr, DONTCHECK,
2564                               &parentwhentargetnotdir, &client, READ_LOCK,
2565                               &rights, &anyrights)))
2566             goto Bad_BulkStatus;
2567         /* set volume synchronization information, but only once per call */
2568         if (i == nfiles)
2569             SetVolumeSync(Sync, volptr);
2570
2571         /* Are we allowed to fetch Fid's status? */
2572         if (targetptr->disk.type != vDirectory) {
2573             if ((errorCode =
2574                  Check_PermissionRights(targetptr, client, rights,
2575                                         CHK_FETCHSTATUS, 0))) {
2576                 if (rx_GetCallAbortCode(acall) == errorCode)
2577                     rx_SetCallAbortCode(acall, 0);
2578                 goto Bad_BulkStatus;
2579             }
2580         }
2581
2582         /* set OutStatus From the Fid  */
2583         GetStatus(targetptr, &OutStats->AFSBulkStats_val[i], rights,
2584                   anyrights, parentwhentargetnotdir);
2585
2586         /* If a r/w volume, also set the CallBack state */
2587         if (VolumeWriteable(volptr))
2588             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2589                               &CallBacks->AFSCBs_val[i]);
2590         else {
2591             struct AFSFid myFid;
2592             memset(&myFid, 0, sizeof(struct AFSFid));
2593             myFid.Volume = tfid->Volume;
2594             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2595                               &CallBacks->AFSCBs_val[i]);
2596         }
2597
2598         /* put back the file ID and volume */
2599         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2600                                volptr, &client);
2601         parentwhentargetnotdir = (Vnode *) 0;
2602         targetptr = (Vnode *) 0;
2603         volptr = (Volume *) 0;
2604         client = (struct client *)0;
2605     }
2606
2607   Bad_BulkStatus:
2608     /* Update and store volume/vnode and parent vnodes back */
2609     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2610                            volptr, &client);
2611     errorCode = CallPostamble(tcon, errorCode, thost);
2612
2613     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2614
2615 #if FS_STATS_DETAILED
2616     TM_GetTimeOfDay(&opStopTime, 0);
2617     if (errorCode == 0) {
2618         FS_LOCK;
2619         (opP->numSuccesses)++;
2620         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2621         fs_stats_AddTo((opP->sumTime), elapsedTime);
2622         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2623         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2624             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2625         }
2626         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2627             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2628         }
2629         FS_UNLOCK;
2630     }
2631 #endif /* FS_STATS_DETAILED */
2632
2633   Audit_and_Return:
2634     ViceLog(2, ("SAFS_BulkStatus        returns %d\n", errorCode));
2635     osi_auditU(acall, BulkFetchStatusEvent, errorCode, 
2636                AUD_ID, t_client ? t_client->ViceId : 0,
2637                AUD_FIDS, Fids, AUD_END);
2638     return errorCode;
2639
2640 }                               /*SRXAFS_BulkStatus */
2641
2642
2643 afs_int32
2644 SRXAFS_InlineBulkStatus(struct rx_call * acall, struct AFSCBFids * Fids,
2645                         struct AFSBulkStats * OutStats,
2646                         struct AFSCBs * CallBacks, struct AFSVolSync * Sync)
2647 {
2648     register int i;
2649     afs_int32 nfiles;
2650     Vnode *targetptr = 0;       /* pointer to vnode to fetch */
2651     Vnode *parentwhentargetnotdir = 0;  /* parent vnode if targetptr is a file */
2652     int errorCode = 0;          /* return code to caller */
2653     Volume *volptr = 0;         /* pointer to the volume */
2654     struct client *client = 0;  /* pointer to the client data */
2655     afs_int32 rights, anyrights;        /* rights for this and any user */
2656     register struct AFSFid *tfid;       /* file id we're dealing with now */
2657     struct rx_connection *tcon;
2658     struct host *thost;
2659     struct client *t_client = NULL;     /* tmp ptr to client data */
2660     AFSFetchStatus *tstatus;
2661 #if FS_STATS_DETAILED
2662     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2663     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2664     struct timeval elapsedTime; /* Transfer time */
2665
2666     /*
2667      * Set our stats pointer, remember when the RPC operation started, and
2668      * tally the operation.
2669      */
2670     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_BULKSTATUS]);
2671     FS_LOCK;
2672     (opP->numOps)++;
2673     FS_UNLOCK;
2674     TM_GetTimeOfDay(&opStartTime, 0);
2675 #endif /* FS_STATS_DETAILED */
2676
2677     ViceLog(1, ("SAFS_InlineBulkStatus\n"));
2678     FS_LOCK;
2679     AFSCallStats.TotalCalls++;
2680     FS_UNLOCK;
2681     nfiles = Fids->AFSCBFids_len;       /* # of files in here */
2682     if (nfiles <= 0) {          /* Sanity check */
2683         errorCode = EINVAL;
2684         goto Audit_and_Return;
2685     }
2686
2687     /* allocate space for return output parameters */
2688     OutStats->AFSBulkStats_val = (struct AFSFetchStatus *)
2689         malloc(nfiles * sizeof(struct AFSFetchStatus));
2690     if (!OutStats->AFSBulkStats_val) {
2691         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2692         assert(0);
2693     }
2694     OutStats->AFSBulkStats_len = nfiles;
2695     CallBacks->AFSCBs_val = (struct AFSCallBack *)
2696         malloc(nfiles * sizeof(struct AFSCallBack));
2697     if (!CallBacks->AFSCBs_val) {
2698         ViceLog(0, ("Failed malloc in SRXAFS_FetchStatus\n"));
2699         assert(0);
2700     }
2701     CallBacks->AFSCBs_len = nfiles;
2702
2703     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))) {
2704         goto Bad_InlineBulkStatus;
2705     }
2706
2707     tfid = Fids->AFSCBFids_val;
2708     for (i = 0; i < nfiles; i++, tfid++) {
2709         /*
2710          * Get volume/vnode for the fetched file; caller's rights to it
2711          * are also returned
2712          */
2713         if ((errorCode =
2714              GetVolumePackage(tcon, tfid, &volptr, &targetptr, DONTCHECK,
2715                               &parentwhentargetnotdir, &client, READ_LOCK,
2716                               &rights, &anyrights))) {
2717             tstatus = &OutStats->AFSBulkStats_val[i];
2718             tstatus->errorCode = errorCode;
2719             PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
2720                              volptr, &client);
2721             parentwhentargetnotdir = (Vnode *) 0;
2722             targetptr = (Vnode *) 0;
2723             volptr = (Volume *) 0;
2724             client = (struct client *)0;
2725             continue;
2726         }
2727
2728         /* set volume synchronization information, but only once per call */
2729         if (i == nfiles)
2730             SetVolumeSync(Sync, volptr);
2731
2732         /* Are we allowed to fetch Fid's status? */
2733         if (targetptr->disk.type != vDirectory) {
2734             if ((errorCode =
2735                  Check_PermissionRights(targetptr, client, rights,
2736                                         CHK_FETCHSTATUS, 0))) {
2737                 tstatus = &OutStats->AFSBulkStats_val[i];
2738                 tstatus->errorCode = errorCode;
2739                 (void)PutVolumePackage(parentwhentargetnotdir, targetptr,
2740                                        (Vnode *) 0, volptr, &client);
2741                 parentwhentargetnotdir = (Vnode *) 0;
2742                 targetptr = (Vnode *) 0;
2743                 volptr = (Volume *) 0;
2744                 client = (struct client *)0;
2745                 continue;
2746             }
2747         }
2748
2749         /* set OutStatus From the Fid  */
2750         GetStatus(targetptr,
2751                   (struct AFSFetchStatus *)&OutStats->AFSBulkStats_val[i],
2752                   rights, anyrights, parentwhentargetnotdir);
2753
2754         /* If a r/w volume, also set the CallBack state */
2755         if (VolumeWriteable(volptr))
2756             SetCallBackStruct(AddBulkCallBack(client->host, tfid),
2757                               &CallBacks->AFSCBs_val[i]);
2758         else {
2759             struct AFSFid myFid;
2760             memset(&myFid, 0, sizeof(struct AFSFid));
2761             myFid.Volume = tfid->Volume;
2762             SetCallBackStruct(AddVolCallBack(client->host, &myFid),
2763                               &CallBacks->AFSCBs_val[i]);
2764         }
2765
2766         /* put back the file ID and volume */
2767         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2768                                volptr, &client);
2769         parentwhentargetnotdir = (Vnode *) 0;
2770         targetptr = (Vnode *) 0;
2771         volptr = (Volume *) 0;
2772         client = (struct client *)0;
2773     }
2774
2775   Bad_InlineBulkStatus:
2776     /* Update and store volume/vnode and parent vnodes back */
2777     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
2778                            volptr, &client);
2779     errorCode = CallPostamble(tcon, errorCode, thost);
2780
2781     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2782
2783 #if FS_STATS_DETAILED
2784     TM_GetTimeOfDay(&opStopTime, 0);
2785     if (errorCode == 0) {
2786         FS_LOCK;
2787         (opP->numSuccesses)++;
2788         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2789         fs_stats_AddTo((opP->sumTime), elapsedTime);
2790         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2791         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2792             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2793         }
2794         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2795             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2796         }
2797         FS_UNLOCK;
2798     }
2799 #endif /* FS_STATS_DETAILED */
2800
2801   Audit_and_Return:
2802     ViceLog(2, ("SAFS_InlineBulkStatus  returns %d\n", errorCode));
2803     osi_auditU(acall, InlineBulkFetchStatusEvent, errorCode, 
2804                AUD_ID, t_client ? t_client->ViceId : 0,
2805                AUD_FIDS, Fids, AUD_END);
2806     return 0;
2807
2808 }                               /*SRXAFS_InlineBulkStatus */
2809
2810
2811 afs_int32
2812 SRXAFS_FetchStatus(struct rx_call * acall, struct AFSFid * Fid,
2813                    struct AFSFetchStatus * OutStatus,
2814                    struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
2815 {
2816     afs_int32 code;
2817     struct rx_connection *tcon;
2818     struct host *thost;
2819     struct client *t_client = NULL;     /* tmp ptr to client data */
2820 #if FS_STATS_DETAILED
2821     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2822     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2823     struct timeval elapsedTime; /* Transfer time */
2824
2825     /*
2826      * Set our stats pointer, remember when the RPC operation started, and
2827      * tally the operation.
2828      */
2829     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_FETCHSTATUS]);
2830     FS_LOCK;
2831     (opP->numOps)++;
2832     FS_UNLOCK;
2833     TM_GetTimeOfDay(&opStartTime, 0);
2834 #endif /* FS_STATS_DETAILED */
2835
2836     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2837         goto Bad_FetchStatus;
2838
2839     code = SAFSS_FetchStatus(acall, Fid, OutStatus, CallBack, Sync);
2840
2841   Bad_FetchStatus:
2842     code = CallPostamble(tcon, code, thost);
2843
2844     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2845
2846 #if FS_STATS_DETAILED
2847     TM_GetTimeOfDay(&opStopTime, 0);
2848     if (code == 0) {
2849         FS_LOCK;
2850         (opP->numSuccesses)++;
2851         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
2852         fs_stats_AddTo((opP->sumTime), elapsedTime);
2853         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
2854         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
2855             fs_stats_TimeAssign((opP->minTime), elapsedTime);
2856         }
2857         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
2858             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
2859         }
2860         FS_UNLOCK;
2861     }
2862 #endif /* FS_STATS_DETAILED */
2863
2864     osi_auditU(acall, FetchStatusEvent, code, 
2865                AUD_ID, t_client ? t_client->ViceId : 0,
2866                AUD_FID, Fid, AUD_END);
2867     return code;
2868
2869 }                               /*SRXAFS_FetchStatus */
2870
2871 static
2872   afs_int32
2873 common_StoreData64(struct rx_call *acall, struct AFSFid *Fid,
2874                    struct AFSStoreStatus *InStatus, afs_fsize_t Pos,
2875                    afs_fsize_t Length, afs_fsize_t FileLength,
2876                    struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
2877 {
2878     Vnode *targetptr = 0;       /* pointer to input fid */
2879     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
2880     Vnode tparentwhentargetnotdir;      /* parent vnode for GetStatus */
2881     int errorCode = 0;          /* return code for caller */
2882     int fileCode = 0;           /* return code from vol package */
2883     Volume *volptr = 0;         /* pointer to the volume header */
2884     struct client *client = 0;  /* pointer to client structure */
2885     afs_int32 rights, anyrights;        /* rights for this and any user */
2886     struct client *t_client = NULL;     /* tmp ptr to client data */
2887     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
2888     struct rx_connection *tcon;
2889     struct host *thost;
2890 #if FS_STATS_DETAILED
2891     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
2892     struct fs_stats_xferData *xferP;    /* Ptr to this op's byte size struct */
2893     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
2894     struct timeval xferStartTime, xferStopTime; /* Start/stop times for xfer portion */
2895     struct timeval elapsedTime; /* Transfer time */
2896     afs_sfsize_t bytesToXfer;   /* # bytes to xfer */
2897     afs_sfsize_t bytesXferred;  /* # bytes actually xfer */
2898     static afs_int32 tot_bytesXferred;  /* shared access protected by FS_LOCK */
2899
2900     /*
2901      * Set our stats pointers, remember when the RPC operation started, and
2902      * tally the operation.
2903      */
2904     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREDATA]);
2905     xferP = &(afs_FullPerfStats.det.xferOpTimes[FS_STATS_XFERIDX_STOREDATA]);
2906     FS_LOCK;
2907     (opP->numOps)++;
2908     FS_UNLOCK;
2909     ViceLog(1,
2910             ("StoreData: Fid = %u.%u.%u\n", Fid->Volume, Fid->Vnode,
2911              Fid->Unique));
2912     TM_GetTimeOfDay(&opStartTime, 0);
2913 #endif /* FS_STATS_DETAILED */
2914
2915     FS_LOCK;
2916     AFSCallStats.StoreData++, AFSCallStats.TotalCalls++;
2917     FS_UNLOCK;
2918     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
2919         goto Bad_StoreData;
2920
2921     /* Get ptr to client data for user Id for logging */
2922     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
2923     logHostAddr.s_addr = rxr_HostOf(tcon);
2924     ViceLog(5,
2925             ("StoreData: Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
2926              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
2927              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
2928
2929     /*
2930      * Get associated volume/vnode for the stored file; caller's rights
2931      * are also returned
2932      */
2933     if ((errorCode =
2934          GetVolumePackage(tcon, Fid, &volptr, &targetptr, MustNOTBeDIR,
2935                           &parentwhentargetnotdir, &client, WRITE_LOCK,
2936                           &rights, &anyrights))) {
2937         goto Bad_StoreData;
2938     }
2939
2940     /* set volume synchronization information */
2941     SetVolumeSync(Sync, volptr);
2942
2943     if ((targetptr->disk.type == vSymlink)) {
2944         /* Should we return a better error code here??? */
2945         errorCode = EISDIR;
2946         goto Bad_StoreData;
2947     }
2948
2949     /* Check if we're allowed to store the data */
2950     if ((errorCode =
2951          Check_PermissionRights(targetptr, client, rights, CHK_STOREDATA,
2952                                 InStatus))) {
2953         goto Bad_StoreData;
2954     }
2955
2956     /*
2957      * Drop the read lock on the parent directory after saving the parent
2958      * vnode information we need to pass to GetStatus
2959      */
2960     if (parentwhentargetnotdir != NULL) {
2961         tparentwhentargetnotdir = *parentwhentargetnotdir;
2962         VPutVnode(&fileCode, parentwhentargetnotdir);
2963         assert(!fileCode || (fileCode == VSALVAGE));
2964         parentwhentargetnotdir = NULL;
2965     }
2966 #if FS_STATS_DETAILED
2967     /*
2968      * Remember when the data transfer started.
2969      */
2970     TM_GetTimeOfDay(&xferStartTime, 0);
2971 #endif /* FS_STATS_DETAILED */
2972
2973     /* Do the actual storing of the data */
2974 #if FS_STATS_DETAILED
2975     errorCode =
2976         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
2977                           FileLength, (InStatus->Mask & AFS_FSYNC),
2978                           &bytesToXfer, &bytesXferred);
2979 #else
2980     errorCode =
2981         StoreData_RXStyle(volptr, targetptr, Fid, client, acall, Pos, Length,
2982                           FileLength, (InStatus->Mask & AFS_FSYNC));
2983     if (errorCode && (!targetptr->changed_newTime))
2984         goto Bad_StoreData;
2985 #endif /* FS_STATS_DETAILED */
2986 #if FS_STATS_DETAILED
2987     /*
2988      * At this point, the data transfer is done, for good or ill.  Remember
2989      * when the transfer ended, bump the number of successes/failures, and
2990      * integrate the transfer size and elapsed time into the stats.  If the
2991      * operation failed, we jump to the appropriate point.
2992      */
2993     TM_GetTimeOfDay(&xferStopTime, 0);
2994     FS_LOCK;
2995     (xferP->numXfers)++;
2996     if (!errorCode) {
2997         (xferP->numSuccesses)++;
2998
2999         /*
3000          * Bump the xfer sum by the number of bytes actually sent, NOT the
3001          * target number.
3002          */
3003         tot_bytesXferred += bytesXferred;
3004         (xferP->sumBytes) += (tot_bytesXferred >> 10);
3005         tot_bytesXferred &= 0x3FF;
3006         if (bytesXferred < xferP->minBytes)
3007             xferP->minBytes = bytesXferred;
3008         if (bytesXferred > xferP->maxBytes)
3009             xferP->maxBytes = bytesXferred;
3010
3011         /*
3012          * Tally the size of the object.  Note: we tally the actual size,
3013          * NOT the number of bytes that made it out over the wire.
3014          */
3015         if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET0)
3016             (xferP->count[0])++;
3017         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET1)
3018             (xferP->count[1])++;
3019         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET2)
3020             (xferP->count[2])++;
3021         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET3)
3022             (xferP->count[3])++;
3023         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET4)
3024             (xferP->count[4])++;
3025         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET5)
3026             (xferP->count[5])++;
3027         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET6)
3028             (xferP->count[6])++;
3029         else if (bytesToXfer <= FS_STATS_MAXBYTES_BUCKET7)
3030             (xferP->count[7])++;
3031         else
3032             (xferP->count[8])++;
3033
3034         fs_stats_GetDiff(elapsedTime, xferStartTime, xferStopTime);
3035         fs_stats_AddTo((xferP->sumTime), elapsedTime);
3036         fs_stats_SquareAddTo((xferP->sqrTime), elapsedTime);
3037         if (fs_stats_TimeLessThan(elapsedTime, (xferP->minTime))) {
3038             fs_stats_TimeAssign((xferP->minTime), elapsedTime);
3039         }
3040         if (fs_stats_TimeGreaterThan(elapsedTime, (xferP->maxTime))) {
3041             fs_stats_TimeAssign((xferP->maxTime), elapsedTime);
3042         }
3043     }
3044     FS_UNLOCK;
3045     /*
3046      * Finally, go off to tell our caller the bad news in case the
3047      * store failed.
3048      */
3049     if (errorCode && (!targetptr->changed_newTime))
3050         goto Bad_StoreData;
3051 #endif /* FS_STATS_DETAILED */
3052
3053     /* Update the status of the target's vnode */
3054     Update_TargetVnodeStatus(targetptr, TVS_SDATA, client, InStatus,
3055                              targetptr, volptr, 0);
3056
3057     /* Get the updated File's status back to the caller */
3058     GetStatus(targetptr, OutStatus, rights, anyrights,
3059               &tparentwhentargetnotdir);
3060
3061   Bad_StoreData:
3062     /* Update and store volume/vnode and parent vnodes back */
3063     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
3064                            volptr, &client);
3065     ViceLog(2, ("SAFS_StoreData returns %d\n", errorCode));
3066
3067     errorCode = CallPostamble(tcon, errorCode, thost);
3068
3069 #if FS_STATS_DETAILED
3070     TM_GetTimeOfDay(&opStopTime, 0);
3071     if (errorCode == 0) {
3072         FS_LOCK;
3073         (opP->numSuccesses)++;
3074         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3075         fs_stats_AddTo((opP->sumTime), elapsedTime);
3076         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3077         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3078             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3079         }
3080         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3081             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3082         }
3083         FS_UNLOCK;
3084     }
3085 #endif /* FS_STATS_DETAILED */
3086     osi_auditU(acall, StoreDataEvent, errorCode, 
3087                AUD_ID, t_client ? t_client->ViceId : 0,
3088                AUD_FID, Fid, AUD_END);
3089     return (errorCode);
3090 }                               /*common_StoreData64 */
3091
3092 afs_int32
3093 SRXAFS_StoreData(struct rx_call * acall, struct AFSFid * Fid,
3094                  struct AFSStoreStatus * InStatus, afs_uint32 Pos,
3095                  afs_uint32 Length, afs_uint32 FileLength,
3096                  struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3097 {
3098     if (FileLength > 0x7fffffff || Pos > 0x7fffffff || 
3099         (0x7fffffff - Pos) < Length)
3100         return EFBIG;
3101
3102     return common_StoreData64(acall, Fid, InStatus, Pos, Length, FileLength,
3103                               OutStatus, Sync);
3104 }                               /*SRXAFS_StoreData */
3105
3106 afs_int32
3107 SRXAFS_StoreData64(struct rx_call * acall, struct AFSFid * Fid,
3108                    struct AFSStoreStatus * InStatus, afs_uint64 Pos,
3109                    afs_uint64 Length, afs_uint64 FileLength,
3110                    struct AFSFetchStatus * OutStatus,
3111                    struct AFSVolSync * Sync)
3112 {
3113     int code;
3114     afs_fsize_t tPos;
3115     afs_fsize_t tLength;
3116     afs_fsize_t tFileLength;
3117
3118 #ifdef AFS_64BIT_ENV
3119 #ifndef AFS_LARGEFILE_ENV
3120     if (FileLength > 0x7fffffff)
3121         return EFBIG;
3122 #endif /* !AFS_LARGEFILE_ENV */
3123     tPos = (afs_fsize_t) Pos;
3124     tLength = (afs_fsize_t) Length;
3125     tFileLength = (afs_fsize_t) FileLength;
3126 #else /* AFS_64BIT_ENV */
3127     if (FileLength.high)
3128         return EFBIG;
3129     tPos = Pos.low;
3130     tLength = Length.low;
3131     tFileLength = FileLength.low;
3132 #endif /* AFS_64BIT_ENV */
3133
3134     code =
3135         common_StoreData64(acall, Fid, InStatus, tPos, tLength, tFileLength,
3136                            OutStatus, Sync);
3137     return code;
3138 }
3139
3140 afs_int32
3141 SRXAFS_StoreACL(struct rx_call * acall, struct AFSFid * Fid,
3142                 struct AFSOpaque * AccessList,
3143                 struct AFSFetchStatus * OutStatus, struct AFSVolSync * Sync)
3144 {
3145     Vnode *targetptr = 0;       /* pointer to input fid */
3146     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3147     int errorCode = 0;          /* return code for caller */
3148     struct AFSStoreStatus InStatus;     /* Input status for fid */
3149     Volume *volptr = 0;         /* pointer to the volume header */
3150     struct client *client = 0;  /* pointer to client structure */
3151     afs_int32 rights, anyrights;        /* rights for this and any user */
3152     struct rx_connection *tcon;
3153     struct host *thost;
3154     struct client *t_client = NULL;     /* tmp ptr to client data */
3155     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3156 #if FS_STATS_DETAILED
3157     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3158     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3159     struct timeval elapsedTime; /* Transfer time */
3160
3161     /*
3162      * Set our stats pointer, remember when the RPC operation started, and
3163      * tally the operation.
3164      */
3165     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STOREACL]);
3166     FS_LOCK;
3167     (opP->numOps)++;
3168     FS_UNLOCK;
3169     TM_GetTimeOfDay(&opStartTime, 0);
3170 #endif /* FS_STATS_DETAILED */
3171     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3172         goto Bad_StoreACL;
3173
3174     /* Get ptr to client data for user Id for logging */
3175     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3176     logHostAddr.s_addr = rxr_HostOf(tcon);
3177     ViceLog(1,
3178             ("SAFS_StoreACL, Fid = %u.%u.%u, ACL=%s, Host %s:%d, Id %d\n",
3179              Fid->Volume, Fid->Vnode, Fid->Unique, AccessList->AFSOpaque_val,
3180              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3181     FS_LOCK;
3182     AFSCallStats.StoreACL++, AFSCallStats.TotalCalls++;
3183     FS_UNLOCK;
3184     InStatus.Mask = 0;          /* not storing any status */
3185
3186     /*
3187      * Get associated volume/vnode for the target dir; caller's rights
3188      * are also returned.
3189      */
3190     if ((errorCode =
3191          GetVolumePackage(tcon, Fid, &volptr, &targetptr, MustBeDIR,
3192                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3193                           &rights, &anyrights))) {
3194         goto Bad_StoreACL;
3195     }
3196
3197     /* set volume synchronization information */
3198     SetVolumeSync(Sync, volptr);
3199
3200     /* Check if we have permission to change the dir's ACL */
3201     if ((errorCode =
3202          Check_PermissionRights(targetptr, client, rights, CHK_STOREACL,
3203                                 &InStatus))) {
3204         goto Bad_StoreACL;
3205     }
3206
3207     /* Build and store the new Access List for the dir */
3208     if ((errorCode = RXStore_AccessList(targetptr, AccessList))) {
3209         goto Bad_StoreACL;
3210     }
3211
3212     targetptr->changed_newTime = 1;     /* status change of directory */
3213
3214     /* convert the write lock to a read lock before breaking callbacks */
3215     VVnodeWriteToRead(&errorCode, targetptr);
3216     assert(!errorCode || errorCode == VSALVAGE);
3217
3218     /* break call backs on the directory  */
3219     BreakCallBack(client->host, Fid, 0);
3220
3221     /* Get the updated dir's status back to the caller */
3222     GetStatus(targetptr, OutStatus, rights, anyrights, 0);
3223
3224   Bad_StoreACL:
3225     /* Update and store volume/vnode and parent vnodes back */
3226     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
3227                      volptr, &client);
3228     ViceLog(2, ("SAFS_StoreACL returns %d\n", errorCode));
3229     errorCode = CallPostamble(tcon, errorCode, thost);
3230
3231 #if FS_STATS_DETAILED
3232     TM_GetTimeOfDay(&opStopTime, 0);
3233     if (errorCode == 0) {
3234         FS_LOCK;
3235         (opP->numSuccesses)++;
3236         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3237         fs_stats_AddTo((opP->sumTime), elapsedTime);
3238         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3239         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3240             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3241         }
3242         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3243             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3244         }
3245         FS_UNLOCK;
3246     }
3247 #endif /* FS_STATS_DETAILED */
3248
3249     osi_auditU(acall, StoreACLEvent, errorCode, 
3250                AUD_ID, t_client ? t_client->ViceId : 0,
3251                AUD_FID, Fid, AUD_ACL, AccessList->AFSOpaque_val, AUD_END);
3252     return errorCode;
3253
3254 }                               /*SRXAFS_StoreACL */
3255
3256
3257 /*
3258  * Note: This routine is called exclusively from SRXAFS_StoreStatus(), and
3259  * should be merged when possible.
3260  */
3261 static afs_int32
3262 SAFSS_StoreStatus(struct rx_call *acall, struct AFSFid *Fid,
3263                   struct AFSStoreStatus *InStatus,
3264                   struct AFSFetchStatus *OutStatus, struct AFSVolSync *Sync)
3265 {
3266     Vnode *targetptr = 0;       /* pointer to input fid */
3267     Vnode *parentwhentargetnotdir = 0;  /* parent of Fid to get ACL */
3268     int errorCode = 0;          /* return code for caller */
3269     Volume *volptr = 0;         /* pointer to the volume header */
3270     struct client *client = 0;  /* pointer to client structure */
3271     afs_int32 rights, anyrights;        /* rights for this and any user */
3272     struct client *t_client = NULL;     /* tmp ptr to client data */
3273     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3274     struct rx_connection *tcon = rx_ConnectionOf(acall);
3275
3276     /* Get ptr to client data for user Id for logging */
3277     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3278     logHostAddr.s_addr = rxr_HostOf(tcon);
3279     ViceLog(1,
3280             ("SAFS_StoreStatus,  Fid    = %u.%u.%u, Host %s:%d, Id %d\n",
3281              Fid->Volume, Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
3282              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3283     FS_LOCK;
3284     AFSCallStats.StoreStatus++, AFSCallStats.TotalCalls++;
3285     FS_UNLOCK;
3286     /*
3287      * Get volume/vnode for the target file; caller's rights to it are
3288      * also returned
3289      */
3290     if ((errorCode =
3291          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
3292                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3293                           &rights, &anyrights))) {
3294         goto Bad_StoreStatus;
3295     }
3296
3297     /* set volume synchronization information */
3298     SetVolumeSync(Sync, volptr);
3299
3300     /* Check if the caller has proper permissions to store status to Fid */
3301     if ((errorCode =
3302          Check_PermissionRights(targetptr, client, rights, CHK_STORESTATUS,
3303                                 InStatus))) {
3304         goto Bad_StoreStatus;
3305     }
3306     /*
3307      * Check for a symbolic link; we can't chmod these (otherwise could
3308      * change a symlink to a mt pt or vice versa)
3309      */
3310     if (targetptr->disk.type == vSymlink && (InStatus->Mask & AFS_SETMODE)) {
3311         errorCode = EINVAL;
3312         goto Bad_StoreStatus;
3313     }
3314
3315     /* Update the status of the target's vnode */
3316     Update_TargetVnodeStatus(targetptr, TVS_SSTATUS, client, InStatus,
3317                              (parentwhentargetnotdir ? parentwhentargetnotdir
3318                               : targetptr), volptr, 0);
3319
3320     /* convert the write lock to a read lock before breaking callbacks */
3321     VVnodeWriteToRead(&errorCode, targetptr);
3322     assert(!errorCode || errorCode == VSALVAGE);
3323
3324     /* Break call backs on Fid */
3325     BreakCallBack(client->host, Fid, 0);
3326
3327     /* Return the updated status back to caller */
3328     GetStatus(targetptr, OutStatus, rights, anyrights,
3329               parentwhentargetnotdir);
3330
3331   Bad_StoreStatus:
3332     /* Update and store volume/vnode and parent vnodes back */
3333     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
3334                      volptr, &client);
3335     ViceLog(2, ("SAFS_StoreStatus returns %d\n", errorCode));
3336     return errorCode;
3337
3338 }                               /*SAFSS_StoreStatus */
3339
3340
3341 afs_int32
3342 SRXAFS_StoreStatus(struct rx_call * acall, struct AFSFid * Fid,
3343                    struct AFSStoreStatus * InStatus,
3344                    struct AFSFetchStatus * OutStatus,
3345                    struct AFSVolSync * Sync)
3346 {
3347     afs_int32 code;
3348     struct rx_connection *tcon;
3349     struct host *thost;
3350     struct client *t_client = NULL;     /* tmp ptr to client data */
3351 #if FS_STATS_DETAILED
3352     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3353     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3354     struct timeval elapsedTime; /* Transfer time */
3355
3356     /*
3357      * Set our stats pointer, remember when the RPC operation started, and
3358      * tally the operation.
3359      */
3360     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_STORESTATUS]);
3361     FS_LOCK;
3362     (opP->numOps)++;
3363     FS_UNLOCK;
3364     TM_GetTimeOfDay(&opStartTime, 0);
3365 #endif /* FS_STATS_DETAILED */
3366
3367     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3368         goto Bad_StoreStatus;
3369
3370     code = SAFSS_StoreStatus(acall, Fid, InStatus, OutStatus, Sync);
3371
3372   Bad_StoreStatus:
3373     code = CallPostamble(tcon, code, thost);
3374
3375     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3376
3377 #if FS_STATS_DETAILED
3378     TM_GetTimeOfDay(&opStopTime, 0);
3379     if (code == 0) {
3380         FS_LOCK;
3381         (opP->numSuccesses)++;
3382         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3383         fs_stats_AddTo((opP->sumTime), elapsedTime);
3384         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3385         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3386             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3387         }
3388         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3389             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3390         }
3391         FS_UNLOCK;
3392     }
3393 #endif /* FS_STATS_DETAILED */
3394
3395     osi_auditU(acall, StoreStatusEvent, code, 
3396                AUD_ID, t_client ? t_client->ViceId : 0,
3397                AUD_FID, Fid, AUD_END);
3398     return code;
3399
3400 }                               /*SRXAFS_StoreStatus */
3401
3402
3403 /*
3404  * This routine is called exclusively by SRXAFS_RemoveFile(), and should be
3405  * merged in when possible.
3406  */
3407 static afs_int32
3408 SAFSS_RemoveFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3409                  struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
3410 {
3411     Vnode *parentptr = 0;       /* vnode of input Directory */
3412     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3413     Vnode *targetptr = 0;       /* file to be deleted */
3414     Volume *volptr = 0;         /* pointer to the volume header */
3415     AFSFid fileFid;             /* area for Fid from the directory */
3416     int errorCode = 0;          /* error code */
3417     DirHandle dir;              /* Handle for dir package I/O */
3418     struct client *client = 0;  /* pointer to client structure */
3419     afs_int32 rights, anyrights;        /* rights for this and any user */
3420     struct client *t_client;    /* tmp ptr to client data */
3421     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3422     struct rx_connection *tcon = rx_ConnectionOf(acall);
3423
3424     FidZero(&dir);
3425     /* Get ptr to client data for user Id for logging */
3426     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3427     logHostAddr.s_addr = rxr_HostOf(tcon);
3428     ViceLog(1,
3429             ("SAFS_RemoveFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3430              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3431              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3432     FS_LOCK;
3433     AFSCallStats.RemoveFile++, AFSCallStats.TotalCalls++;
3434     FS_UNLOCK;
3435     /*
3436      * Get volume/vnode for the parent dir; caller's access rights are
3437      * also returned
3438      */
3439     if ((errorCode =
3440          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
3441                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3442                           &rights, &anyrights))) {
3443         goto Bad_RemoveFile;
3444     }
3445     /* set volume synchronization information */
3446     SetVolumeSync(Sync, volptr);
3447
3448     /* Does the caller has delete (& write) access to the parent directory? */
3449     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
3450         goto Bad_RemoveFile;
3451     }
3452
3453     /* Actually delete the desired file */
3454     if ((errorCode =
3455          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
3456                       MustNOTBeDIR))) {
3457         goto Bad_RemoveFile;
3458     }
3459
3460     /* Update the vnode status of the parent dir */
3461 #if FS_STATS_DETAILED
3462     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3463                              parentptr->disk.linkCount,
3464                              client->InSameNetwork);
3465 #else
3466     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3467                              parentptr->disk.linkCount);
3468 #endif /* FS_STATS_DETAILED */
3469
3470     /* Return the updated parent dir's status back to caller */
3471     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3472
3473     /* Handle internal callback state for the parent and the deleted file */
3474     if (targetptr->disk.linkCount == 0) {
3475         /* no references left, discard entry */
3476         DeleteFileCallBacks(&fileFid);
3477         /* convert the parent lock to a read lock before breaking callbacks */
3478         VVnodeWriteToRead(&errorCode, parentptr);
3479         assert(!errorCode || errorCode == VSALVAGE);
3480     } else {
3481         /* convert the parent lock to a read lock before breaking callbacks */
3482         VVnodeWriteToRead(&errorCode, parentptr);
3483         assert(!errorCode || errorCode == VSALVAGE);
3484         /* convert the target lock to a read lock before breaking callbacks */
3485         VVnodeWriteToRead(&errorCode, targetptr);
3486         assert(!errorCode || errorCode == VSALVAGE);
3487         /* tell all the file has changed */
3488         BreakCallBack(client->host, &fileFid, 1);
3489     }
3490
3491     /* break call back on the directory */
3492     BreakCallBack(client->host, DirFid, 0);
3493
3494   Bad_RemoveFile:
3495     /* Update and store volume/vnode and parent vnodes back */
3496     PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr, 
3497                      volptr, &client);
3498     FidZap(&dir);
3499     ViceLog(2, ("SAFS_RemoveFile returns %d\n", errorCode));
3500     return errorCode;
3501
3502 }                               /*SAFSS_RemoveFile */
3503
3504
3505 afs_int32
3506 SRXAFS_RemoveFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3507                   struct AFSFetchStatus * OutDirStatus,
3508                   struct AFSVolSync * Sync)
3509 {
3510     afs_int32 code;
3511     struct rx_connection *tcon;
3512     struct host *thost;
3513     struct client *t_client = NULL;     /* tmp ptr to client data */
3514 #if FS_STATS_DETAILED
3515     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3516     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3517     struct timeval elapsedTime; /* Transfer time */
3518
3519     /*
3520      * Set our stats pointer, remember when the RPC operation started, and
3521      * tally the operation.
3522      */
3523     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEFILE]);
3524     FS_LOCK;
3525     (opP->numOps)++;
3526     FS_UNLOCK;
3527     TM_GetTimeOfDay(&opStartTime, 0);
3528 #endif /* FS_STATS_DETAILED */
3529
3530     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3531         goto Bad_RemoveFile;
3532
3533     code = SAFSS_RemoveFile(acall, DirFid, Name, OutDirStatus, Sync);
3534
3535   Bad_RemoveFile:
3536     code = CallPostamble(tcon, code, thost);
3537
3538     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3539
3540 #if FS_STATS_DETAILED
3541     TM_GetTimeOfDay(&opStopTime, 0);
3542     if (code == 0) {
3543         FS_LOCK;
3544         (opP->numSuccesses)++;
3545         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3546         fs_stats_AddTo((opP->sumTime), elapsedTime);
3547         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3548         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3549             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3550         }
3551         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3552             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3553         }
3554         FS_UNLOCK;
3555     }
3556 #endif /* FS_STATS_DETAILED */
3557
3558     osi_auditU(acall, RemoveFileEvent, code, 
3559                AUD_ID, t_client ? t_client->ViceId : 0,
3560                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
3561     return code;
3562
3563 }                               /*SRXAFS_RemoveFile */
3564
3565
3566 /*
3567  * This routine is called exclusively from SRXAFS_CreateFile(), and should
3568  * be merged in when possible.
3569  */
3570 static afs_int32
3571 SAFSS_CreateFile(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3572                  struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
3573                  struct AFSFetchStatus *OutFidStatus,
3574                  struct AFSFetchStatus *OutDirStatus,
3575                  struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
3576 {
3577     Vnode *parentptr = 0;       /* vnode of input Directory */
3578     Vnode *targetptr = 0;       /* vnode of the new file */
3579     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3580     Volume *volptr = 0;         /* pointer to the volume header */
3581     int errorCode = 0;          /* error code */
3582     DirHandle dir;              /* Handle for dir package I/O */
3583     struct client *client = 0;  /* pointer to client structure */
3584     afs_int32 rights, anyrights;        /* rights for this and any user */
3585     struct client *t_client;    /* tmp ptr to client data */
3586     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3587     struct rx_connection *tcon = rx_ConnectionOf(acall);
3588
3589     FidZero(&dir);
3590
3591     /* Get ptr to client data for user Id for logging */
3592     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3593     logHostAddr.s_addr = rxr_HostOf(tcon);
3594     ViceLog(1,
3595             ("SAFS_CreateFile %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
3596              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
3597              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3598     FS_LOCK;
3599     AFSCallStats.CreateFile++, AFSCallStats.TotalCalls++;
3600     FS_UNLOCK;
3601     if (!FileNameOK(Name)) {
3602         errorCode = EINVAL;
3603         goto Bad_CreateFile;
3604     }
3605
3606     /*
3607      * Get associated volume/vnode for the parent dir; caller long are
3608      * also returned
3609      */
3610     if ((errorCode =
3611          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
3612                           &parentwhentargetnotdir, &client, WRITE_LOCK,
3613                           &rights, &anyrights))) {
3614         goto Bad_CreateFile;
3615     }
3616
3617     /* set volume synchronization information */
3618     SetVolumeSync(Sync, volptr);
3619
3620     /* Can we write (and insert) onto the parent directory? */
3621     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
3622         goto Bad_CreateFile;
3623     }
3624     /* get a new vnode for the file to be created and set it up */
3625     if ((errorCode =
3626          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
3627                         vFile, nBlocks(0)))) {
3628         goto Bad_CreateFile;
3629     }
3630
3631     /* update the status of the parent vnode */
3632 #if FS_STATS_DETAILED
3633     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3634                              parentptr->disk.linkCount,
3635                              client->InSameNetwork);
3636 #else
3637     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
3638                              parentptr->disk.linkCount);
3639 #endif /* FS_STATS_DETAILED */
3640
3641     /* update the status of the new file's vnode */
3642     Update_TargetVnodeStatus(targetptr, TVS_CFILE, client, InStatus,
3643                              parentptr, volptr, 0);
3644
3645     /* 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 */
3646     GetStatus(targetptr, OutFidStatus, rights | PRSFS_ADMINISTER, anyrights, parentptr);
3647     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
3648
3649     /* convert the write lock to a read lock before breaking callbacks */
3650     VVnodeWriteToRead(&errorCode, parentptr);
3651     assert(!errorCode || errorCode == VSALVAGE);
3652
3653     /* break call back on parent dir */
3654     BreakCallBack(client->host, DirFid, 0);
3655
3656     /* Return a callback promise for the newly created file to the caller */
3657     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
3658
3659   Bad_CreateFile:
3660     /* Update and store volume/vnode and parent vnodes back */
3661     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
3662                            volptr, &client);
3663     FidZap(&dir);
3664     ViceLog(2, ("SAFS_CreateFile returns %d\n", errorCode));
3665     return errorCode;
3666
3667 }                               /*SAFSS_CreateFile */
3668
3669
3670 afs_int32
3671 SRXAFS_CreateFile(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
3672                   struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
3673                   struct AFSFetchStatus * OutFidStatus,
3674                   struct AFSFetchStatus * OutDirStatus,
3675                   struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
3676 {
3677     afs_int32 code;
3678     struct rx_connection *tcon;
3679     struct host *thost;
3680     struct client *t_client = NULL;     /* tmp ptr to client data */
3681 #if FS_STATS_DETAILED
3682     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
3683     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
3684     struct timeval elapsedTime; /* Transfer time */
3685
3686     /*
3687      * Set our stats pointer, remember when the RPC operation started, and
3688      * tally the operation.
3689      */
3690     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CREATEFILE]);
3691     FS_LOCK;
3692     (opP->numOps)++;
3693     FS_UNLOCK;
3694     TM_GetTimeOfDay(&opStartTime, 0);
3695 #endif /* FS_STATS_DETAILED */
3696
3697     memset(OutFid, 0, sizeof(struct AFSFid));
3698
3699     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3700         goto Bad_CreateFile;
3701
3702     code =
3703         SAFSS_CreateFile(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
3704                          OutDirStatus, CallBack, Sync);
3705
3706   Bad_CreateFile:
3707     code = CallPostamble(tcon, code, thost);
3708
3709     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3710
3711 #if FS_STATS_DETAILED
3712     TM_GetTimeOfDay(&opStopTime, 0);
3713     if (code == 0) {
3714         FS_LOCK;
3715         (opP->numSuccesses)++;
3716         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
3717         fs_stats_AddTo((opP->sumTime), elapsedTime);
3718         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
3719         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
3720             fs_stats_TimeAssign((opP->minTime), elapsedTime);
3721         }
3722         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
3723             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
3724         }
3725         FS_UNLOCK;
3726     }
3727 #endif /* FS_STATS_DETAILED */
3728
3729     osi_auditU(acall, CreateFileEvent, code, 
3730                AUD_ID, t_client ? t_client->ViceId : 0,
3731                AUD_FID, DirFid, AUD_STR, Name, AUD_FID, OutFid, AUD_END);
3732     return code;
3733
3734 }                               /*SRXAFS_CreateFile */
3735
3736
3737 /*
3738  * This routine is called exclusively from SRXAFS_Rename(), and should be
3739  * merged in when possible.
3740  */
3741 static afs_int32
3742 SAFSS_Rename(struct rx_call *acall, struct AFSFid *OldDirFid, char *OldName,
3743              struct AFSFid *NewDirFid, char *NewName,
3744              struct AFSFetchStatus *OutOldDirStatus,
3745              struct AFSFetchStatus *OutNewDirStatus, struct AFSVolSync *Sync)
3746 {
3747     Vnode *oldvptr = 0;         /* vnode of the old Directory */
3748     Vnode *newvptr = 0;         /* vnode of the new Directory */
3749     Vnode *fileptr = 0;         /* vnode of the file to move */
3750     Vnode *newfileptr = 0;      /* vnode of the file to delete */
3751     Vnode *testvptr = 0;        /* used in directory tree walk */
3752     Vnode *parent = 0;          /* parent for use in SetAccessList */
3753     int errorCode = 0;          /* error code */
3754     int fileCode = 0;           /* used when writing Vnodes */
3755     VnodeId testnode;           /* used in directory tree walk */
3756     AFSFid fileFid;             /* Fid of file to move */
3757     AFSFid newFileFid;          /* Fid of new file */
3758     DirHandle olddir;           /* Handle for dir package I/O */
3759     DirHandle newdir;           /* Handle for dir package I/O */
3760     DirHandle filedir;          /* Handle for dir package I/O */
3761     DirHandle newfiledir;       /* Handle for dir package I/O */
3762     Volume *volptr = 0;         /* pointer to the volume header */
3763     struct client *client = 0;  /* pointer to client structure */
3764     afs_int32 rights, anyrights;        /* rights for this and any user */
3765     afs_int32 newrights;        /* rights for this user */
3766     afs_int32 newanyrights;     /* rights for any user */
3767     int doDelete;               /* deleted the rename target (ref count now 0) */
3768     int code;
3769     struct client *t_client;    /* tmp ptr to client data */
3770     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3771     struct rx_connection *tcon = rx_ConnectionOf(acall);
3772
3773     FidZero(&olddir);
3774     FidZero(&newdir);
3775     FidZero(&filedir);
3776     FidZero(&newfiledir);
3777
3778     /* Get ptr to client data for user Id for logging */
3779     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3780     logHostAddr.s_addr = rxr_HostOf(tcon);
3781     ViceLog(1,
3782             ("SAFS_Rename %s    to %s,  Fid = %u.%u.%u to %u.%u.%u, Host %s:%d, Id %d\n",
3783              OldName, NewName, OldDirFid->Volume, OldDirFid->Vnode,
3784              OldDirFid->Unique, NewDirFid->Volume, NewDirFid->Vnode,
3785              NewDirFid->Unique, inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
3786     FS_LOCK;
3787     AFSCallStats.Rename++, AFSCallStats.TotalCalls++;
3788     FS_UNLOCK;
3789     if (!FileNameOK(NewName)) {
3790         errorCode = EINVAL;
3791         goto Bad_Rename;
3792     }
3793     if (OldDirFid->Volume != NewDirFid->Volume) {
3794         DFlush();
3795         errorCode = EXDEV;
3796         goto Bad_Rename;
3797     }
3798     if ((strcmp(OldName, ".") == 0) || (strcmp(OldName, "..") == 0)
3799         || (strcmp(NewName, ".") == 0) || (strcmp(NewName, "..") == 0)
3800         || (strlen(NewName) == 0) || (strlen(OldName) == 0)) {
3801         DFlush();
3802         errorCode = EINVAL;
3803         goto Bad_Rename;
3804     }
3805
3806     if (OldDirFid->Vnode <= NewDirFid->Vnode) {
3807         if ((errorCode =
3808              GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr, MustBeDIR,
3809                               &parent, &client, WRITE_LOCK, &rights,
3810                               &anyrights))) {
3811             DFlush();
3812             goto Bad_Rename;
3813         }
3814         if (OldDirFid->Vnode == NewDirFid->Vnode) {
3815             newvptr = oldvptr;
3816             newrights = rights, newanyrights = anyrights;
3817         } else
3818             if ((errorCode =
3819                  GetVolumePackage(tcon, NewDirFid, &volptr, &newvptr,
3820                                   MustBeDIR, &parent, &client, WRITE_LOCK,
3821                                   &newrights, &newanyrights))) {
3822             DFlush();
3823             goto Bad_Rename;
3824         }
3825     } else {
3826         if ((errorCode =
3827              GetVolumePackage(tcon, NewDirFid, &volptr, &newvptr, MustBeDIR,
3828                               &parent, &client, WRITE_LOCK, &newrights,
3829                               &newanyrights))) {
3830             DFlush();
3831             goto Bad_Rename;
3832         }
3833         if ((errorCode =
3834              GetVolumePackage(tcon, OldDirFid, &volptr, &oldvptr, MustBeDIR,
3835                               &parent, &client, WRITE_LOCK, &rights,
3836                               &anyrights))) {
3837             DFlush();
3838             goto Bad_Rename;
3839         }
3840     }
3841
3842     /* set volume synchronization information */
3843     SetVolumeSync(Sync, volptr);
3844
3845     if ((errorCode = CheckWriteMode(oldvptr, rights, PRSFS_DELETE))) {
3846         goto Bad_Rename;
3847     }
3848     if ((errorCode = CheckWriteMode(newvptr, newrights, PRSFS_INSERT))) {
3849         goto Bad_Rename;
3850     }
3851
3852     /* The CopyOnWrite might return ENOSPC ( disk full). Even if the second
3853      *  call to CopyOnWrite returns error, it is not necessary to revert back
3854      *  the effects of the first call because the contents of the volume is 
3855      *  not modified, it is only replicated.
3856      */
3857     if (oldvptr->disk.cloned) {
3858         ViceLog(25, ("Rename : calling CopyOnWrite on  old dir\n"));
3859         if ((errorCode = CopyOnWrite(oldvptr, volptr)))
3860             goto Bad_Rename;
3861     }
3862     SetDirHandle(&olddir, oldvptr);
3863     if (newvptr->disk.cloned) {
3864         ViceLog(25, ("Rename : calling CopyOnWrite on  new dir\n"));
3865         if ((errorCode = CopyOnWrite(newvptr, volptr)))
3866             goto Bad_Rename;
3867     }
3868
3869     SetDirHandle(&newdir, newvptr);
3870
3871     /* Lookup the file to delete its vnode */
3872     if (Lookup(&olddir, OldName, &fileFid)) {
3873         errorCode = ENOENT;
3874         goto Bad_Rename;
3875     }
3876     if (fileFid.Vnode == oldvptr->vnodeNumber
3877         || fileFid.Vnode == newvptr->vnodeNumber) {
3878         errorCode = FSERR_ELOOP;
3879         goto Bad_Rename;
3880     }
3881     fileFid.Volume = V_id(volptr);
3882     fileptr = VGetVnode(&errorCode, volptr, fileFid.Vnode, WRITE_LOCK);
3883     if (errorCode != 0) {
3884         ViceLog(0,
3885                 ("SAFSS_Rename(): Error in VGetVnode() for old file %s, code %d\n",
3886                  OldName, errorCode));
3887         VTakeOffline(volptr);
3888         goto Bad_Rename;
3889     }
3890     if (fileptr->disk.uniquifier != fileFid.Unique) {
3891         ViceLog(0,
3892                 ("SAFSS_Rename(): Old file %s uniquifier mismatch\n",
3893                  OldName));
3894         VTakeOffline(volptr);
3895         errorCode = EIO;
3896         goto Bad_Rename;
3897     }
3898
3899     if (fileptr->disk.type != vDirectory && oldvptr != newvptr
3900         && fileptr->disk.linkCount != 1) {
3901         /*
3902          * Hard links exist to this file - cannot move one of the links to
3903          * a new directory because of AFS restrictions (this is the same
3904          * reason that links cannot be made across directories, i.e.
3905          * access lists)
3906          */
3907         errorCode = EXDEV;
3908         goto Bad_Rename;
3909     }
3910
3911     /* Lookup the new file  */
3912     if (!(Lookup(&newdir, NewName, &newFileFid))) {
3913         if (readonlyServer) {
3914             errorCode = VREADONLY;
3915             goto Bad_Rename;
3916         }
3917         if (!(newrights & PRSFS_DELETE)) {
3918             errorCode = EACCES;
3919             goto Bad_Rename;
3920         }
3921         if (newFileFid.Vnode == oldvptr->vnodeNumber
3922             || newFileFid.Vnode == newvptr->vnodeNumber
3923             || newFileFid.Vnode == fileFid.Vnode) {
3924             errorCode = EINVAL;
3925             goto Bad_Rename;
3926         }
3927         newFileFid.Volume = V_id(volptr);
3928         newfileptr =
3929             VGetVnode(&errorCode, volptr, newFileFid.Vnode, WRITE_LOCK);
3930         if (errorCode != 0) {
3931             ViceLog(0,
3932                     ("SAFSS_Rename(): Error in VGetVnode() for new file %s, code %d\n",
3933                      NewName, errorCode));
3934             VTakeOffline(volptr);
3935             goto Bad_Rename;
3936         }
3937         if (fileptr->disk.uniquifier != fileFid.Unique) {
3938             ViceLog(0,
3939                     ("SAFSS_Rename(): New file %s uniquifier mismatch\n",
3940                      NewName));
3941             VTakeOffline(volptr);
3942             errorCode = EIO;
3943             goto Bad_Rename;
3944         }
3945         SetDirHandle(&newfiledir, newfileptr);
3946         /* Now check that we're moving directories over directories properly, etc.
3947          * return proper POSIX error codes:
3948          * if fileptr is a file and new is a dir: EISDIR.
3949          * if fileptr is a dir and new is a file: ENOTDIR.
3950          * Also, dir to be removed must be empty, of course.
3951          */
3952         if (newfileptr->disk.type == vDirectory) {
3953             if (fileptr->disk.type != vDirectory) {
3954                 errorCode = EISDIR;
3955                 goto Bad_Rename;
3956             }
3957             if ((IsEmpty(&newfiledir))) {
3958                 errorCode = EEXIST;
3959                 goto Bad_Rename;
3960             }
3961         } else {
3962             if (fileptr->disk.type == vDirectory) {
3963                 errorCode = ENOTDIR;
3964                 goto Bad_Rename;
3965             }
3966         }
3967     }
3968
3969     /*
3970      * ok - now we check that the old name is not above new name in the
3971      * directory structure.  This is to prevent removing a subtree alltogether
3972      */
3973     if ((oldvptr != newvptr) && (fileptr->disk.type == vDirectory)) {
3974         afs_int32 forpass = 0, vnum = 0, top = 0;
3975         for (testnode = newvptr->disk.parent; testnode != 0; forpass++) {
3976             if (testnode > vnum) vnum = testnode;
3977             if (forpass > vnum) {
3978                 errorCode = FSERR_ELOOP;
3979                 goto Bad_Rename;
3980             }
3981             if (testnode == oldvptr->vnodeNumber) {
3982                 testnode = oldvptr->disk.parent;
3983                 continue;
3984             }
3985             if ((testnode == fileptr->vnodeNumber)
3986                 || (testnode == newvptr->vnodeNumber)) {
3987                 errorCode = FSERR_ELOOP;
3988                 goto Bad_Rename;
3989             }
3990             if ((newfileptr) && (testnode == newfileptr->vnodeNumber)) {
3991                 errorCode = FSERR_ELOOP;
3992                 goto Bad_Rename;
3993             }
3994             if (testnode == 1) top = 1;
3995             testvptr = VGetVnode(&errorCode, volptr, testnode, READ_LOCK);
3996             assert(errorCode == 0);
3997             testnode = testvptr->disk.parent;
3998             VPutVnode(&errorCode, testvptr);
3999             if ((top == 1) && (testnode != 0)) {
4000                 VTakeOffline(volptr);
4001                 ViceLog(0,
4002                         ("Volume %u now offline, must be salvaged.\n",
4003                          volptr->hashid));
4004                 errorCode = EIO;
4005                 goto Bad_Rename;
4006             }
4007             assert(errorCode == 0);
4008         }
4009     }
4010     /* Do the CopyonWrite first before modifying anything else. Copying is
4011      *  required because we may have to change entries for .. 
4012      */
4013     if ((fileptr->disk.type == vDirectory) && (fileptr->disk.cloned)) {
4014         ViceLog(25, ("Rename : calling CopyOnWrite on  target dir\n"));
4015         if ((errorCode = CopyOnWrite(fileptr, volptr)))
4016             goto Bad_Rename;
4017     }
4018
4019     /* If the new name exists already, delete it and the file it points to */
4020     doDelete = 0;
4021     if (newfileptr) {
4022         /* Delete NewName from its directory */
4023         code = Delete(&newdir, NewName);
4024         assert(code == 0);
4025
4026         /* Drop the link count */
4027         newfileptr->disk.linkCount--;
4028         if (newfileptr->disk.linkCount == 0) {  /* Link count 0 - delete */
4029             afs_fsize_t newSize;
4030             VN_GET_LEN(newSize, newfileptr);
4031             VAdjustDiskUsage((Error *) & errorCode, volptr,
4032                              (afs_sfsize_t) - nBlocks(newSize), 0);
4033             if (VN_GET_INO(newfileptr)) {
4034                 IH_REALLYCLOSE(newfileptr->handle);
4035                 errorCode =
4036                     IH_DEC(V_linkHandle(volptr), VN_GET_INO(newfileptr),
4037                            V_parentId(volptr));
4038                 IH_RELEASE(newfileptr->handle);
4039                 if (errorCode == -1) {
4040                     ViceLog(0,
4041                             ("Del: inode=%s, name=%s, errno=%d\n",
4042                              PrintInode(NULL, VN_GET_INO(newfileptr)),
4043                              NewName, errno));
4044                     if ((errno != ENOENT) && (errno != EIO)
4045                         && (errno != ENXIO))
4046                         ViceLog(0, ("Do we need to fsck?"));
4047                 }
4048             }
4049             VN_SET_INO(newfileptr, (Inode) 0);
4050             newfileptr->delete = 1;     /* Mark NewName vnode to delete */
4051             doDelete = 1;
4052         } else {
4053             /* Link count did not drop to zero.
4054              * Mark NewName vnode as changed - updates stime.
4055              */
4056             newfileptr->changed_newTime = 1;
4057         }
4058     }
4059
4060     /*
4061      * If the create below fails, and the delete above worked, we have
4062      * removed the new name and not replaced it.  This is not very likely,
4063      * but possible.  We could try to put the old file back, but it is
4064      * highly unlikely that it would work since it would involve issuing
4065      * another create.
4066      */
4067     if ((errorCode = Create(&newdir, (char *)NewName, &fileFid)))
4068         goto Bad_Rename;
4069
4070     /* Delete the old name */
4071     assert(Delete(&olddir, (char *)OldName) == 0);
4072
4073     /* if the directory length changes, reflect it in the statistics */
4074 #if FS_STATS_DETAILED
4075     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4076                              oldvptr->disk.linkCount, client->InSameNetwork);
4077     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4078                              newvptr->disk.linkCount, client->InSameNetwork);
4079 #else
4080     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
4081                              oldvptr->disk.linkCount);
4082     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
4083                              newvptr->disk.linkCount);
4084 #endif /* FS_STATS_DETAILED */
4085
4086     if (oldvptr == newvptr)
4087         oldvptr->disk.dataVersion--;    /* Since it was bumped by 2! */
4088
4089     fileptr->disk.parent = newvptr->vnodeNumber;
4090     fileptr->changed_newTime = 1;       /* status change of moved file */
4091
4092     /* if we are dealing with a rename of a directory */
4093     if (fileptr->disk.type == vDirectory) {
4094         assert(!fileptr->disk.cloned);
4095         SetDirHandle(&filedir, fileptr);
4096         /* fix .. to point to the correct place */
4097         Delete(&filedir, ".."); /* No assert--some directories may be bad */
4098         assert(Create(&filedir, "..", NewDirFid) == 0);
4099         fileptr->disk.dataVersion++;
4100         /* if the parent directories are different the link counts have to be   */
4101         /* changed due to .. in the renamed directory */
4102         if (oldvptr != newvptr) {
4103             oldvptr->disk.linkCount--;
4104             newvptr->disk.linkCount++;
4105         }
4106     }
4107
4108     /* set up return status */
4109     GetStatus(oldvptr, OutOldDirStatus, rights, anyrights, 0);
4110     GetStatus(newvptr, OutNewDirStatus, newrights, newanyrights, 0);
4111     if (newfileptr && doDelete) {
4112         DeleteFileCallBacks(&newFileFid);       /* no other references */
4113     }
4114
4115     DFlush();
4116
4117     /* convert the write locks to a read locks before breaking callbacks */
4118     VVnodeWriteToRead(&errorCode, newvptr);
4119     assert(!errorCode || errorCode == VSALVAGE);
4120     if (oldvptr != newvptr) {
4121         VVnodeWriteToRead(&errorCode, oldvptr);
4122         assert(!errorCode || errorCode == VSALVAGE);
4123     }
4124     if (newfileptr && !doDelete) {
4125         /* convert the write lock to a read lock before breaking callbacks */
4126         VVnodeWriteToRead(&errorCode, newfileptr);
4127         assert(!errorCode || errorCode == VSALVAGE);
4128     }
4129
4130     /* break call back on NewDirFid, OldDirFid, NewDirFid and newFileFid  */
4131     BreakCallBack(client->host, NewDirFid, 0);
4132     if (oldvptr != newvptr) {
4133         BreakCallBack(client->host, OldDirFid, 0);
4134         if (fileptr->disk.type == vDirectory)   /* if a dir moved, .. changed */
4135             BreakCallBack(client->host, &fileFid, 0);
4136     }
4137     if (newfileptr) {
4138         /* Note:  it is not necessary to break the callback */
4139         if (doDelete)
4140             DeleteFileCallBacks(&newFileFid);   /* no other references */
4141         else
4142             /* other's still exist (with wrong link count) */
4143             BreakCallBack(client->host, &newFileFid, 1);
4144     }
4145
4146   Bad_Rename:
4147     if (newfileptr) {
4148         VPutVnode(&fileCode, newfileptr);
4149         assert(fileCode == 0);
4150     }
4151     (void)PutVolumePackage(fileptr, (newvptr && newvptr != oldvptr ? 
4152                                      newvptr : 0), oldvptr, volptr, &client);
4153     FidZap(&olddir);
4154     FidZap(&newdir);
4155     FidZap(&filedir);
4156     FidZap(&newfiledir);
4157     ViceLog(2, ("SAFS_Rename returns %d\n", errorCode));
4158     return errorCode;
4159
4160 }                               /*SAFSS_Rename */
4161
4162
4163 afs_int32
4164 SRXAFS_Rename(struct rx_call * acall, struct AFSFid * OldDirFid,
4165               char *OldName, struct AFSFid * NewDirFid, char *NewName,
4166               struct AFSFetchStatus * OutOldDirStatus,
4167               struct AFSFetchStatus * OutNewDirStatus,
4168               struct AFSVolSync * Sync)
4169 {
4170     afs_int32 code;
4171     struct rx_connection *tcon;
4172     struct host *thost;
4173     struct client *t_client = NULL;     /* tmp ptr to client data */
4174 #if FS_STATS_DETAILED
4175     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4176     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4177     struct timeval elapsedTime; /* Transfer time */
4178
4179     /*
4180      * Set our stats pointer, remember when the RPC operation started, and
4181      * tally the operation.
4182      */
4183     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RENAME]);
4184     FS_LOCK;
4185     (opP->numOps)++;
4186     FS_UNLOCK;
4187     TM_GetTimeOfDay(&opStartTime, 0);
4188 #endif /* FS_STATS_DETAILED */
4189
4190     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4191         goto Bad_Rename;
4192
4193     code =
4194         SAFSS_Rename(acall, OldDirFid, OldName, NewDirFid, NewName,
4195                      OutOldDirStatus, OutNewDirStatus, Sync);
4196
4197   Bad_Rename:
4198     code = CallPostamble(tcon, code, thost);
4199
4200     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4201
4202 #if FS_STATS_DETAILED
4203     TM_GetTimeOfDay(&opStopTime, 0);
4204     if (code == 0) {
4205         FS_LOCK;
4206         (opP->numSuccesses)++;
4207         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4208         fs_stats_AddTo((opP->sumTime), elapsedTime);
4209         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4210         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4211             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4212         }
4213         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4214             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4215         }
4216         FS_UNLOCK;
4217     }
4218 #endif /* FS_STATS_DETAILED */
4219
4220     osi_auditU(acall, RenameFileEvent, code, 
4221                AUD_ID, t_client ? t_client->ViceId : 0,
4222                AUD_FID, OldDirFid, AUD_STR, OldName, 
4223                AUD_FID, NewDirFid, AUD_STR, NewName, AUD_END);
4224     return code;
4225
4226 }                               /*SRXAFS_Rename */
4227
4228
4229 /*
4230  * This routine is called exclusively by SRXAFS_Symlink(), and should be
4231  * merged into it when possible.
4232  */
4233 static afs_int32
4234 SAFSS_Symlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4235               char *LinkContents, struct AFSStoreStatus *InStatus,
4236               struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
4237               struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4238 {
4239     Vnode *parentptr = 0;       /* vnode of input Directory */
4240     Vnode *targetptr = 0;       /* vnode of the new link */
4241     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4242     int errorCode = 0;          /* error code */
4243     int len, code = 0;
4244     DirHandle dir;              /* Handle for dir package I/O */
4245     Volume *volptr = 0;         /* pointer to the volume header */
4246     struct client *client = 0;  /* pointer to client structure */
4247     afs_int32 rights, anyrights;        /* rights for this and any user */
4248     struct client *t_client;    /* tmp ptr to client data */
4249     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4250     FdHandle_t *fdP;
4251     struct rx_connection *tcon = rx_ConnectionOf(acall);
4252
4253     FidZero(&dir);
4254
4255     /* Get ptr to client data for user Id for logging */
4256     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4257     logHostAddr.s_addr = rxr_HostOf(tcon);
4258     ViceLog(1,
4259             ("SAFS_Symlink %s to %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4260              LinkContents, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4261              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4262     FS_LOCK;
4263     AFSCallStats.Symlink++, AFSCallStats.TotalCalls++;
4264     FS_UNLOCK;
4265     if (!FileNameOK(Name)) {
4266         errorCode = EINVAL;
4267         goto Bad_SymLink;
4268     }
4269
4270     /*
4271      * Get the vnode and volume for the parent dir along with the caller's
4272      * rights to it
4273      */
4274     if ((errorCode =
4275          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4276                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4277                           &rights, &anyrights))) {
4278         goto Bad_SymLink;
4279     }
4280
4281     /* set volume synchronization information */
4282     SetVolumeSync(Sync, volptr);
4283
4284     /* Does the caller has insert (and write) access to the parent directory? */
4285     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4286         goto Bad_SymLink;
4287     }
4288
4289     /*
4290      * If we're creating a mount point (any x bits clear), we must have
4291      * administer access to the directory, too.  Always allow sysadmins
4292      * to do this.
4293      */
4294     if ((InStatus->Mask & AFS_SETMODE) && !(InStatus->UnixModeBits & 0111)) {
4295         if (readonlyServer) {
4296             errorCode = VREADONLY;
4297             goto Bad_SymLink;
4298         }
4299         /*
4300          * We have a mountpoint, 'cause we're trying to set the Unix mode
4301          * bits to something with some x bits missing (default mode bits
4302          * if AFS_SETMODE is false is 0777)
4303          */
4304         if (VanillaUser(client) && !(rights & PRSFS_ADMINISTER)) {
4305             errorCode = EACCES;
4306             goto Bad_SymLink;
4307         }
4308     }
4309
4310     /* get a new vnode for the symlink and set it up */
4311     if ((errorCode =
4312          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
4313                         vSymlink, nBlocks(strlen((char *)LinkContents))))) {
4314         goto Bad_SymLink;
4315     }
4316
4317     /* update the status of the parent vnode */
4318 #if FS_STATS_DETAILED
4319     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4320                              parentptr->disk.linkCount,
4321                              client->InSameNetwork);
4322 #else
4323     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4324                              parentptr->disk.linkCount);
4325 #endif /* FS_STATS_DETAILED */
4326
4327     /* update the status of the new symbolic link file vnode */
4328     Update_TargetVnodeStatus(targetptr, TVS_SLINK, client, InStatus,
4329                              parentptr, volptr, strlen((char *)LinkContents));
4330
4331     /* Write the contents of the symbolic link name into the target inode */
4332     fdP = IH_OPEN(targetptr->handle);
4333     if (fdP == NULL) {
4334         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4335                                volptr, &client);
4336         VTakeOffline(volptr);
4337         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
4338                     volptr->hashid));
4339         return EIO;
4340     }    
4341     len = strlen((char *) LinkContents);
4342     code = (len == FDH_WRITE(fdP, (char *) LinkContents, len)) ? 0 : VDISKFULL;
4343     if (code) 
4344         ViceLog(0, ("SAFSS_Symlink FDH_WRITE failed for len=%d, Fid=%u.%d.%d\n", len, OutFid->Volume, OutFid->Vnode, OutFid->Unique));
4345     FDH_CLOSE(fdP);
4346     /*
4347      * Set up and return modified status for the parent dir and new symlink
4348      * to caller.
4349      */
4350     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4351     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4352
4353     /* convert the write lock to a read lock before breaking callbacks */
4354     VVnodeWriteToRead(&errorCode, parentptr);
4355     assert(!errorCode || errorCode == VSALVAGE);
4356
4357     /* break call back on the parent dir */
4358     BreakCallBack(client->host, DirFid, 0);
4359
4360   Bad_SymLink:
4361     /* Write the all modified vnodes (parent, new files) and volume back */
4362     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4363                            volptr, &client);
4364     FidZap(&dir);
4365     ViceLog(2, ("SAFS_Symlink returns %d\n", errorCode));
4366     return ( errorCode ? errorCode : code );
4367
4368 }                               /*SAFSS_Symlink */
4369
4370
4371 afs_int32
4372 SRXAFS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4373                OutFidStatus, OutDirStatus, Sync)
4374      struct AFSVolSync *Sync;
4375      struct rx_call *acall;     /* Rx call */
4376      struct AFSFid *DirFid;     /* Parent dir's fid */
4377      char *Name;                /* File name to create */
4378      char *LinkContents;        /* Contents of the new created file */
4379      struct AFSStoreStatus *InStatus;   /* Input status for the new symbolic link */
4380      struct AFSFid *OutFid;     /* Fid for newly created symbolic link */
4381      struct AFSFetchStatus *OutFidStatus;       /* Output status for new symbolic link */
4382      struct AFSFetchStatus *OutDirStatus;       /* Output status for parent dir */
4383
4384 {
4385     afs_int32 code;
4386     struct rx_connection *tcon;
4387     struct host *thost;
4388     struct client *t_client = NULL;     /* tmp ptr to client data */
4389 #if FS_STATS_DETAILED
4390     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4391     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4392     struct timeval elapsedTime; /* Transfer time */
4393
4394     /*
4395      * Set our stats pointer, remember when the RPC operation started, and
4396      * tally the operation.
4397      */
4398     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SYMLINK]);
4399     FS_LOCK;
4400     (opP->numOps)++;
4401     FS_UNLOCK;
4402     TM_GetTimeOfDay(&opStartTime, 0);
4403 #endif /* FS_STATS_DETAILED */
4404
4405     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4406         goto Bad_Symlink;
4407
4408     code =
4409         SAFSS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4410                       OutFidStatus, OutDirStatus, Sync);
4411
4412   Bad_Symlink:
4413     code = CallPostamble(tcon, code, thost);
4414
4415     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4416
4417 #if FS_STATS_DETAILED
4418     TM_GetTimeOfDay(&opStopTime, 0);
4419     if (code == 0) {
4420         FS_LOCK;
4421         (opP->numSuccesses)++;
4422         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4423         fs_stats_AddTo((opP->sumTime), elapsedTime);
4424         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4425         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4426             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4427         }
4428         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4429             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4430         }
4431         FS_UNLOCK;
4432     }
4433 #endif /* FS_STATS_DETAILED */
4434
4435     osi_auditU(acall, SymlinkEvent, code, 
4436                AUD_ID, t_client ? t_client->ViceId : 0, 
4437                AUD_FID, DirFid, AUD_STR, Name,
4438                AUD_FID, OutFid, AUD_STR, LinkContents, AUD_END);
4439     return code;
4440
4441 }                               /*SRXAFS_Symlink */
4442
4443
4444 /*
4445  * This routine is called exclusively by SRXAFS_Link(), and should be
4446  * merged into it when possible.
4447  */
4448 static afs_int32
4449 SAFSS_Link(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4450            struct AFSFid *ExistingFid, 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 file */
4455     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4456     Volume *volptr = 0;         /* pointer to the volume header */
4457     int errorCode = 0;          /* error code */
4458     DirHandle dir;              /* Handle for dir package I/O */
4459     struct client *client = 0;  /* pointer to client structure */
4460     afs_int32 rights, anyrights;        /* rights for this and any user */
4461     struct client *t_client;    /* tmp ptr to client data */
4462     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4463     struct rx_connection *tcon = rx_ConnectionOf(acall);
4464
4465     FidZero(&dir);
4466
4467     /* Get ptr to client data for user Id for logging */
4468     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4469     logHostAddr.s_addr = rxr_HostOf(tcon);
4470     ViceLog(1,
4471             ("SAFS_Link %s,     Did = %u.%u.%u, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
4472              Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4473              ExistingFid->Volume, ExistingFid->Vnode, ExistingFid->Unique,
4474              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4475     FS_LOCK;
4476     AFSCallStats.Link++, AFSCallStats.TotalCalls++;
4477     FS_UNLOCK;
4478     if (DirFid->Volume != ExistingFid->Volume) {
4479         errorCode = EXDEV;
4480         goto Bad_Link;
4481     }
4482     if (!FileNameOK(Name)) {
4483         errorCode = EINVAL;
4484         goto Bad_Link;
4485     }
4486
4487     /*
4488      * Get the vnode and volume for the parent dir along with the caller's
4489      * rights to it
4490      */
4491     if ((errorCode =
4492          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4493                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4494                           &rights, &anyrights))) {
4495         goto Bad_Link;
4496     }
4497
4498     /* set volume synchronization information */
4499     SetVolumeSync(Sync, volptr);
4500
4501     /* Can the caller insert into the parent directory? */
4502     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4503         goto Bad_Link;
4504     }
4505
4506     if (((DirFid->Vnode & 1) && (ExistingFid->Vnode & 1)) || (DirFid->Vnode == ExistingFid->Vnode)) {   /* at present, */
4507         /* AFS fileservers always have directory vnodes that are odd.   */
4508         errorCode = EISDIR;
4509         goto Bad_Link;
4510     }
4511
4512     /* get the file vnode  */
4513     if ((errorCode =
4514          CheckVnode(ExistingFid, &volptr, &targetptr, WRITE_LOCK))) {
4515         goto Bad_Link;
4516     }
4517     if (targetptr->disk.type != vFile) {
4518         errorCode = EISDIR;
4519         goto Bad_Link;
4520     }
4521     if (targetptr->disk.parent != DirFid->Vnode) {
4522         errorCode = EXDEV;
4523         goto Bad_Link;
4524     }
4525     if (parentptr->disk.cloned) {
4526         ViceLog(25, ("Link : calling CopyOnWrite on  target dir\n"));
4527         if ((errorCode = CopyOnWrite(parentptr, volptr)))
4528             goto Bad_Link;      /* disk full error */
4529     }
4530
4531     /* add the name to the directory */
4532     SetDirHandle(&dir, parentptr);
4533     if ((errorCode = Create(&dir, (char *)Name, ExistingFid)))
4534         goto Bad_Link;
4535     DFlush();
4536
4537     /* update the status in the parent vnode */
4538     /**WARNING** --> disk.author SHOULDN'T be modified???? */
4539 #if FS_STATS_DETAILED
4540     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4541                              parentptr->disk.linkCount,
4542                              client->InSameNetwork);
4543 #else
4544     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4545                              parentptr->disk.linkCount);
4546 #endif /* FS_STATS_DETAILED */
4547
4548     targetptr->disk.linkCount++;
4549     targetptr->disk.author = client->ViceId;
4550     targetptr->changed_newTime = 1;     /* Status change of linked-to file */
4551
4552     /* set up return status */
4553     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4554     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4555
4556     /* convert the write locks to read locks before breaking callbacks */
4557     VVnodeWriteToRead(&errorCode, targetptr);
4558     assert(!errorCode || errorCode == VSALVAGE);
4559     VVnodeWriteToRead(&errorCode, parentptr);
4560     assert(!errorCode || errorCode == VSALVAGE);
4561
4562     /* break call back on DirFid */
4563     BreakCallBack(client->host, DirFid, 0);
4564     /*
4565      * We also need to break the callback for the file that is hard-linked since part 
4566      * of its status (like linkcount) is changed
4567      */
4568     BreakCallBack(client->host, ExistingFid, 0);
4569
4570   Bad_Link:
4571     /* Write the all modified vnodes (parent, new files) and volume back */
4572     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4573                            volptr, &client);
4574     FidZap(&dir);
4575     ViceLog(2, ("SAFS_Link returns %d\n", errorCode));
4576     return errorCode;
4577
4578 }                               /*SAFSS_Link */
4579
4580
4581 afs_int32
4582 SRXAFS_Link(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4583             struct AFSFid * ExistingFid, struct AFSFetchStatus * OutFidStatus,
4584             struct AFSFetchStatus * OutDirStatus, struct AFSVolSync * Sync)
4585 {
4586     afs_int32 code;
4587     struct rx_connection *tcon;
4588     struct host *thost;
4589     struct client *t_client = NULL;     /* tmp ptr to client data */
4590 #if FS_STATS_DETAILED
4591     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4592     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4593     struct timeval elapsedTime; /* Transfer time */
4594
4595     /*
4596      * Set our stats pointer, remember when the RPC operation started, and
4597      * tally the operation.
4598      */
4599     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_LINK]);
4600     FS_LOCK;
4601     (opP->numOps)++;
4602     FS_UNLOCK;
4603     TM_GetTimeOfDay(&opStartTime, 0);
4604 #endif /* FS_STATS_DETAILED */
4605
4606     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4607         goto Bad_Link;
4608
4609     code =
4610         SAFSS_Link(acall, DirFid, Name, ExistingFid, OutFidStatus,
4611                    OutDirStatus, Sync);
4612
4613   Bad_Link:
4614     code = CallPostamble(tcon, code, thost);
4615
4616     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4617
4618 #if FS_STATS_DETAILED
4619     TM_GetTimeOfDay(&opStopTime, 0);
4620     if (code == 0) {
4621         FS_LOCK;
4622         (opP->numSuccesses)++;
4623         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4624         fs_stats_AddTo((opP->sumTime), elapsedTime);
4625         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4626         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4627             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4628         }
4629         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4630             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4631         }
4632         FS_UNLOCK;
4633     }
4634 #endif /* FS_STATS_DETAILED */
4635
4636     osi_auditU(acall, LinkEvent, code, 
4637                AUD_ID, t_client ? t_client->ViceId : 0,
4638                AUD_FID, DirFid, AUD_STR, Name,
4639                AUD_FID, ExistingFid, AUD_END);
4640     return code;
4641
4642 }                               /*SRXAFS_Link */
4643
4644
4645 /*
4646  * This routine is called exclusively by SRXAFS_MakeDir(), and should be
4647  * merged into it when possible.
4648  */
4649 static afs_int32
4650 SAFSS_MakeDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4651               struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
4652               struct AFSFetchStatus *OutFidStatus,
4653               struct AFSFetchStatus *OutDirStatus,
4654               struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
4655 {
4656     Vnode *parentptr = 0;       /* vnode of input Directory */
4657     Vnode *targetptr = 0;       /* vnode of the new file */
4658     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4659     Volume *volptr = 0;         /* pointer to the volume header */
4660     int errorCode = 0;          /* error code */
4661     struct acl_accessList *newACL;      /* Access list */
4662     int newACLSize;             /* Size of access list */
4663     DirHandle dir;              /* Handle for dir package I/O */
4664     DirHandle parentdir;        /* Handle for dir package I/O */
4665     struct client *client = 0;  /* pointer to client structure */
4666     afs_int32 rights, anyrights;        /* rights for this and any user */
4667     struct client *t_client;    /* tmp ptr to client data */
4668     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4669     struct rx_connection *tcon = rx_ConnectionOf(acall);
4670
4671     FidZero(&dir);
4672     FidZero(&parentdir);
4673
4674     /* Get ptr to client data for user Id for logging */
4675     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4676     logHostAddr.s_addr = rxr_HostOf(tcon);
4677     ViceLog(1,
4678             ("SAFS_MakeDir %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4679              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4680              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4681     FS_LOCK;
4682     AFSCallStats.MakeDir++, AFSCallStats.TotalCalls++;
4683     FS_UNLOCK;
4684     if (!FileNameOK(Name)) {
4685         errorCode = EINVAL;
4686         goto Bad_MakeDir;
4687     }
4688
4689     /*
4690      * Get the vnode and volume for the parent dir along with the caller's
4691      * rights to it.
4692      */
4693     if ((errorCode =
4694          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4695                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4696                           &rights, &anyrights))) {
4697         goto Bad_MakeDir;
4698     }
4699
4700     /* set volume synchronization information */
4701     SetVolumeSync(Sync, volptr);
4702
4703     /* Write access to the parent directory? */
4704 #ifdef DIRCREATE_NEED_WRITE
4705     /*
4706      * requires w access for the user to create a directory. this
4707      * closes a loophole in the current security arrangement, since a
4708      * user with i access only can create a directory and get the
4709      * implcit a access that goes with dir ownership, and proceed to 
4710      * subvert quota in the volume.
4711      */
4712     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))
4713         || (errorCode = CheckWriteMode(parentptr, rights, PRSFS_WRITE))) {
4714 #else
4715     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4716 #endif /* DIRCREATE_NEED_WRITE */
4717         goto Bad_MakeDir;
4718     }
4719 #define EMPTYDIRBLOCKS 2
4720     /* get a new vnode and set it up */
4721     if ((errorCode =
4722          Alloc_NewVnode(parentptr, &parentdir, volptr, &targetptr, Name,
4723                         OutFid, vDirectory, EMPTYDIRBLOCKS))) {
4724         goto Bad_MakeDir;
4725     }
4726
4727     /* Update the status for the parent dir */
4728 #if FS_STATS_DETAILED
4729     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4730                              parentptr->disk.linkCount + 1,
4731                              client->InSameNetwork);
4732 #else
4733     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4734                              parentptr->disk.linkCount + 1);
4735 #endif /* FS_STATS_DETAILED */
4736
4737     /* Point to target's ACL buffer and copy the parent's ACL contents to it */
4738     assert((SetAccessList
4739             (&targetptr, &volptr, &newACL, &newACLSize,
4740              &parentwhentargetnotdir, (AFSFid *) 0, 0)) == 0);
4741     assert(parentwhentargetnotdir == 0);
4742     memcpy((char *)newACL, (char *)VVnodeACL(parentptr), VAclSize(parentptr));
4743
4744     /* update the status for the target vnode */
4745     Update_TargetVnodeStatus(targetptr, TVS_MKDIR, client, InStatus,
4746                              parentptr, volptr, 0);
4747
4748     /* Actually create the New directory in the directory package */
4749     SetDirHandle(&dir, targetptr);
4750     assert(!(MakeDir(&dir, OutFid, DirFid)));
4751     DFlush();
4752     VN_SET_LEN(targetptr, (afs_fsize_t) Length(&dir));
4753
4754     /* set up return status */
4755     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4756     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4757
4758     /* convert the write lock to a read lock before breaking callbacks */
4759     VVnodeWriteToRead(&errorCode, parentptr);
4760     assert(!errorCode || errorCode == VSALVAGE);
4761
4762     /* break call back on DirFid */
4763     BreakCallBack(client->host, DirFid, 0);
4764
4765     /* Return a callback promise to caller */
4766     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
4767
4768   Bad_MakeDir:
4769     /* Write the all modified vnodes (parent, new files) and volume back */
4770     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4771                            volptr, &client);
4772     FidZap(&dir);
4773     FidZap(&parentdir);
4774     ViceLog(2, ("SAFS_MakeDir returns %d\n", errorCode));
4775     return errorCode;
4776
4777 }                               /*SAFSS_MakeDir */
4778
4779
4780 afs_int32
4781 SRXAFS_MakeDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4782                struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
4783                struct AFSFetchStatus * OutFidStatus,
4784                struct AFSFetchStatus * OutDirStatus,
4785                struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
4786 {
4787     afs_int32 code;
4788     struct rx_connection *tcon;
4789     struct host *thost;
4790     struct client *t_client = NULL;     /* tmp ptr to client data */
4791 #if FS_STATS_DETAILED
4792     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4793     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4794     struct timeval elapsedTime; /* Transfer time */
4795
4796     /*
4797      * Set our stats pointer, remember when the RPC operation started, and
4798      * tally the operation.
4799      */
4800     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_MAKEDIR]);
4801     FS_LOCK;
4802     (opP->numOps)++;
4803     FS_UNLOCK;
4804     TM_GetTimeOfDay(&opStartTime, 0);
4805 #endif /* FS_STATS_DETAILED */
4806     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4807         goto Bad_MakeDir;
4808
4809     code =
4810         SAFSS_MakeDir(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
4811                       OutDirStatus, CallBack, Sync);
4812
4813   Bad_MakeDir:
4814     code = CallPostamble(tcon, code, thost);
4815
4816     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4817
4818 #if FS_STATS_DETAILED
4819     TM_GetTimeOfDay(&opStopTime, 0);
4820     if (code == 0) {
4821         FS_LOCK;
4822         (opP->numSuccesses)++;
4823         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4824         fs_stats_AddTo((opP->sumTime), elapsedTime);
4825         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4826         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4827             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4828         }
4829         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4830             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4831         }
4832         FS_UNLOCK;
4833     }
4834 #endif /* FS_STATS_DETAILED */
4835
4836     osi_auditU(acall, MakeDirEvent, code, 
4837                AUD_ID, t_client ? t_client->ViceId : 0,
4838                AUD_FID, DirFid, AUD_STR, Name,
4839                AUD_FID, OutFid, AUD_END);
4840     return code;
4841
4842 }                               /*SRXAFS_MakeDir */
4843
4844
4845 /*
4846  * This routine is called exclusively by SRXAFS_RemoveDir(), and should be
4847  * merged into it when possible.
4848  */
4849 static afs_int32
4850 SAFSS_RemoveDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4851                 struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4852 {
4853     Vnode *parentptr = 0;       /* vnode of input Directory */
4854     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4855     Vnode *targetptr = 0;       /* file to be deleted */
4856     AFSFid fileFid;             /* area for Fid from the directory */
4857     int errorCode = 0;          /* error code */
4858     DirHandle dir;              /* Handle for dir package I/O */
4859     Volume *volptr = 0;         /* pointer to the volume header */
4860     struct client *client = 0;  /* pointer to client structure */
4861     afs_int32 rights, anyrights;        /* rights for this and any user */
4862     Vnode debugvnode1, debugvnode2;
4863     struct client *t_client;    /* tmp ptr to client data */
4864     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4865     struct rx_connection *tcon = rx_ConnectionOf(acall);
4866
4867     FidZero(&dir);
4868
4869     /* Get ptr to client data for user Id for logging */
4870     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4871     logHostAddr.s_addr = rxr_HostOf(tcon);
4872     ViceLog(1,
4873             ("SAFS_RemoveDir    %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4874              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4875              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4876     FS_LOCK;
4877     AFSCallStats.RemoveDir++, AFSCallStats.TotalCalls++;
4878     FS_UNLOCK;
4879     /*
4880      * Get the vnode and volume for the parent dir along with the caller's
4881      * rights to it
4882      */
4883     if ((errorCode =
4884          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4885                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4886                           &rights, &anyrights))) {
4887         goto Bad_RemoveDir;
4888     }
4889     debugvnode1 = *parentptr;
4890
4891     /* set volume synchronization information */
4892     SetVolumeSync(Sync, volptr);
4893
4894     /* Does the caller has delete (&write) access to the parent dir? */
4895     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
4896         goto Bad_RemoveDir;
4897     }
4898
4899     debugvnode2 = *parentptr;
4900     /* Do the actual delete of the desired (empty) directory, Name */
4901     if ((errorCode =
4902          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
4903                       MustBeDIR))) {
4904         goto Bad_RemoveDir;
4905     }
4906
4907     /* Update the status for the parent dir; link count is also adjusted */
4908 #if FS_STATS_DETAILED
4909     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4910                              parentptr->disk.linkCount - 1,
4911                              client->InSameNetwork);
4912 #else
4913     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4914                              parentptr->disk.linkCount - 1);
4915 #endif /* FS_STATS_DETAILED */
4916
4917     /* Return to the caller the updated parent dir status */
4918     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4919
4920     /*
4921      * Note: it is not necessary to break the callback on fileFid, since
4922      * refcount is now 0, so no one should be able to refer to the dir
4923      * any longer
4924      */
4925     DeleteFileCallBacks(&fileFid);
4926
4927     /* convert the write lock to a read lock before breaking callbacks */
4928     VVnodeWriteToRead(&errorCode, parentptr);
4929     assert(!errorCode || errorCode == VSALVAGE);
4930
4931     /* break call back on DirFid and fileFid */
4932     BreakCallBack(client->host, DirFid, 0);
4933
4934   Bad_RemoveDir:
4935     /* Write the all modified vnodes (parent, new files) and volume back */
4936     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4937                            volptr, &client);
4938     FidZap(&dir);
4939     ViceLog(2, ("SAFS_RemoveDir returns %d\n", errorCode));
4940     return errorCode;
4941
4942 }                               /*SAFSS_RemoveDir */
4943
4944
4945 afs_int32
4946 SRXAFS_RemoveDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4947                  struct AFSFetchStatus * OutDirStatus,
4948                  struct AFSVolSync * Sync)
4949 {
4950     afs_int32 code;
4951     struct rx_connection *tcon;
4952     struct host *thost;
4953     struct client *t_client = NULL;     /* tmp ptr to client data */
4954 #if FS_STATS_DETAILED
4955     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
4956     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
4957     struct timeval elapsedTime; /* Transfer time */
4958
4959     /*
4960      * Set our stats pointer, remember when the RPC operation started, and
4961      * tally the operation.
4962      */
4963     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_REMOVEDIR]);
4964     FS_LOCK;
4965     (opP->numOps)++;
4966     FS_UNLOCK;
4967     TM_GetTimeOfDay(&opStartTime, 0);
4968 #endif /* FS_STATS_DETAILED */
4969
4970     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4971         goto Bad_RemoveDir;
4972
4973     code = SAFSS_RemoveDir(acall, DirFid, Name, OutDirStatus, Sync);
4974
4975   Bad_RemoveDir:
4976     code = CallPostamble(tcon, code, thost);
4977
4978     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4979
4980 #if FS_STATS_DETAILED
4981     TM_GetTimeOfDay(&opStopTime, 0);
4982     if (code == 0) {
4983         FS_LOCK;
4984         (opP->numSuccesses)++;
4985         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
4986         fs_stats_AddTo((opP->sumTime), elapsedTime);
4987         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
4988         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
4989             fs_stats_TimeAssign((opP->minTime), elapsedTime);
4990         }
4991         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
4992             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
4993         }
4994         FS_UNLOCK;
4995     }
4996 #endif /* FS_STATS_DETAILED */
4997
4998     osi_auditU(acall, RemoveDirEvent, code, 
4999                AUD_ID, t_client ? t_client->ViceId : 0,
5000                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
5001     return code;
5002
5003 }                               /*SRXAFS_RemoveDir */
5004
5005
5006 /*
5007  * This routine is called exclusively by SRXAFS_SetLock(), and should be
5008  * merged into it when possible.
5009  */
5010 static afs_int32
5011 SAFSS_SetLock(struct rx_call *acall, struct AFSFid *Fid, ViceLockType type,
5012               struct AFSVolSync *Sync)
5013 {
5014     Vnode *targetptr = 0;       /* vnode of input file */
5015     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5016     int errorCode = 0;          /* error code */
5017     Volume *volptr = 0;         /* pointer to the volume header */
5018     struct client *client = 0;  /* pointer to client structure */
5019     afs_int32 rights, anyrights;        /* rights for this and any user */
5020     struct client *t_client;    /* tmp ptr to client data */
5021     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5022     static char *locktype[4] = { "LockRead", "LockWrite", "LockExtend", "LockRelease" };
5023     struct rx_connection *tcon = rx_ConnectionOf(acall);
5024
5025     if (type != LockRead && type != LockWrite) {
5026         errorCode = EINVAL;
5027         goto Bad_SetLock;
5028     }
5029     /* Get ptr to client data for user Id for logging */
5030     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5031     logHostAddr.s_addr = rxr_HostOf(tcon);
5032     ViceLog(1,
5033             ("SAFS_SetLock type = %s Fid = %u.%u.%u, Host %s:%d, Id %d\n",
5034              locktype[(int)type], Fid->Volume, Fid->Vnode, Fid->Unique,
5035              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5036     FS_LOCK;
5037     AFSCallStats.SetLock++, AFSCallStats.TotalCalls++;
5038     FS_UNLOCK;
5039     /*
5040      * Get the vnode and volume for the desired file along with the caller's
5041      * rights to it
5042      */
5043     if ((errorCode =
5044          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5045                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5046                           &rights, &anyrights))) {
5047         goto Bad_SetLock;
5048     }
5049
5050     /* set volume synchronization information */
5051     SetVolumeSync(Sync, volptr);
5052
5053     /* Handle the particular type of set locking, type */
5054     errorCode = HandleLocking(targetptr, client, rights, type);
5055
5056   Bad_SetLock:
5057     /* Write the all modified vnodes (parent, new files) and volume back */
5058     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5059                            volptr, &client);
5060
5061     if ((errorCode == VREADONLY) && (type == LockRead))
5062         errorCode = 0;          /* allow read locks on RO volumes without saving state */
5063
5064     ViceLog(2, ("SAFS_SetLock returns %d\n", errorCode));
5065     return (errorCode);
5066
5067 }                               /*SAFSS_SetLock */
5068
5069
5070 afs_int32
5071 SRXAFS_OldSetLock(struct rx_call * acall, struct AFSFid * Fid,
5072                   ViceLockType type, struct AFSVolSync * Sync)
5073 {
5074     return SRXAFS_SetLock(acall, Fid, type, Sync);
5075 }                               /*SRXAFS_OldSetLock */
5076
5077
5078 afs_int32
5079 SRXAFS_SetLock(struct rx_call * acall, struct AFSFid * Fid, ViceLockType type,
5080                struct AFSVolSync * Sync)
5081 {
5082     afs_int32 code;
5083     struct rx_connection *tcon;
5084     struct host *thost;
5085     struct client *t_client = NULL;     /* tmp ptr to client data */
5086 #if FS_STATS_DETAILED
5087     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5088     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5089     struct timeval elapsedTime; /* Transfer time */
5090
5091     /*
5092      * Set our stats pointer, remember when the RPC operation started, and
5093      * tally the operation.
5094      */
5095     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETLOCK]);
5096     FS_LOCK;
5097     (opP->numOps)++;
5098     FS_UNLOCK;
5099     TM_GetTimeOfDay(&opStartTime, 0);
5100 #endif /* FS_STATS_DETAILED */
5101
5102     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5103         goto Bad_SetLock;
5104
5105     code = SAFSS_SetLock(acall, Fid, type, Sync);
5106
5107   Bad_SetLock:
5108     code = CallPostamble(tcon, code, thost);
5109
5110     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5111
5112 #if FS_STATS_DETAILED
5113     TM_GetTimeOfDay(&opStopTime, 0);
5114     if (code == 0) {
5115         FS_LOCK;
5116         (opP->numSuccesses)++;
5117         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5118         fs_stats_AddTo((opP->sumTime), elapsedTime);
5119         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5120         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5121             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5122         }
5123         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5124             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5125         }
5126         FS_UNLOCK;
5127     }
5128 #endif /* FS_STATS_DETAILED */
5129
5130     osi_auditU(acall, SetLockEvent, code, 
5131                AUD_ID, t_client ? t_client->ViceId : 0, 
5132                AUD_FID, Fid, AUD_LONG, type, AUD_END);
5133     return code;
5134 }                               /*SRXAFS_SetLock */
5135
5136
5137 /*
5138  * This routine is called exclusively by SRXAFS_ExtendLock(), and should be
5139  * merged into it when possible.
5140  */
5141 static afs_int32
5142 SAFSS_ExtendLock(struct rx_call *acall, struct AFSFid *Fid,
5143                  struct AFSVolSync *Sync)
5144 {
5145     Vnode *targetptr = 0;       /* vnode of input file */
5146     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5147     int errorCode = 0;          /* error code */
5148     Volume *volptr = 0;         /* pointer to the volume header */
5149     struct client *client = 0;  /* pointer to client structure */
5150     afs_int32 rights, anyrights;        /* rights for this and any user */
5151     struct client *t_client;    /* tmp ptr to client data */
5152     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5153     struct rx_connection *tcon = rx_ConnectionOf(acall);
5154
5155     /* Get ptr to client data for user Id for logging */
5156     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5157     logHostAddr.s_addr = rxr_HostOf(tcon);
5158     ViceLog(1,
5159             ("SAFS_ExtendLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5160              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5161              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5162     FS_LOCK;
5163     AFSCallStats.ExtendLock++, AFSCallStats.TotalCalls++;
5164     FS_UNLOCK;
5165     /*
5166      * Get the vnode and volume for the desired file along with the caller's
5167      * rights to it
5168      */
5169     if ((errorCode =
5170          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5171                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5172                           &rights, &anyrights))) {
5173         goto Bad_ExtendLock;
5174     }
5175
5176     /* set volume synchronization information */
5177     SetVolumeSync(Sync, volptr);
5178
5179     /* Handle the actual lock extension */
5180     errorCode = HandleLocking(targetptr, client, rights, LockExtend);
5181
5182   Bad_ExtendLock:
5183     /* Put back file's vnode and volume */
5184     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5185                            volptr, &client);
5186
5187     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5188         errorCode = 0;          /* under our generous policy re RO vols */
5189
5190     ViceLog(2, ("SAFS_ExtendLock returns %d\n", errorCode));
5191     return (errorCode);
5192
5193 }                               /*SAFSS_ExtendLock */
5194
5195
5196 afs_int32
5197 SRXAFS_OldExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5198                      struct AFSVolSync * Sync)
5199 {
5200     return SRXAFS_ExtendLock(acall, Fid, Sync);
5201 }                               /*SRXAFS_OldExtendLock */
5202
5203
5204 afs_int32
5205 SRXAFS_ExtendLock(struct rx_call * acall, struct AFSFid * Fid,
5206                   struct AFSVolSync * Sync)
5207 {
5208     afs_int32 code;
5209     struct rx_connection *tcon;
5210     struct host *thost;
5211     struct client *t_client = NULL;     /* tmp ptr to client data */
5212 #if FS_STATS_DETAILED
5213     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5214     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5215     struct timeval elapsedTime; /* Transfer time */
5216
5217     /*
5218      * Set our stats pointer, remember when the RPC operation started, and
5219      * tally the operation.
5220      */
5221     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_EXTENDLOCK]);
5222     FS_LOCK;
5223     (opP->numOps)++;
5224     FS_UNLOCK;
5225     TM_GetTimeOfDay(&opStartTime, 0);
5226 #endif /* FS_STATS_DETAILED */
5227
5228     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5229         goto Bad_ExtendLock;
5230
5231     code = SAFSS_ExtendLock(acall, Fid, Sync);
5232
5233   Bad_ExtendLock:
5234     code = CallPostamble(tcon, code, thost);
5235
5236     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5237
5238 #if FS_STATS_DETAILED
5239     TM_GetTimeOfDay(&opStopTime, 0);
5240     if (code == 0) {
5241         FS_LOCK;
5242         (opP->numSuccesses)++;
5243         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5244         fs_stats_AddTo((opP->sumTime), elapsedTime);
5245         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5246         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5247             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5248         }
5249         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5250             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5251         }
5252         FS_UNLOCK;
5253     }
5254 #endif /* FS_STATS_DETAILED */
5255
5256     osi_auditU(acall, ExtendLockEvent, code, 
5257                AUD_ID, t_client ? t_client->ViceId : 0,
5258                AUD_FID, Fid, AUD_END);
5259     return code;
5260
5261 }                               /*SRXAFS_ExtendLock */
5262
5263
5264 /*
5265  * This routine is called exclusively by SRXAFS_ReleaseLock(), and should be
5266  * merged into it when possible.
5267  */
5268 static afs_int32
5269 SAFSS_ReleaseLock(struct rx_call *acall, struct AFSFid *Fid,
5270                   struct AFSVolSync *Sync)
5271 {
5272     Vnode *targetptr = 0;       /* vnode of input file */
5273     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
5274     int errorCode = 0;          /* error code */
5275     Volume *volptr = 0;         /* pointer to the volume header */
5276     struct client *client = 0;  /* pointer to client structure */
5277     afs_int32 rights, anyrights;        /* rights for this and any user */
5278     struct client *t_client;    /* tmp ptr to client data */
5279     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
5280     struct rx_connection *tcon = rx_ConnectionOf(acall);
5281
5282     /* Get ptr to client data for user Id for logging */
5283     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5284     logHostAddr.s_addr = rxr_HostOf(tcon);
5285     ViceLog(1,
5286             ("SAFS_ReleaseLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
5287              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
5288              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
5289     FS_LOCK;
5290     AFSCallStats.ReleaseLock++, AFSCallStats.TotalCalls++;
5291     FS_UNLOCK;
5292     /*
5293      * Get the vnode and volume for the desired file along with the caller's
5294      * rights to it
5295      */
5296     if ((errorCode =
5297          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
5298                           &parentwhentargetnotdir, &client, WRITE_LOCK,
5299                           &rights, &anyrights))) {
5300         goto Bad_ReleaseLock;
5301     }
5302
5303     /* set volume synchronization information */
5304     SetVolumeSync(Sync, volptr);
5305
5306     /* Handle the actual lock release */
5307     if ((errorCode = HandleLocking(targetptr, client, rights, LockRelease)))
5308         goto Bad_ReleaseLock;
5309
5310     /* if no more locks left, a callback would be triggered here */
5311     if (targetptr->disk.lock.lockCount <= 0) {
5312         /* convert the write lock to a read lock before breaking callbacks */
5313         VVnodeWriteToRead(&errorCode, targetptr);
5314         assert(!errorCode || errorCode == VSALVAGE);
5315         BreakCallBack(client->host, Fid, 0);
5316     }
5317
5318   Bad_ReleaseLock:
5319     /* Put back file's vnode and volume */
5320     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5321                            volptr, &client);
5322
5323     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
5324         errorCode = 0;          /* under our generous policy re RO vols */
5325
5326     ViceLog(2, ("SAFS_ReleaseLock returns %d\n", errorCode));
5327     return (errorCode);
5328
5329 }                               /*SAFSS_ReleaseLock */
5330
5331
5332 afs_int32
5333 SRXAFS_OldReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5334                       struct AFSVolSync * Sync)
5335 {
5336     return SRXAFS_ReleaseLock(acall, Fid, Sync);
5337 }                               /*SRXAFS_OldReleaseLock */
5338
5339
5340 afs_int32
5341 SRXAFS_ReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
5342                    struct AFSVolSync * Sync)
5343 {
5344     afs_int32 code;
5345     struct rx_connection *tcon;
5346     struct host *thost;
5347     struct client *t_client = NULL;     /* tmp ptr to client data */
5348 #if FS_STATS_DETAILED
5349     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5350     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5351     struct timeval elapsedTime; /* Transfer time */
5352
5353     /*
5354      * Set our stats pointer, remember when the RPC operation started, and
5355      * tally the operation.
5356      */
5357     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_RELEASELOCK]);
5358     FS_LOCK;
5359     (opP->numOps)++;
5360     FS_UNLOCK;
5361     TM_GetTimeOfDay(&opStartTime, 0);
5362 #endif /* FS_STATS_DETAILED */
5363
5364     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5365         goto Bad_ReleaseLock;
5366
5367     code = SAFSS_ReleaseLock(acall, Fid, Sync);
5368
5369   Bad_ReleaseLock:
5370     code = CallPostamble(tcon, code, thost);
5371
5372     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5373
5374 #if FS_STATS_DETAILED
5375     TM_GetTimeOfDay(&opStopTime, 0);
5376     if (code == 0) {
5377         FS_LOCK;
5378         (opP->numSuccesses)++;
5379         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5380         fs_stats_AddTo((opP->sumTime), elapsedTime);
5381         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5382         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5383             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5384         }
5385         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5386             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5387         }
5388         FS_UNLOCK;
5389     }
5390 #endif /* FS_STATS_DETAILED */
5391
5392     osi_auditU(acall, ReleaseLockEvent, code, 
5393                AUD_ID, t_client ? t_client->ViceId : 0, 
5394                AUD_FID, Fid, AUD_END);
5395     return code;
5396
5397 }                               /*SRXAFS_ReleaseLock */
5398
5399
5400 void
5401 SetSystemStats(struct AFSStatistics *stats)
5402 {
5403     /* Fix this sometime soon.. */
5404     /* Because hey, it's not like we have a network monitoring protocol... */
5405     struct timeval time;
5406
5407     /* this works on all system types */
5408     TM_GetTimeOfDay(&time, 0);
5409     stats->CurrentTime = time.tv_sec;
5410 }                               /*SetSystemStats */
5411
5412 void
5413 SetAFSStats(struct AFSStatistics *stats)
5414 {
5415     extern afs_int32 StartTime, CurrentConnections;
5416     int seconds;
5417
5418     FS_LOCK;
5419     stats->CurrentMsgNumber = 0;
5420     stats->OldestMsgNumber = 0;
5421     stats->StartTime = StartTime;
5422     stats->CurrentConnections = CurrentConnections;
5423     stats->TotalAFSCalls = AFSCallStats.TotalCalls;
5424     stats->TotalFetchs =
5425         AFSCallStats.FetchData + AFSCallStats.FetchACL +
5426         AFSCallStats.FetchStatus;
5427     stats->FetchDatas = AFSCallStats.FetchData;
5428     stats->FetchedBytes = AFSCallStats.TotalFetchedBytes;
5429     seconds = AFSCallStats.AccumFetchTime / 1000;
5430     if (seconds <= 0)
5431         seconds = 1;
5432     stats->FetchDataRate = AFSCallStats.TotalFetchedBytes / seconds;
5433     stats->TotalStores =
5434         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5435         AFSCallStats.StoreStatus;
5436     stats->StoreDatas = AFSCallStats.StoreData;
5437     stats->StoredBytes = AFSCallStats.TotalStoredBytes;
5438     seconds = AFSCallStats.AccumStoreTime / 1000;
5439     if (seconds <= 0)
5440         seconds = 1;
5441     stats->StoreDataRate = AFSCallStats.TotalStoredBytes / seconds;
5442 #ifdef AFS_NT40_ENV
5443     stats->ProcessSize = -1;    /* TODO: */
5444 #else
5445     stats->ProcessSize = (afs_int32) ((long)sbrk(0) >> 10);
5446 #endif
5447     FS_UNLOCK;
5448     h_GetWorkStats((int *)&(stats->WorkStations),
5449                    (int *)&(stats->ActiveWorkStations), (int *)0,
5450                    (afs_int32) (FT_ApproxTime()) - (15 * 60));
5451
5452 }                               /*SetAFSStats */
5453
5454 /* Get disk related information from all AFS partitions. */
5455
5456 void
5457 SetVolumeStats(struct AFSStatistics *stats)
5458 {
5459     struct DiskPartition *part;
5460     int i = 0;
5461
5462     for (part = DiskPartitionList; part && i < AFS_MSTATDISKS;
5463          part = part->next) {
5464         stats->Disks[i].TotalBlocks = part->totalUsable;
5465         stats->Disks[i].BlocksAvailable = part->free;
5466         memset(stats->Disks[i].Name, 0, AFS_DISKNAMESIZE);
5467         strncpy(stats->Disks[i].Name, part->name, AFS_DISKNAMESIZE);
5468         i++;
5469     }
5470     while (i < AFS_MSTATDISKS) {
5471         stats->Disks[i].TotalBlocks = -1;
5472         i++;
5473     }
5474 }                               /*SetVolumeStats */
5475
5476 afs_int32
5477 SRXAFS_GetStatistics(struct rx_call *acall, struct ViceStatistics *Statistics)
5478 {
5479     afs_int32 code;
5480     struct rx_connection *tcon = rx_ConnectionOf(acall);
5481     struct host *thost;
5482     struct client *t_client = NULL;     /* tmp ptr to client data */
5483 #if FS_STATS_DETAILED
5484     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5485     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5486     struct timeval elapsedTime; /* Transfer time */
5487
5488     /*
5489      * Set our stats pointer, remember when the RPC operation started, and
5490      * tally the operation.
5491      */
5492     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETSTATISTICS]);
5493     FS_LOCK;
5494     (opP->numOps)++;
5495     FS_UNLOCK;
5496     TM_GetTimeOfDay(&opStartTime, 0);
5497 #endif /* FS_STATS_DETAILED */
5498
5499     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5500         goto Bad_GetStatistics;
5501
5502     ViceLog(1, ("SAFS_GetStatistics Received\n"));
5503     FS_LOCK;
5504     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5505     FS_UNLOCK;
5506     memset(Statistics, 0, sizeof(*Statistics));
5507     SetAFSStats((struct AFSStatistics *)Statistics);
5508     SetVolumeStats((struct AFSStatistics *)Statistics);
5509     SetSystemStats((struct AFSStatistics *)Statistics);
5510
5511   Bad_GetStatistics:
5512     code = CallPostamble(tcon, code, thost);
5513
5514     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5515
5516 #if FS_STATS_DETAILED
5517     TM_GetTimeOfDay(&opStopTime, 0);
5518     if (code == 0) {
5519         FS_LOCK;
5520         (opP->numSuccesses)++;
5521         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5522         fs_stats_AddTo((opP->sumTime), elapsedTime);
5523         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5524         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5525             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5526         }
5527         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5528             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5529         }
5530         FS_UNLOCK;
5531     }
5532 #endif /* FS_STATS_DETAILED */
5533
5534     osi_auditU(acall, GetStatisticsEvent, code, 
5535                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5536     return code;
5537 }                               /*SRXAFS_GetStatistics */
5538
5539
5540 /*------------------------------------------------------------------------
5541  * EXPORTED SRXAFS_XStatsVersion
5542  *
5543  * Description:
5544  *      Routine called by the server-side RPC interface to implement
5545  *      pulling out the xstat version number for the File Server.
5546  *
5547  * Arguments:
5548  *      a_versionP : Ptr to the version number variable to set.
5549  *
5550  * Returns:
5551  *      0 (always)
5552  *
5553  * Environment:
5554  *      Nothing interesting.
5555  *
5556  * Side Effects:
5557  *      As advertised.
5558  *------------------------------------------------------------------------*/
5559
5560 afs_int32
5561 SRXAFS_XStatsVersion(struct rx_call * a_call, afs_int32 * a_versionP)
5562 {                               /*SRXAFS_XStatsVersion */
5563
5564     struct client *t_client = NULL;     /* tmp ptr to client data */
5565     struct rx_connection *tcon = rx_ConnectionOf(a_call);
5566 #if FS_STATS_DETAILED
5567     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5568     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5569     struct timeval elapsedTime; /* Transfer time */
5570
5571     /*
5572      * Set our stats pointer, remember when the RPC operation started, and
5573      * tally the operation.
5574      */
5575     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_XSTATSVERSION]);
5576     FS_LOCK;
5577     (opP->numOps)++;
5578     FS_UNLOCK;
5579     TM_GetTimeOfDay(&opStartTime, 0);
5580 #endif /* FS_STATS_DETAILED */
5581
5582     *a_versionP = AFS_XSTAT_VERSION;
5583
5584     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5585
5586 #if FS_STATS_DETAILED
5587     TM_GetTimeOfDay(&opStopTime, 0);
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_LOCK;
5598     (opP->numSuccesses)++;
5599     FS_UNLOCK;
5600 #endif /* FS_STATS_DETAILED */
5601
5602     osi_auditU(a_call, XStatsVersionEvent, 0, 
5603                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5604     return (0);
5605 }                               /*SRXAFS_XStatsVersion */
5606
5607
5608 /*------------------------------------------------------------------------
5609  * PRIVATE FillPerfValues
5610  *
5611  * Description:
5612  *      Routine called to fill a regular performance data structure.
5613  *
5614  * Arguments:
5615  *      a_perfP : Ptr to perf structure to fill
5616  *
5617  * Returns:
5618  *      Nothing.
5619  *
5620  * Environment:
5621  *      Various collections need this info, so the guts were put in
5622  *      this separate routine.
5623  *
5624  * Side Effects:
5625  *      As advertised.
5626  *------------------------------------------------------------------------*/
5627
5628 static void
5629 FillPerfValues(struct afs_PerfStats *a_perfP)
5630 {                               /*FillPerfValues */
5631     afs_uint32 hi, lo;
5632     int dir_Buffers;            /*# buffers in use by dir package */
5633     int dir_Calls;              /*# read calls in dir package */
5634     int dir_IOs;                /*# I/O ops in dir package */
5635
5636     /*
5637      * Vnode cache section.
5638      */
5639     a_perfP->vcache_L_Entries = VnodeClassInfo[vLarge].cacheSize;
5640     a_perfP->vcache_L_Allocs = VnodeClassInfo[vLarge].allocs;
5641     a_perfP->vcache_L_Gets = VnodeClassInfo[vLarge].gets;
5642     a_perfP->vcache_L_Reads = VnodeClassInfo[vLarge].reads;
5643     a_perfP->vcache_L_Writes = VnodeClassInfo[vLarge].writes;
5644     a_perfP->vcache_S_Entries = VnodeClassInfo[vSmall].cacheSize;
5645     a_perfP->vcache_S_Allocs = VnodeClassInfo[vSmall].allocs;
5646     a_perfP->vcache_S_Gets = VnodeClassInfo[vSmall].gets;
5647     a_perfP->vcache_S_Reads = VnodeClassInfo[vSmall].reads;
5648     a_perfP->vcache_S_Writes = VnodeClassInfo[vSmall].writes;
5649     a_perfP->vcache_H_Entries = VStats.hdr_cache_size;
5650     SplitInt64(VStats.hdr_gets, hi, lo);
5651     a_perfP->vcache_H_Gets = lo;
5652     SplitInt64(VStats.hdr_loads, hi, lo);
5653     a_perfP->vcache_H_Replacements = lo;
5654
5655     /*
5656      * Directory section.
5657      */
5658     DStat(&dir_Buffers, &dir_Calls, &dir_IOs);
5659     a_perfP->dir_Buffers = (afs_int32) dir_Buffers;
5660     a_perfP->dir_Calls = (afs_int32) dir_Calls;
5661     a_perfP->dir_IOs = (afs_int32) dir_IOs;
5662
5663     /*
5664      * Rx section.
5665      */
5666     a_perfP->rx_packetRequests = (afs_int32) rx_stats.packetRequests;
5667     a_perfP->rx_noPackets_RcvClass =
5668         (afs_int32) rx_stats.receivePktAllocFailures;
5669     a_perfP->rx_noPackets_SendClass =
5670         (afs_int32) rx_stats.sendPktAllocFailures;
5671     a_perfP->rx_noPackets_SpecialClass =
5672         (afs_int32) rx_stats.specialPktAllocFailures;
5673     a_perfP->rx_socketGreedy = (afs_int32) rx_stats.socketGreedy;
5674     a_perfP->rx_bogusPacketOnRead = (afs_int32) rx_stats.bogusPacketOnRead;
5675     a_perfP->rx_bogusHost = (afs_int32) rx_stats.bogusHost;
5676     a_perfP->rx_noPacketOnRead = (afs_int32) rx_stats.noPacketOnRead;
5677     a_perfP->rx_noPacketBuffersOnRead =
5678         (afs_int32) rx_stats.noPacketBuffersOnRead;
5679     a_perfP->rx_selects = (afs_int32) rx_stats.selects;
5680     a_perfP->rx_sendSelects = (afs_int32) rx_stats.sendSelects;
5681     a_perfP->rx_packetsRead_RcvClass =
5682         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_RECEIVE];
5683     a_perfP->rx_packetsRead_SendClass =
5684         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SEND];
5685     a_perfP->rx_packetsRead_SpecialClass =
5686         (afs_int32) rx_stats.packetsRead[RX_PACKET_CLASS_SPECIAL];
5687     a_perfP->rx_dataPacketsRead = (afs_int32) rx_stats.dataPacketsRead;
5688     a_perfP->rx_ackPacketsRead = (afs_int32) rx_stats.ackPacketsRead;
5689     a_perfP->rx_dupPacketsRead = (afs_int32) rx_stats.dupPacketsRead;
5690     a_perfP->rx_spuriousPacketsRead =
5691         (afs_int32) rx_stats.spuriousPacketsRead;
5692     a_perfP->rx_packetsSent_RcvClass =
5693         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_RECEIVE];
5694     a_perfP->rx_packetsSent_SendClass =
5695         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SEND];
5696     a_perfP->rx_packetsSent_SpecialClass =
5697         (afs_int32) rx_stats.packetsSent[RX_PACKET_CLASS_SPECIAL];
5698     a_perfP->rx_ackPacketsSent = (afs_int32) rx_stats.ackPacketsSent;
5699     a_perfP->rx_pingPacketsSent = (afs_int32) rx_stats.pingPacketsSent;
5700     a_perfP->rx_abortPacketsSent = (afs_int32) rx_stats.abortPacketsSent;
5701     a_perfP->rx_busyPacketsSent = (afs_int32) rx_stats.busyPacketsSent;
5702     a_perfP->rx_dataPacketsSent = (afs_int32) rx_stats.dataPacketsSent;
5703     a_perfP->rx_dataPacketsReSent = (afs_int32) rx_stats.dataPacketsReSent;
5704     a_perfP->rx_dataPacketsPushed = (afs_int32) rx_stats.dataPacketsPushed;
5705     a_perfP->rx_ignoreAckedPacket = (afs_int32) rx_stats.ignoreAckedPacket;
5706     a_perfP->rx_totalRtt_Sec = (afs_int32) rx_stats.totalRtt.sec;
5707     a_perfP->rx_totalRtt_Usec = (afs_int32) rx_stats.totalRtt.usec;
5708     a_perfP->rx_minRtt_Sec = (afs_int32) rx_stats.minRtt.sec;
5709     a_perfP->rx_minRtt_Usec = (afs_int32) rx_stats.minRtt.usec;
5710     a_perfP->rx_maxRtt_Sec = (afs_int32) rx_stats.maxRtt.sec;
5711     a_perfP->rx_maxRtt_Usec = (afs_int32) rx_stats.maxRtt.usec;
5712     a_perfP->rx_nRttSamples = (afs_int32) rx_stats.nRttSamples;
5713     a_perfP->rx_nServerConns = (afs_int32) rx_stats.nServerConns;
5714     a_perfP->rx_nClientConns = (afs_int32) rx_stats.nClientConns;
5715     a_perfP->rx_nPeerStructs = (afs_int32) rx_stats.nPeerStructs;
5716     a_perfP->rx_nCallStructs = (afs_int32) rx_stats.nCallStructs;
5717     a_perfP->rx_nFreeCallStructs = (afs_int32) rx_stats.nFreeCallStructs;
5718
5719     a_perfP->host_NumHostEntries = HTs;
5720     a_perfP->host_HostBlocks = HTBlocks;
5721     h_GetHostNetStats(&(a_perfP->host_NonDeletedHosts),
5722                       &(a_perfP->host_HostsInSameNetOrSubnet),
5723                       &(a_perfP->host_HostsInDiffSubnet),
5724                       &(a_perfP->host_HostsInDiffNetwork));
5725     a_perfP->host_NumClients = CEs;
5726     a_perfP->host_ClientBlocks = CEBlocks;
5727
5728     a_perfP->sysname_ID = afs_perfstats.sysname_ID;
5729     a_perfP->rx_nBusies = (afs_int32) rx_stats.nBusies;
5730     a_perfP->fs_nBusies = afs_perfstats.fs_nBusies;
5731 }                               /*FillPerfValues */
5732
5733
5734 /*------------------------------------------------------------------------
5735  * EXPORTED SRXAFS_GetXStats
5736  *
5737  * Description:
5738  *      Routine called by the server-side callback RPC interface to
5739  *      implement getting the given data collection from the extended
5740  *      File Server statistics.
5741  *
5742  * Arguments:
5743  *      a_call              : Ptr to Rx call on which this request came in.
5744  *      a_clientVersionNum  : Client version number.
5745  *      a_opCode            : Desired operation.
5746  *      a_serverVersionNumP : Ptr to version number to set.
5747  *      a_timeP             : Ptr to time value (seconds) to set.
5748  *      a_dataP             : Ptr to variable array structure to return
5749  *                            stuff in.
5750  *
5751  * Returns:
5752  *      0 (always).
5753  *
5754  * Environment:
5755  *      Nothing interesting.
5756  *
5757  * Side Effects:
5758  *      As advertised.
5759  *------------------------------------------------------------------------*/
5760
5761 afs_int32
5762 SRXAFS_GetXStats(struct rx_call *a_call, afs_int32 a_clientVersionNum,
5763                  afs_int32 a_collectionNumber, afs_int32 * a_srvVersionNumP,
5764                  afs_int32 * a_timeP, AFS_CollData * a_dataP)
5765 {                               /*SRXAFS_GetXStats */
5766
5767     register int code;          /*Return value */
5768     afs_int32 *dataBuffP;       /*Ptr to data to be returned */
5769     afs_int32 dataBytes;        /*Bytes in data buffer */
5770 #if FS_STATS_DETAILED
5771     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5772     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5773     struct timeval elapsedTime; /* Transfer time */
5774
5775     /*
5776      * Set our stats pointer, remember when the RPC operation started, and
5777      * tally the operation.
5778      */
5779     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETXSTATS]);
5780     FS_LOCK;
5781     (opP->numOps)++;
5782     FS_UNLOCK;
5783     TM_GetTimeOfDay(&opStartTime, 0);
5784 #endif /* FS_STATS_DETAILED */
5785
5786     /*
5787      * Record the time of day and the server version number.
5788      */
5789     *a_srvVersionNumP = AFS_XSTAT_VERSION;
5790     *a_timeP = FT_ApproxTime();
5791
5792     /*
5793      * Stuff the appropriate data in there (assume victory)
5794      */
5795     code = 0;
5796
5797     ViceLog(1,
5798             ("Received GetXStats call for collection %d\n",
5799              a_collectionNumber));
5800
5801 #if 0
5802     /*
5803      * We're not keeping stats, so just return successfully with
5804      * no data.
5805      */
5806     a_dataP->AFS_CollData_len = 0;
5807     a_dataP->AFS_CollData_val = NULL;
5808 #endif /* 0 */
5809
5810     switch (a_collectionNumber) {
5811     case AFS_XSTATSCOLL_CALL_INFO:
5812         /*
5813          * Pass back all the call-count-related data.
5814          *
5815          * >>> We are forced to allocate a separate area in which to
5816          * >>> put this stuff in by the RPC stub generator, since it
5817          * >>> will be freed at the tail end of the server stub code.
5818          */
5819 #if 0
5820         /*
5821          * I don't think call-level stats are being collected yet
5822          * for the File Server.
5823          */
5824         dataBytes = sizeof(struct afs_Stats);
5825         dataBuffP = (afs_int32 *) malloc(dataBytes);
5826         memcpy(dataBuffP, &afs_cmstats, dataBytes);
5827         a_dataP->AFS_CollData_len = dataBytes >> 2;
5828         a_dataP->AFS_CollData_val = dataBuffP;
5829 #else
5830         a_dataP->AFS_CollData_len = 0;
5831         a_dataP->AFS_CollData_val = NULL;
5832 #endif /* 0 */
5833         break;
5834
5835     case AFS_XSTATSCOLL_PERF_INFO:
5836         /*
5837          * Pass back all the regular performance-related data.
5838          *
5839          * >>> We are forced to allocate a separate area in which to
5840          * >>> put this stuff in by the RPC stub generator, since it
5841          * >>> will be freed at the tail end of the server stub code.
5842          */
5843
5844         afs_perfstats.numPerfCalls++;
5845         FillPerfValues(&afs_perfstats);
5846
5847         /*
5848          * Don't overwrite the spares at the end.
5849          */
5850
5851         dataBytes = sizeof(struct afs_PerfStats);
5852         dataBuffP = (afs_int32 *) malloc(dataBytes);
5853         memcpy(dataBuffP, &afs_perfstats, dataBytes);
5854         a_dataP->AFS_CollData_len = dataBytes >> 2;
5855         a_dataP->AFS_CollData_val = dataBuffP;
5856         break;
5857
5858     case AFS_XSTATSCOLL_FULL_PERF_INFO:
5859         /*
5860          * Pass back the full collection of performance-related data.
5861          * We have to stuff the basic, overall numbers in, but the
5862          * detailed numbers are kept in the structure already.
5863          *
5864          * >>> We are forced to allocate a separate area in which to
5865          * >>> put this stuff in by the RPC stub generator, since it
5866          * >>> will be freed at the tail end of the server stub code.
5867          */
5868
5869         afs_perfstats.numPerfCalls++;
5870 #if FS_STATS_DETAILED
5871         afs_FullPerfStats.overall.numPerfCalls = afs_perfstats.numPerfCalls;
5872         FillPerfValues(&afs_FullPerfStats.overall);
5873
5874         /*
5875          * Don't overwrite the spares at the end.
5876          */
5877
5878         dataBytes = sizeof(struct fs_stats_FullPerfStats);
5879         dataBuffP = (afs_int32 *) malloc(dataBytes);
5880         memcpy(dataBuffP, &afs_FullPerfStats, dataBytes);
5881         a_dataP->AFS_CollData_len = dataBytes >> 2;
5882         a_dataP->AFS_CollData_val = dataBuffP;
5883 #endif
5884         break;
5885
5886     case AFS_XSTATSCOLL_CBSTATS:
5887         afs_perfstats.numPerfCalls++;
5888
5889         dataBytes = sizeof(struct cbcounters);
5890         dataBuffP = (afs_int32 *) malloc(dataBytes);
5891         {
5892             extern struct cbcounters cbstuff;
5893             dataBuffP[0]=cbstuff.DeleteFiles;
5894             dataBuffP[1]=cbstuff.DeleteCallBacks;
5895             dataBuffP[2]=cbstuff.BreakCallBacks;
5896             dataBuffP[3]=cbstuff.AddCallBacks;
5897             dataBuffP[4]=cbstuff.GotSomeSpaces;
5898             dataBuffP[5]=cbstuff.DeleteAllCallBacks;
5899             dataBuffP[6]=cbstuff.nFEs;
5900             dataBuffP[7]=cbstuff.nCBs;
5901             dataBuffP[8]=cbstuff.nblks;
5902             dataBuffP[9]=cbstuff.CBsTimedOut;
5903             dataBuffP[10]=cbstuff.nbreakers;
5904             dataBuffP[11]=cbstuff.GSS1;
5905             dataBuffP[12]=cbstuff.GSS2;
5906             dataBuffP[13]=cbstuff.GSS3;
5907             dataBuffP[14]=cbstuff.GSS4;
5908             dataBuffP[15]=cbstuff.GSS5;
5909         }
5910
5911         a_dataP->AFS_CollData_len = dataBytes >> 2;
5912         a_dataP->AFS_CollData_val = dataBuffP;
5913         break;
5914
5915
5916     default:
5917         /*
5918          * Illegal collection number.
5919          */
5920         a_dataP->AFS_CollData_len = 0;
5921         a_dataP->AFS_CollData_val = NULL;
5922         code = 1;
5923     }                           /*Switch on collection number */
5924
5925 #if FS_STATS_DETAILED
5926     TM_GetTimeOfDay(&opStopTime, 0);
5927     if (code == 0) {
5928         FS_LOCK;
5929         (opP->numSuccesses)++;
5930         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
5931         fs_stats_AddTo((opP->sumTime), elapsedTime);
5932         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
5933         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
5934             fs_stats_TimeAssign((opP->minTime), elapsedTime);
5935         }
5936         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
5937             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
5938         }
5939         FS_UNLOCK;
5940     }
5941 #endif /* FS_STATS_DETAILED */
5942
5943     return (code);
5944
5945 }                               /*SRXAFS_GetXStats */
5946
5947
5948 static afs_int32
5949 common_GiveUpCallBacks(struct rx_call *acall, struct AFSCBFids *FidArray,
5950                        struct AFSCBs *CallBackArray)
5951 {
5952     afs_int32 errorCode = 0;
5953     register int i;
5954     struct client *client = 0;
5955     struct rx_connection *tcon;
5956     struct host *thost;
5957 #if FS_STATS_DETAILED
5958     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
5959     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
5960     struct timeval elapsedTime; /* Transfer time */
5961
5962     /*
5963      * Set our stats pointer, remember when the RPC operation started, and
5964      * tally the operation.
5965      */
5966     opP =
5967         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GIVEUPCALLBACKS]);
5968     FS_LOCK;
5969     (opP->numOps)++;
5970     FS_UNLOCK;
5971     TM_GetTimeOfDay(&opStartTime, 0);
5972 #endif /* FS_STATS_DETAILED */
5973
5974     if (FidArray)
5975         ViceLog(1,
5976                 ("SAFS_GiveUpCallBacks (Noffids=%d)\n",
5977                  FidArray->AFSCBFids_len));
5978
5979     FS_LOCK;
5980     AFSCallStats.GiveUpCallBacks++, AFSCallStats.TotalCalls++;
5981     FS_UNLOCK;
5982     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5983         goto Bad_GiveUpCallBacks;
5984
5985     if (!FidArray && !CallBackArray) {
5986         ViceLog(1,
5987                 ("SAFS_GiveUpAllCallBacks: host=%x\n",
5988                  (tcon->peer ? tcon->peer->host : 0)));
5989         errorCode = GetClient(tcon, &client);
5990         if (!errorCode) {
5991             DeleteAllCallBacks_r(client->host, 1);
5992             PutClient(&client);
5993         }
5994     } else {
5995         if (FidArray->AFSCBFids_len < CallBackArray->AFSCBs_len) {
5996             ViceLog(0,
5997                     ("GiveUpCallBacks: #Fids %d < #CallBacks %d, host=%x\n",
5998                      FidArray->AFSCBFids_len, CallBackArray->AFSCBs_len,
5999                      (tcon->peer ? tcon->peer->host : 0)));
6000             errorCode = EINVAL;
6001             goto Bad_GiveUpCallBacks;
6002         }
6003
6004         errorCode = GetClient(tcon, &client);
6005         if (!errorCode) {
6006             for (i = 0; i < FidArray->AFSCBFids_len; i++) {
6007                 register struct AFSFid *fid = &(FidArray->AFSCBFids_val[i]);
6008                 DeleteCallBack(client->host, fid);
6009             }
6010             PutClient(&client);
6011         }
6012     }
6013
6014   Bad_GiveUpCallBacks:
6015     errorCode = CallPostamble(tcon, errorCode, thost);
6016
6017 #if FS_STATS_DETAILED
6018     TM_GetTimeOfDay(&opStopTime, 0);
6019     if (errorCode == 0) {
6020         FS_LOCK;
6021         (opP->numSuccesses)++;
6022         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6023         fs_stats_AddTo((opP->sumTime), elapsedTime);
6024         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6025         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6026             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6027         }
6028         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6029             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6030         }
6031         FS_UNLOCK;
6032     }
6033 #endif /* FS_STATS_DETAILED */
6034     return errorCode;
6035
6036 }                               /*common_GiveUpCallBacks */
6037
6038
6039 afs_int32
6040 SRXAFS_GiveUpCallBacks(struct rx_call * acall, struct AFSCBFids * FidArray,
6041                        struct AFSCBs * CallBackArray)
6042 {
6043     return common_GiveUpCallBacks(acall, FidArray, CallBackArray);
6044 }                               /*SRXAFS_GiveUpCallBacks */
6045
6046 afs_int32
6047 SRXAFS_GiveUpAllCallBacks(struct rx_call * acall)
6048 {
6049     return common_GiveUpCallBacks(acall, 0, 0);
6050 }                               /*SRXAFS_GiveUpAllCallBacks */
6051
6052
6053 afs_int32
6054 SRXAFS_NGetVolumeInfo(struct rx_call * acall, char *avolid,
6055                       struct AFSVolumeInfo * avolinfo)
6056 {
6057     return (VNOVOL);            /* XXX Obsolete routine XXX */
6058
6059 }                               /*SRXAFS_NGetVolumeInfo */
6060
6061
6062 /*
6063  * Dummy routine. Should never be called (the cache manager should only 
6064  * invoke this interface when communicating with a AFS/DFS Protocol
6065  * Translator).
6066  */
6067 afs_int32
6068 SRXAFS_Lookup(struct rx_call * call_p, struct AFSFid * afs_dfid_p,
6069               char *afs_name_p, struct AFSFid * afs_fid_p,
6070               struct AFSFetchStatus * afs_status_p,
6071               struct AFSFetchStatus * afs_dir_status_p,
6072               struct AFSCallBack * afs_callback_p,
6073               struct AFSVolSync * afs_sync_p)
6074 {
6075     return EINVAL;
6076 }
6077
6078
6079 afs_int32
6080 SRXAFS_GetCapabilities(struct rx_call * acall, Capabilities * capabilities)
6081 {
6082     afs_int32 code;
6083     struct rx_connection *tcon;
6084     struct host *thost;
6085     afs_int32 *dataBuffP;
6086     afs_int32 dataBytes;
6087
6088     FS_LOCK;
6089     AFSCallStats.GetCapabilities++, AFSCallStats.TotalCalls++;
6090     afs_FullPerfStats.overall.fs_nGetCaps++;
6091     FS_UNLOCK;
6092     ViceLog(2, ("SAFS_GetCapabilties\n"));
6093
6094     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6095         goto Bad_GetCaps;
6096
6097     dataBytes = 1 * sizeof(afs_int32);
6098     dataBuffP = (afs_int32 *) malloc(dataBytes);
6099     dataBuffP[0] = VICED_CAPABILITY_ERRORTRANS | VICED_CAPABILITY_WRITELOCKACL;
6100 #if defined(AFS_64BIT_ENV) && defined(AFS_LARGEFILE_ENV)
6101     dataBuffP[0] |= VICED_CAPABILITY_64BITFILES;
6102 #endif
6103     if (saneacls)
6104         dataBuffP[0] |= VICED_CAPABILITY_SANEACLS;
6105
6106     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
6107     capabilities->Capabilities_val = dataBuffP;
6108
6109   Bad_GetCaps:
6110     code = CallPostamble(tcon, code, thost);
6111
6112
6113     return 0;
6114 }
6115
6116 afs_int32
6117 SRXAFS_FlushCPS(struct rx_call * acall, struct ViceIds * vids,
6118                 struct IPAddrs * addrs, afs_int32 spare1, afs_int32 * spare2,
6119                 afs_int32 * spare3)
6120 {
6121     int i;
6122     afs_int32 nids, naddrs;
6123     afs_int32 *vd, *addr;
6124     int errorCode = 0;          /* return code to caller */
6125     struct client *client = 0;
6126     struct rx_connection *tcon = rx_ConnectionOf(acall);
6127
6128     ViceLog(1, ("SRXAFS_FlushCPS\n"));
6129     FS_LOCK;
6130     AFSCallStats.TotalCalls++;
6131     FS_UNLOCK;
6132     nids = vids->ViceIds_len;   /* # of users in here */
6133     naddrs = addrs->IPAddrs_len;        /* # of hosts in here */
6134     if (nids < 0 || naddrs < 0) {
6135         errorCode = EINVAL;
6136         goto Bad_FlushCPS;
6137     }
6138
6139     vd = vids->ViceIds_val;
6140     for (i = 0; i < nids; i++, vd++) {
6141         if (!*vd)
6142             continue;
6143         client = h_ID2Client(*vd);      /* returns write locked and refCounted, or NULL */
6144         if (!client)
6145             continue;
6146
6147         client->prfail = 2;     /* Means re-eval client's cps */
6148 #ifdef  notdef
6149         if (client->tcon) {
6150             rx_SetRock(((struct rx_connection *)client->tcon), 0);
6151         }
6152 #endif
6153         if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
6154             free(client->CPS.prlist_val);
6155             client->CPS.prlist_val = NULL;
6156             client->CPS.prlist_len = 0;
6157         }
6158         ReleaseWriteLock(&client->lock);
6159         PutClient(&client);
6160     }
6161
6162     addr = addrs->IPAddrs_val;
6163     for (i = 0; i < naddrs; i++, addr++) {
6164         if (*addr)
6165             h_flushhostcps(*addr, htons(7001));
6166     }
6167
6168   Bad_FlushCPS:
6169     ViceLog(2, ("SAFS_FlushCPS  returns %d\n", errorCode));
6170     return errorCode;
6171 }                               /*SRXAFS_FlushCPS */
6172
6173 /* worthless hack to let CS keep running ancient software */
6174 static int
6175 afs_vtoi(register char *aname)
6176 {
6177     register afs_int32 temp;
6178     register int tc;
6179
6180     temp = 0;
6181     while ((tc = *aname++)) {
6182         if (tc > '9' || tc < '0')
6183             return 0;           /* invalid name */
6184         temp *= 10;
6185         temp += tc - '0';
6186     }
6187     return temp;
6188 }
6189
6190 /*
6191  * may get name or #, but must handle all weird cases (recognize readonly
6192  * or backup volumes by name or #
6193  */
6194 static afs_int32
6195 CopyVolumeEntry(char *aname, register struct vldbentry *ave,
6196                 register struct VolumeInfo *av)
6197 {
6198     register int i, j, vol;
6199     afs_int32 mask, whichType;
6200     afs_uint32 *serverHost, *typePtr;
6201
6202     /* figure out what type we want if by name */
6203     i = strlen(aname);
6204     if (i >= 8 && strcmp(aname + i - 7, ".backup") == 0)
6205         whichType = BACKVOL;
6206     else if (i >= 10 && strcmp(aname + i - 9, ".readonly") == 0)
6207         whichType = ROVOL;
6208     else
6209         whichType = RWVOL;
6210
6211     vol = afs_vtoi(aname);
6212     if (vol == 0)
6213         vol = ave->volumeId[whichType];
6214
6215     /*
6216      * Now vol has volume # we're interested in.  Next, figure out the type
6217      * of the volume by looking finding it in the vldb entry
6218      */
6219     if ((ave->flags & VLF_RWEXISTS) && vol == ave->volumeId[RWVOL]) {
6220         mask = VLSF_RWVOL;
6221         whichType = RWVOL;
6222     } else if ((ave->flags & VLF_ROEXISTS) && vol == ave->volumeId[ROVOL]) {
6223         mask = VLSF_ROVOL;
6224         whichType = ROVOL;
6225     } else if ((ave->flags & VLF_BACKEXISTS) && vol == ave->volumeId[BACKVOL]) {
6226         mask = VLSF_RWVOL;      /* backup always is on the same volume as parent */
6227         whichType = BACKVOL;
6228     } else
6229         return EINVAL;          /* error: can't find volume in vldb entry */
6230
6231     typePtr = &av->Type0;
6232     serverHost = &av->Server0;
6233     av->Vid = vol;
6234     av->Type = whichType;
6235     av->Type0 = av->Type1 = av->Type2 = av->Type3 = av->Type4 = 0;
6236     if (ave->flags & VLF_RWEXISTS)
6237         typePtr[RWVOL] = ave->volumeId[RWVOL];
6238     if (ave->flags & VLF_ROEXISTS)
6239         typePtr[ROVOL] = ave->volumeId[ROVOL];
6240     if (ave->flags & VLF_BACKEXISTS)
6241         typePtr[BACKVOL] = ave->volumeId[BACKVOL];
6242
6243     for (i = 0, j = 0; i < ave->nServers; i++) {
6244         if ((ave->serverFlags[i] & mask) == 0)
6245             continue;           /* wrong volume */
6246         serverHost[j] = ave->serverNumber[i];
6247         j++;
6248     }
6249     av->ServerCount = j;
6250     if (j < 8)
6251         serverHost[j++] = 0;    /* bogus 8, but compat only now */
6252     return 0;
6253 }
6254
6255 static afs_int32
6256 TryLocalVLServer(char *avolid, struct VolumeInfo *avolinfo)
6257 {
6258     static struct rx_connection *vlConn = 0;
6259     static int down = 0;
6260     static afs_int32 lastDownTime = 0;
6261     struct vldbentry tve;
6262     struct rx_securityClass *vlSec;
6263     register afs_int32 code;
6264
6265     if (!vlConn) {
6266         vlSec = rxnull_NewClientSecurityObject();
6267         vlConn =
6268             rx_NewConnection(htonl(0x7f000001), htons(7003), 52, vlSec, 0);
6269         rx_SetConnDeadTime(vlConn, 15); /* don't wait long */
6270     }
6271     if (down && (FT_ApproxTime() < lastDownTime + 180)) {
6272         return 1;               /* failure */
6273     }
6274
6275     code = VL_GetEntryByNameO(vlConn, avolid, &tve);
6276     if (code >= 0)
6277         down = 0;               /* call worked */
6278     if (code) {
6279         if (code < 0) {
6280             lastDownTime = FT_ApproxTime();     /* last time we tried an RPC */
6281             down = 1;
6282         }
6283         return code;
6284     }
6285
6286     /* otherwise convert to old format vldb entry */
6287     code = CopyVolumeEntry(avolid, &tve, avolinfo);
6288     return code;
6289 }
6290
6291
6292
6293
6294
6295
6296 afs_int32
6297 SRXAFS_GetVolumeInfo(struct rx_call * acall, char *avolid,
6298                      struct VolumeInfo * avolinfo)
6299 {
6300     afs_int32 code;
6301     struct rx_connection *tcon;
6302     struct host *thost;
6303 #if FS_STATS_DETAILED
6304     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6305     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6306     struct timeval elapsedTime; /* Transfer time */
6307
6308     /*
6309      * Set our stats pointer, remember when the RPC operation started, and
6310      * tally the operation.
6311      */
6312     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMEINFO]);
6313     FS_LOCK;
6314     (opP->numOps)++;
6315     FS_UNLOCK;
6316     TM_GetTimeOfDay(&opStartTime, 0);
6317 #endif /* FS_STATS_DETAILED */
6318     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6319         goto Bad_GetVolumeInfo;
6320
6321     FS_LOCK;
6322     AFSCallStats.GetVolumeInfo++, AFSCallStats.TotalCalls++;
6323     FS_UNLOCK;
6324     code = TryLocalVLServer(avolid, avolinfo);
6325     ViceLog(1,
6326             ("SAFS_GetVolumeInfo returns %d, Volume %u, type %x, servers %x %x %x %x...\n",
6327              code, avolinfo->Vid, avolinfo->Type, avolinfo->Server0,
6328              avolinfo->Server1, avolinfo->Server2, avolinfo->Server3));
6329     avolinfo->Type4 = 0xabcd9999;       /* tell us to try new vldb */
6330
6331   Bad_GetVolumeInfo:
6332     code = CallPostamble(tcon, code, thost);
6333
6334 #if FS_STATS_DETAILED
6335     TM_GetTimeOfDay(&opStopTime, 0);
6336     if (code == 0) {
6337         FS_LOCK;
6338         (opP->numSuccesses)++;
6339         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6340         fs_stats_AddTo((opP->sumTime), elapsedTime);
6341         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6342         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6343             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6344         }
6345         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6346             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6347         }
6348         FS_UNLOCK;
6349     }
6350 #endif /* FS_STATS_DETAILED */
6351
6352     return code;
6353
6354 }                               /*SRXAFS_GetVolumeInfo */
6355
6356
6357 afs_int32
6358 SRXAFS_GetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6359                        AFSFetchVolumeStatus * FetchVolStatus, char **Name,
6360                        char **OfflineMsg, char **Motd)
6361 {
6362     Vnode *targetptr = 0;       /* vnode of the new file */
6363     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6364     int errorCode = 0;          /* error code */
6365     Volume *volptr = 0;         /* pointer to the volume header */
6366     struct client *client = 0;  /* pointer to client entry */
6367     afs_int32 rights, anyrights;        /* rights for this and any user */
6368     AFSFid dummyFid;
6369     struct rx_connection *tcon;
6370     struct host *thost;
6371     struct client *t_client = NULL;     /* tmp ptr to client data */
6372 #if FS_STATS_DETAILED
6373     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6374     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6375     struct timeval elapsedTime; /* Transfer time */
6376
6377     /*
6378      * Set our stats pointer, remember when the RPC operation started, and
6379      * tally the operation.
6380      */
6381     opP =
6382         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETVOLUMESTATUS]);
6383     FS_LOCK;
6384     (opP->numOps)++;
6385     FS_UNLOCK;
6386     TM_GetTimeOfDay(&opStartTime, 0);
6387 #endif /* FS_STATS_DETAILED */
6388
6389     ViceLog(1, ("SAFS_GetVolumeStatus for volume %u\n", avolid));
6390     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6391         goto Bad_GetVolumeStatus;
6392
6393     FS_LOCK;
6394     AFSCallStats.GetVolumeStatus++, AFSCallStats.TotalCalls++;
6395     FS_UNLOCK;
6396     if (avolid == 0) {
6397         errorCode = EINVAL;
6398         goto Bad_GetVolumeStatus;
6399     }
6400     dummyFid.Volume = avolid, dummyFid.Vnode =
6401         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6402
6403     if ((errorCode =
6404          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6405                           &parentwhentargetnotdir, &client, READ_LOCK,
6406                           &rights, &anyrights)))
6407         goto Bad_GetVolumeStatus;
6408
6409     if ((VanillaUser(client)) && (!(rights & PRSFS_READ))) {
6410         errorCode = EACCES;
6411         goto Bad_GetVolumeStatus;
6412     }
6413     (void)RXGetVolumeStatus(FetchVolStatus, Name, OfflineMsg, Motd, volptr);
6414
6415   Bad_GetVolumeStatus:
6416     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
6417                            volptr, &client);
6418     ViceLog(2, ("SAFS_GetVolumeStatus returns %d\n", errorCode));
6419     /* next is to guarantee out strings exist for stub */
6420     if (*Name == 0) {
6421         *Name = (char *)malloc(1);
6422         **Name = 0;
6423     }
6424     if (*Motd == 0) {
6425         *Motd = (char *)malloc(1);
6426         **Motd = 0;
6427     }
6428     if (*OfflineMsg == 0) {
6429         *OfflineMsg = (char *)malloc(1);
6430         **OfflineMsg = 0;
6431     }
6432     errorCode = CallPostamble(tcon, errorCode, thost);
6433
6434     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6435
6436 #if FS_STATS_DETAILED
6437     TM_GetTimeOfDay(&opStopTime, 0);
6438     if (errorCode == 0) {
6439         FS_LOCK;
6440         (opP->numSuccesses)++;
6441         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6442         fs_stats_AddTo((opP->sumTime), elapsedTime);
6443         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6444         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6445             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6446         }
6447         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6448             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6449         }
6450         FS_UNLOCK;
6451     }
6452 #endif /* FS_STATS_DETAILED */
6453
6454     osi_auditU(acall, GetVolumeStatusEvent, errorCode, 
6455                AUD_ID, t_client ? t_client->ViceId : 0,
6456                AUD_LONG, avolid, AUD_STR, *Name, AUD_END);
6457     return (errorCode);
6458
6459 }                               /*SRXAFS_GetVolumeStatus */
6460
6461
6462 afs_int32
6463 SRXAFS_SetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
6464                        AFSStoreVolumeStatus * StoreVolStatus, char *Name,
6465                        char *OfflineMsg, char *Motd)
6466 {
6467     Vnode *targetptr = 0;       /* vnode of the new file */
6468     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
6469     int errorCode = 0;          /* error code */
6470     Volume *volptr = 0;         /* pointer to the volume header */
6471     struct client *client = 0;  /* pointer to client entry */
6472     afs_int32 rights, anyrights;        /* rights for this and any user */
6473     AFSFid dummyFid;
6474     struct rx_connection *tcon = rx_ConnectionOf(acall);
6475     struct host *thost;
6476     struct client *t_client = NULL;     /* tmp ptr to client data */
6477 #if FS_STATS_DETAILED
6478     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6479     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6480     struct timeval elapsedTime; /* Transfer time */
6481
6482     /*
6483      * Set our stats pointer, remember when the RPC operation started, and
6484      * tally the operation.
6485      */
6486     opP =
6487         &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_SETVOLUMESTATUS]);
6488     FS_LOCK;
6489     (opP->numOps)++;
6490     FS_UNLOCK;
6491     TM_GetTimeOfDay(&opStartTime, 0);
6492 #endif /* FS_STATS_DETAILED */
6493
6494     ViceLog(1, ("SAFS_SetVolumeStatus for volume %u\n", avolid));
6495     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6496         goto Bad_SetVolumeStatus;
6497
6498     FS_LOCK;
6499     AFSCallStats.SetVolumeStatus++, AFSCallStats.TotalCalls++;
6500     FS_UNLOCK;
6501     if (avolid == 0) {
6502         errorCode = EINVAL;
6503         goto Bad_SetVolumeStatus;
6504     }
6505     dummyFid.Volume = avolid, dummyFid.Vnode =
6506         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
6507
6508     if ((errorCode =
6509          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
6510                           &parentwhentargetnotdir, &client, READ_LOCK,
6511                           &rights, &anyrights)))
6512         goto Bad_SetVolumeStatus;
6513
6514     if (readonlyServer) {
6515         errorCode = VREADONLY;
6516         goto Bad_SetVolumeStatus;
6517     }
6518     if (VanillaUser(client)) {
6519         errorCode = EACCES;
6520         goto Bad_SetVolumeStatus;
6521     }
6522
6523     errorCode =
6524         RXUpdate_VolumeStatus(volptr, StoreVolStatus, Name, OfflineMsg, Motd);
6525
6526   Bad_SetVolumeStatus:
6527     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0, 
6528                      volptr, &client);
6529     ViceLog(2, ("SAFS_SetVolumeStatus returns %d\n", errorCode));
6530     errorCode = CallPostamble(tcon, errorCode, thost);
6531
6532     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
6533
6534 #if FS_STATS_DETAILED
6535     TM_GetTimeOfDay(&opStopTime, 0);
6536     if (errorCode == 0) {
6537         FS_LOCK;
6538         (opP->numSuccesses)++;
6539         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6540         fs_stats_AddTo((opP->sumTime), elapsedTime);
6541         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6542         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6543             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6544         }
6545         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6546             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6547         }
6548         FS_UNLOCK;
6549     }
6550 #endif /* FS_STATS_DETAILED */
6551
6552     osi_auditU(acall, SetVolumeStatusEvent, errorCode, 
6553                AUD_ID, t_client ? t_client->ViceId : 0,
6554                AUD_LONG, avolid, AUD_STR, Name, AUD_END);
6555     return (errorCode);
6556 }                               /*SRXAFS_SetVolumeStatus */
6557
6558 #define DEFAULTVOLUME   "root.afs"
6559
6560 afs_int32
6561 SRXAFS_GetRootVolume(struct rx_call * acall, char **VolumeName)
6562 {
6563 #ifdef notdef
6564     int fd;
6565     int len;
6566     char *temp;
6567     struct rx_connection *tcon;
6568     struct host *thost;
6569 #endif
6570     int errorCode = 0;
6571 #if FS_STATS_DETAILED
6572     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6573     struct timeval opStartTime; /* Start time for RPC op */
6574 #ifdef notdef
6575     struct timeval opStopTime;
6576     struct timeval elapsedTime; /* Transfer time */
6577 #endif
6578
6579     /*
6580      * Set our stats pointer, remember when the RPC operation started, and
6581      * tally the operation.
6582      */
6583     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETROOTVOLUME]);
6584     FS_LOCK;
6585     (opP->numOps)++;
6586     FS_UNLOCK;
6587     TM_GetTimeOfDay(&opStartTime, 0);
6588 #endif /* FS_STATS_DETAILED */
6589
6590     return FSERR_EOPNOTSUPP;
6591
6592 #ifdef  notdef
6593     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))
6594         goto Bad_GetRootVolume;
6595     FS_LOCK;
6596     AFSCallStats.GetRootVolume++, AFSCallStats.TotalCalls++;
6597     FS_UNLOCK;
6598     temp = malloc(256);
6599     fd = afs_open(AFSDIR_SERVER_ROOTVOL_FILEPATH, O_RDONLY, 0666);
6600     if (fd <= 0)
6601         strcpy(temp, DEFAULTVOLUME);
6602     else {
6603 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6604         lockf(fd, F_LOCK, 0);
6605 #else
6606         flock(fd, LOCK_EX);
6607 #endif
6608         len = read(fd, temp, 256);
6609 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6610         lockf(fd, F_ULOCK, 0);
6611 #else
6612         flock(fd, LOCK_UN);
6613 #endif
6614         close(fd);
6615         if (temp[len - 1] == '\n')
6616             len--;
6617         temp[len] = '\0';
6618     }
6619     *VolumeName = temp;         /* freed by rx server-side stub */
6620
6621   Bad_GetRootVolume:
6622     errorCode = CallPostamble(tcon, errorCode, thost);
6623
6624 #if FS_STATS_DETAILED
6625     TM_GetTimeOfDay(&opStopTime, 0);
6626     if (errorCode == 0) {
6627         FS_LOCK;
6628         (opP->numSuccesses)++;
6629         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6630         fs_stats_AddTo((opP->sumTime), elapsedTime);
6631         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6632         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6633             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6634         }
6635         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6636             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6637         }
6638         FS_UNLOCK;
6639     }
6640 #endif /* FS_STATS_DETAILED */
6641
6642     return (errorCode);
6643 #endif /* notdef */
6644
6645 }                               /*SRXAFS_GetRootVolume */
6646
6647
6648 /* still works because a struct CBS is the same as a struct AFSOpaque */
6649 afs_int32
6650 SRXAFS_CheckToken(struct rx_call * acall, afs_int32 AfsId,
6651                   struct AFSOpaque * Token)
6652 {
6653     afs_int32 code;
6654     struct rx_connection *tcon;
6655     struct host *thost;
6656 #if FS_STATS_DETAILED
6657     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6658     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6659     struct timeval elapsedTime; /* Transfer time */
6660
6661     /*
6662      * Set our stats pointer, remember when the RPC operation started, and
6663      * tally the operation.
6664      */
6665     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_CHECKTOKEN]);
6666     FS_LOCK;
6667     (opP->numOps)++;
6668     FS_UNLOCK;
6669     TM_GetTimeOfDay(&opStartTime, 0);
6670 #endif /* FS_STATS_DETAILED */
6671
6672     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6673         goto Bad_CheckToken;
6674
6675     code = FSERR_ECONNREFUSED;
6676
6677   Bad_CheckToken:
6678     code = CallPostamble(tcon, code, thost);
6679
6680 #if FS_STATS_DETAILED
6681     TM_GetTimeOfDay(&opStopTime, 0);
6682     if (code == 0) {
6683         FS_LOCK;
6684         (opP->numSuccesses)++;
6685         fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6686         fs_stats_AddTo((opP->sumTime), elapsedTime);
6687         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6688         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6689             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6690         }
6691         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6692             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6693         }
6694         FS_UNLOCK;
6695     }
6696 #endif /* FS_STATS_DETAILED */
6697
6698     return code;
6699
6700 }                               /*SRXAFS_CheckToken */
6701
6702 afs_int32
6703 SRXAFS_GetTime(struct rx_call * acall, afs_uint32 * Seconds,
6704                afs_uint32 * USeconds)
6705 {
6706     afs_int32 code;
6707     struct rx_connection *tcon;
6708     struct host *thost;
6709     struct timeval tpl;
6710 #if FS_STATS_DETAILED
6711     struct fs_stats_opTimingData *opP;  /* Ptr to this op's timing struct */
6712     struct timeval opStartTime, opStopTime;     /* Start/stop times for RPC op */
6713     struct timeval elapsedTime; /* Transfer time */
6714
6715     /*
6716      * Set our stats pointer, remember when the RPC operation started, and
6717      * tally the operation.
6718      */
6719     opP = &(afs_FullPerfStats.det.rpcOpTimes[FS_STATS_RPCIDX_GETTIME]);
6720     FS_LOCK;
6721     (opP->numOps)++;
6722     FS_UNLOCK;
6723     TM_GetTimeOfDay(&opStartTime, 0);
6724 #endif /* FS_STATS_DETAILED */
6725
6726     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6727         goto Bad_GetTime;
6728
6729     FS_LOCK;
6730     AFSCallStats.GetTime++, AFSCallStats.TotalCalls++;
6731     FS_UNLOCK;
6732     TM_GetTimeOfDay(&tpl, 0);
6733     *Seconds = tpl.tv_sec;
6734     *USeconds = tpl.tv_usec;
6735
6736     ViceLog(2, ("SAFS_GetTime returns %u, %u\n", *Seconds, *USeconds));
6737
6738   Bad_GetTime:
6739     code = CallPostamble(tcon, code, thost);
6740
6741 #if FS_STATS_DETAILED
6742     TM_GetTimeOfDay(&opStopTime, 0);
6743     fs_stats_GetDiff(elapsedTime, opStartTime, opStopTime);
6744     if (code == 0) {
6745         FS_LOCK;
6746         (opP->numSuccesses)++;
6747         fs_stats_AddTo((opP->sumTime), elapsedTime);
6748         fs_stats_SquareAddTo((opP->sqrTime), elapsedTime);
6749         if (fs_stats_TimeLessThan(elapsedTime, (opP->minTime))) {
6750             fs_stats_TimeAssign((opP->minTime), elapsedTime);
6751         }
6752         if (fs_stats_TimeGreaterThan(elapsedTime, (opP->maxTime))) {
6753             fs_stats_TimeAssign((opP->maxTime), elapsedTime);
6754         }
6755         FS_UNLOCK;
6756     }
6757 #endif /* FS_STATS_DETAILED */
6758
6759     return code;
6760
6761 }                               /*SRXAFS_GetTime */
6762
6763
6764 /*
6765  * FetchData_RXStyle
6766  *
6767  * Purpose:
6768  *      Implement a client's data fetch using Rx.
6769  *
6770  * Arguments:
6771  *      volptr          : Ptr to the given volume's info.
6772  *      targetptr       : Pointer to the vnode involved.
6773  *      Call            : Ptr to the Rx call involved.
6774  *      Pos             : Offset within the file.
6775  *      Len             : Length in bytes to read; this value is bogus!
6776  * if FS_STATS_DETAILED
6777  *      a_bytesToFetchP : Set to the number of bytes to be fetched from
6778  *                        the File Server.
6779  *      a_bytesFetchedP : Set to the actual number of bytes fetched from
6780  *                        the File Server.
6781  * endif
6782  */
6783
6784 afs_int32
6785 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
6786                   register struct rx_call * Call, afs_sfsize_t Pos,
6787                   afs_sfsize_t Len, afs_int32 Int64Mode,
6788 #if FS_STATS_DETAILED
6789                   afs_sfsize_t * a_bytesToFetchP,
6790                   afs_sfsize_t * a_bytesFetchedP
6791 #endif                          /* FS_STATS_DETAILED */
6792     )
6793 {
6794     struct timeval StartTime, StopTime; /* used to calculate file  transfer rates */
6795     int errorCode = 0;          /* Returned error code to caller */
6796     IHandle_t *ihP;
6797     FdHandle_t *fdP;
6798 #ifdef AFS_NT40_ENV
6799     register char *tbuffer;
6800 #else /* AFS_NT40_ENV */
6801     struct iovec tiov[RX_MAXIOVECS];
6802     int tnio;
6803 #endif /* AFS_NT40_ENV */
6804     afs_sfsize_t tlen;
6805     afs_int32 optSize;
6806
6807 #if FS_STATS_DETAILED
6808     /*
6809      * Initialize the byte count arguments.
6810      */
6811     (*a_bytesToFetchP) = 0;
6812     (*a_bytesFetchedP) = 0;
6813 #endif /* FS_STATS_DETAILED */
6814
6815
6816     ViceLog(25,
6817             ("FetchData_RXStyle: Pos %llu, Len %llu\n", (afs_uintmax_t) Pos,
6818              (afs_uintmax_t) Len));
6819
6820     if (!VN_GET_INO(targetptr)) {
6821         afs_int32 zero = htonl(0);
6822         /*
6823          * This is used for newly created files; we simply send 0 bytes
6824          * back to make the cache manager happy...
6825          */
6826         if (Int64Mode)
6827             rx_Write(Call, (char *)&zero, sizeof(afs_int32));   /* send 0-length  */
6828         rx_Write(Call, (char *)&zero, sizeof(afs_int32));       /* send 0-length  */
6829         return (0);
6830     }
6831     TM_GetTimeOfDay(&StartTime, 0);
6832     ihP = targetptr->handle;
6833     fdP = IH_OPEN(ihP);
6834     if (fdP == NULL) {
6835         VTakeOffline(volptr);
6836         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6837                     volptr->hashid));
6838         return EIO;
6839     }
6840     optSize = sendBufSize;
6841     tlen = FDH_SIZE(fdP);
6842     ViceLog(25,
6843             ("FetchData_RXStyle: file size %llu\n", (afs_uintmax_t) tlen));
6844     if (tlen < 0) {
6845         FDH_CLOSE(fdP);
6846         VTakeOffline(volptr);
6847         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6848                     volptr->hashid));
6849         return EIO;
6850     }
6851     if (Pos > tlen) {
6852         Len = 0;
6853     }
6854
6855     if (Pos + Len > tlen)
6856         Len = tlen - Pos;       /* get length we should send */
6857     (void)FDH_SEEK(fdP, Pos, 0);
6858     {
6859         afs_int32 high, low;
6860         SplitOffsetOrSize(Len, high, low);
6861         assert(Int64Mode || (Len >= 0 && high == 0) || Len < 0);
6862         if (Int64Mode) {
6863             high = htonl(high);
6864             rx_Write(Call, (char *)&high, sizeof(afs_int32));   /* High order bits */
6865         }
6866         low = htonl(low);
6867         rx_Write(Call, (char *)&low, sizeof(afs_int32));        /* send length on fetch */
6868     }
6869 #if FS_STATS_DETAILED
6870     (*a_bytesToFetchP) = Len;
6871 #endif /* FS_STATS_DETAILED */
6872 #ifdef AFS_NT40_ENV
6873     tbuffer = AllocSendBuffer();
6874 #endif /* AFS_NT40_ENV */
6875     while (Len > 0) {
6876         int wlen;
6877         if (Len > optSize)
6878             wlen = optSize;
6879         else
6880             wlen = (int)Len;
6881 #ifdef AFS_NT40_ENV
6882         errorCode = FDH_READ(fdP, tbuffer, wlen);
6883         if (errorCode != wlen) {
6884             FDH_CLOSE(fdP);
6885             FreeSendBuffer((struct afs_buffer *)tbuffer);
6886             VTakeOffline(volptr);
6887             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6888                         volptr->hashid));
6889             return EIO;
6890         }
6891         errorCode = rx_Write(Call, tbuffer, wlen);
6892 #else /* AFS_NT40_ENV */
6893         errorCode = rx_WritevAlloc(Call, tiov, &tnio, RX_MAXIOVECS, wlen);
6894         if (errorCode <= 0) {
6895             FDH_CLOSE(fdP);
6896             return EIO;
6897         }
6898         wlen = errorCode;
6899         errorCode = FDH_READV(fdP, tiov, tnio);
6900         if (errorCode != wlen) {
6901             FDH_CLOSE(fdP);
6902             VTakeOffline(volptr);
6903             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6904                         volptr->hashid));
6905             return EIO;
6906         }
6907         errorCode = rx_Writev(Call, tiov, tnio, wlen);
6908 #endif /* AFS_NT40_ENV */
6909 #if FS_STATS_DETAILED
6910         /*
6911          * Bump the number of bytes actually sent by the number from this
6912          * latest iteration
6913          */
6914         (*a_bytesFetchedP) += errorCode;
6915 #endif /* FS_STATS_DETAILED */
6916         if (errorCode != wlen) {
6917             FDH_CLOSE(fdP);
6918 #ifdef AFS_NT40_ENV
6919             FreeSendBuffer((struct afs_buffer *)tbuffer);
6920 #endif /* AFS_NT40_ENV */
6921             return -31;
6922         }
6923         Len -= wlen;
6924     }
6925 #ifdef AFS_NT40_ENV
6926     FreeSendBuffer((struct afs_buffer *)tbuffer);
6927 #endif /* AFS_NT40_ENV */
6928     FDH_CLOSE(fdP);
6929     TM_GetTimeOfDay(&StopTime, 0);
6930
6931     /* Adjust all Fetch Data related stats */
6932     FS_LOCK;
6933     if (AFSCallStats.TotalFetchedBytes > 2000000000)    /* Reset if over 2 billion */
6934         AFSCallStats.TotalFetchedBytes = AFSCallStats.AccumFetchTime = 0;
6935     AFSCallStats.AccumFetchTime +=
6936         ((StopTime.tv_sec - StartTime.tv_sec) * 1000) +
6937         ((StopTime.tv_usec - StartTime.tv_usec) / 1000);
6938     {
6939         afs_fsize_t targLen;
6940         VN_GET_LEN(targLen, targetptr);
6941         AFSCallStats.TotalFetchedBytes += targLen;
6942         AFSCallStats.FetchSize1++;
6943         if (targLen < SIZE2)
6944             AFSCallStats.FetchSize2++;
6945         else if (targLen < SIZE3)
6946             AFSCallStats.FetchSize3++;
6947         else if (targLen < SIZE4)
6948             AFSCallStats.FetchSize4++;
6949         else
6950             AFSCallStats.FetchSize5++;
6951     }
6952     FS_UNLOCK;
6953     return (0);
6954
6955 }                               /*FetchData_RXStyle */
6956
6957 static int
6958 GetLinkCountAndSize(Volume * vp, FdHandle_t * fdP, int *lc,
6959                     afs_sfsize_t * size)
6960 {
6961 #ifdef AFS_NAMEI_ENV
6962     FdHandle_t *lhp;
6963     lhp = IH_OPEN(V_linkHandle(vp));
6964     if (!lhp)
6965         return EIO;
6966 #ifdef AFS_NT40_ENV
6967     *lc = nt_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
6968 #else
6969     *lc = namei_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0);
6970 #endif
6971     FDH_CLOSE(lhp);
6972     if (*lc < 0)
6973         return -1;
6974     *size = OS_SIZE(fdP->fd_fd);
6975     return (*size == -1) ? -1 : 0;
6976 #else
6977     struct afs_stat status;
6978
6979     if (afs_fstat(fdP->fd_fd, &status) < 0) {
6980         return -1;
6981     }
6982
6983     *lc = GetLinkCount(vp, &status);
6984     *size = status.st_size;
6985     return 0;
6986 #endif
6987 }
6988
6989 /*
6990  * StoreData_RXStyle
6991  *
6992  * Purpose:
6993  *      Implement a client's data store using Rx.
6994  *
6995  * Arguments:
6996  *      volptr          : Ptr to the given volume's info.
6997  *      targetptr       : Pointer to the vnode involved.
6998  *      Call            : Ptr to the Rx call involved.
6999  *      Pos             : Offset within the file.
7000  *      Len             : Length in bytes to store; this value is bogus!
7001  * if FS_STATS_DETAILED
7002  *      a_bytesToStoreP : Set to the number of bytes to be stored to
7003  *                        the File Server.
7004  *      a_bytesStoredP  : Set to the actual number of bytes stored to
7005  *                        the File Server.
7006  * endif
7007  */
7008 afs_int32
7009 StoreData_RXStyle(Volume * volptr, Vnode * targetptr, struct AFSFid * Fid,
7010                   struct client * client, register struct rx_call * Call,
7011                   afs_fsize_t Pos, afs_fsize_t Length, afs_fsize_t FileLength,
7012                   int sync,
7013 #if FS_STATS_DETAILED
7014                   afs_sfsize_t * a_bytesToStoreP,
7015                   afs_sfsize_t * a_bytesStoredP
7016 #endif                          /* FS_STATS_DETAILED */
7017     )
7018 {
7019     afs_sfsize_t bytesTransfered;       /* number of bytes actually transfered */
7020     struct timeval StartTime, StopTime; /* Used to measure how long the store takes */
7021     int errorCode = 0;          /* Returned error code to caller */
7022 #ifdef AFS_NT40_ENV
7023     register char *tbuffer;     /* data copying buffer */
7024 #else /* AFS_NT40_ENV */
7025     struct iovec tiov[RX_MAXIOVECS];    /* no data copying with iovec */
7026     int tnio;                   /* temp for iovec size */
7027 #endif /* AFS_NT40_ENV */
7028     afs_sfsize_t tlen;          /* temp for xfr length */
7029     Inode tinode;               /* inode for I/O */
7030     afs_int32 optSize;          /* optimal transfer size */
7031     afs_sfsize_t DataLength;    /* size of inode */
7032     afs_sfsize_t TruncatedLength;       /* size after ftruncate */
7033     afs_fsize_t NewLength;      /* size after this store completes */
7034     afs_sfsize_t adjustSize;    /* bytes to call VAdjust... with */
7035     int linkCount;              /* link count on inode */
7036     FdHandle_t *fdP;
7037     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
7038
7039 #if FS_STATS_DETAILED
7040     /*
7041      * Initialize the byte count arguments.
7042      */
7043     (*a_bytesToStoreP) = 0;
7044     (*a_bytesStoredP) = 0;
7045 #endif /* FS_STATS_DETAILED */
7046
7047     /*
7048      * We break the callbacks here so that the following signal will not
7049      * leave a window.
7050      */
7051     BreakCallBack(client->host, Fid, 0);
7052
7053     if (Pos == -1 || VN_GET_INO(targetptr) == 0) {
7054         /* the inode should have been created in Alloc_NewVnode */
7055         logHostAddr.s_addr = rxr_HostOf(rx_ConnectionOf(Call));
7056         ViceLog(0,
7057                 ("StoreData_RXStyle : Inode non-existent Fid = %u.%u.%u, inode = %llu, Pos %llu Host %s:%d\n",
7058                  Fid->Volume, Fid->Vnode, Fid->Unique,
7059                  (afs_uintmax_t) VN_GET_INO(targetptr), (afs_uintmax_t) Pos,
7060                  inet_ntoa(logHostAddr), ntohs(rxr_PortOf(rx_ConnectionOf(Call)))));
7061         return ENOENT;          /* is this proper error code? */
7062     } else {
7063         /*
7064          * See if the file has several links (from other volumes).  If it
7065          * does, then we have to make a copy before changing it to avoid
7066          *changing read-only clones of this dude
7067          */
7068         ViceLog(25,
7069                 ("StoreData_RXStyle : Opening inode %s\n",
7070                  PrintInode(NULL, VN_GET_INO(targetptr))));
7071         fdP = IH_OPEN(targetptr->handle);
7072         if (fdP == NULL)
7073             return ENOENT;
7074         if (GetLinkCountAndSize(volptr, fdP, &linkCount, &DataLength) < 0) {
7075             FDH_CLOSE(fdP);
7076             VTakeOffline(volptr);
7077             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
7078                         volptr->hashid));
7079             return EIO;
7080         }
7081
7082         if (linkCount != 1) {
7083             afs_fsize_t size;
7084             ViceLog(25,
7085                     ("StoreData_RXStyle : inode %s has more than onelink\n",
7086                      PrintInode(NULL, VN_GET_INO(targetptr))));
7087             /* other volumes share this data, better copy it first */
7088
7089             /* Adjust the disk block count by the creation of the new inode.
7090              * We call the special VDiskUsage so we don't adjust the volume's
7091              * quota since we don't want to penalyze the user for afs's internal
7092              * mechanisms (i.e. copy on write overhead.) Also the right size
7093              * of the disk will be recorded...
7094              */
7095             FDH_CLOSE(fdP);
7096             VN_GET_LEN(size, targetptr);
7097             volptr->partition->flags &= ~PART_DONTUPDATE;
7098             VSetPartitionDiskUsage(volptr->partition);
7099             volptr->partition->flags |= PART_DONTUPDATE;
7100             if ((errorCode = VDiskUsage(volptr, nBlocks(size)))) {
7101                 volptr->partition->flags &= ~PART_DONTUPDATE;
7102                 return (errorCode);
7103             }
7104
7105             ViceLog(25, ("StoreData : calling CopyOnWrite on  target dir\n"));
7106             if ((errorCode = CopyOnWrite(targetptr, volptr))) {
7107                 ViceLog(25, ("StoreData : CopyOnWrite failed\n"));
7108                 volptr->partition->flags &= ~PART_DONTUPDATE;
7109                 return (errorCode);
7110             }
7111             volptr->partition->flags &= ~PART_DONTUPDATE;
7112             VSetPartitionDiskUsage(volptr->partition);
7113             fdP = IH_OPEN(targetptr->handle);
7114             if (fdP == NULL) {
7115                 ViceLog(25,
7116                         ("StoreData : Reopen after CopyOnWrite failed\n"));
7117                 return ENOENT;
7118             }
7119         }
7120         tinode = VN_GET_INO(targetptr);
7121     }
7122     if (!VALID_INO(tinode)) {
7123         VTakeOffline(volptr);
7124         ViceLog(0,("Volume %u now offline, must be salvaged.\n",
7125                    volptr->hashid));
7126         return EIO;
7127     }
7128
7129     /* compute new file length */
7130     NewLength = DataLength;
7131     if (FileLength < NewLength)
7132         /* simulate truncate */
7133         NewLength = FileLength;
7134     TruncatedLength = NewLength;        /* remember length after possible ftruncate */
7135     if (Pos + Length > NewLength)
7136         NewLength = Pos + Length;       /* and write */
7137
7138     /* adjust the disk block count by the difference in the files */
7139     {
7140         afs_fsize_t targSize;
7141         VN_GET_LEN(targSize, targetptr);
7142         adjustSize = nBlocks(NewLength) - nBlocks(targSize);
7143     }
7144     if ((errorCode =
7145          AdjustDiskUsage(volptr, adjustSize,
7146                          adjustSize - SpareComp(volptr)))) {
7147         FDH_CLOSE(fdP);
7148         return (errorCode);
7149     }
7150
7151     /* can signal cache manager to proceed from close now */
7152     /* this bit means that the locks are set and protections are OK */
7153     rx_SetLocalStatus(Call, 1);
7154
7155     TM_GetTimeOfDay(&StartTime, 0);
7156
7157     optSize = sendBufSize;
7158     ViceLog(25,
7159             ("StoreData_RXStyle: Pos %llu, DataLength %llu, FileLength %llu, Length %llu\n",
7160              (afs_uintmax_t) Pos, (afs_uintmax_t) DataLength,
7161              (afs_uintmax_t) FileLength, (afs_uintmax_t) Length));
7162
7163     /* truncate the file iff it needs it (ftruncate is slow even when its a noop) */
7164     if (FileLength < DataLength)
7165         FDH_TRUNC(fdP, FileLength);
7166     if (Pos > 0)
7167         FDH_SEEK(fdP, Pos, 0);
7168     bytesTransfered = 0;
7169 #ifdef AFS_NT40_ENV
7170     tbuffer = AllocSendBuffer();
7171 #endif /* AFS_NT40_ENV */
7172     /* if length == 0, the loop below isn't going to do anything, including
7173      * extend the length of the inode, which it must do, since the file system
7174      * assumes that the inode length == vnode's file length.  So, we extend
7175      * the file length manually if need be.  Note that if file is bigger than
7176      * Pos+(Length==0), we dont' have to do anything, and certainly shouldn't
7177      * do what we're going to do below.
7178      */
7179     if (Length == 0 && Pos > TruncatedLength) {
7180         /* Set the file's length; we've already done an lseek to the right
7181          * spot above.
7182          */
7183         errorCode = FDH_WRITE(fdP, &tlen, 1);
7184         if (errorCode != 1)
7185             goto done;
7186         errorCode = FDH_TRUNC(fdP, Pos);
7187     } else {
7188         /* have some data to copy */
7189 #if FS_STATS_DETAILED
7190         (*a_bytesToStoreP) = Length;
7191 #endif /* FS_STATS_DETAILED */
7192         while (1) {
7193             int rlen;
7194             if (bytesTransfered >= Length) {
7195                 errorCode = 0;
7196                 break;
7197             }
7198             tlen = Length - bytesTransfered;    /* how much more to do */
7199             if (tlen > optSize)
7200                 rlen = optSize; /* bound by buffer size */
7201             else
7202                 rlen = (int)tlen;
7203 #ifdef AFS_NT40_ENV
7204             errorCode = rx_Read(Call, tbuffer, rlen);
7205 #else /* AFS_NT40_ENV */
7206             errorCode = rx_Readv(Call, tiov, &tnio, RX_MAXIOVECS, rlen);
7207 #endif /* AFS_NT40_ENV */
7208 #if FS_STATS_DETAILED
7209             (*a_bytesStoredP) += errorCode;
7210 #endif /* FS_STATS_DETAILED */
7211             if (errorCode <= 0) {
7212                 errorCode = -32;
7213                 break;
7214             }
7215             rlen = errorCode;
7216 #ifdef AFS_NT40_ENV
7217             errorCode = FDH_WRITE(fdP, tbuffer, rlen);
7218 #else /* AFS_NT40_ENV */
7219             errorCode = FDH_WRITEV(fdP, tiov, tnio);
7220 #endif /* AFS_NT40_ENV */
7221             if (errorCode != rlen) {
7222                 errorCode = VDISKFULL;
7223                 break;
7224             }
7225             bytesTransfered += rlen;
7226         }
7227     }
7228   done:
7229 #ifdef AFS_NT40_ENV
7230     FreeSendBuffer((struct afs_buffer *)tbuffer);
7231 #endif /* AFS_NT40_ENV */
7232     if (sync) {
7233         FDH_SYNC(fdP);
7234     }
7235     if (errorCode) {
7236         afs_fsize_t nfSize = (afs_fsize_t) FDH_SIZE(fdP);
7237         /* something went wrong: adjust size and return */
7238         VN_SET_LEN(targetptr, nfSize);  /* set new file size. */
7239         /* changed_newTime is tested in StoreData to detemine if we
7240          * need to update the target vnode.
7241          */
7242         targetptr->changed_newTime = 1;
7243         FDH_CLOSE(fdP);
7244         /* set disk usage to be correct */
7245         VAdjustDiskUsage(&errorCode, volptr,
7246                          (afs_sfsize_t) (nBlocks(nfSize) -
7247                                          nBlocks(NewLength)), 0);
7248         return errorCode;
7249     }
7250     FDH_CLOSE(fdP);
7251
7252     TM_GetTimeOfDay(&StopTime, 0);
7253
7254     VN_SET_LEN(targetptr, NewLength);
7255
7256     /* Update all StoreData related stats */
7257     FS_LOCK;
7258     if (AFSCallStats.TotalStoredBytes > 2000000000)     /* reset if over 2 billion */
7259         AFSCallStats.TotalStoredBytes = AFSCallStats.AccumStoreTime = 0;
7260     AFSCallStats.StoreSize1++;  /* Piggybacked data */
7261     {
7262         afs_fsize_t targLen;
7263         VN_GET_LEN(targLen, targetptr);
7264         if (targLen < SIZE2)
7265             AFSCallStats.StoreSize2++;
7266         else if (targLen < SIZE3)
7267             AFSCallStats.StoreSize3++;
7268         else if (targLen < SIZE4)
7269             AFSCallStats.StoreSize4++;
7270         else
7271             AFSCallStats.StoreSize5++;
7272     }
7273     FS_UNLOCK;
7274     return (errorCode);
7275
7276 }                               /*StoreData_RXStyle */
7277
7278 static int sys2et[512];
7279
7280 void
7281 init_sys_error_to_et(void)
7282 {
7283     memset(&sys2et, 0, sizeof(sys2et));
7284     sys2et[EPERM] = UAEPERM;
7285     sys2et[ENOENT] = UAENOENT;
7286     sys2et[ESRCH] = UAESRCH;
7287     sys2et[EINTR] = UAEINTR;
7288     sys2et[EIO] = UAEIO;
7289     sys2et[ENXIO] = UAENXIO;
7290     sys2et[E2BIG] = UAE2BIG;
7291     sys2et[ENOEXEC] = UAENOEXEC;
7292     sys2et[EBADF] = UAEBADF;
7293     sys2et[ECHILD] = UAECHILD;
7294     sys2et[EAGAIN] = UAEAGAIN;
7295     sys2et[ENOMEM] = UAENOMEM;
7296     sys2et[EACCES] = UAEACCES;
7297     sys2et[EFAULT] = UAEFAULT;
7298     sys2et[ENOTBLK] = UAENOTBLK;
7299     sys2et[EBUSY] = UAEBUSY;
7300     sys2et[EEXIST] = UAEEXIST;
7301     sys2et[EXDEV] = UAEXDEV;
7302     sys2et[ENODEV] = UAENODEV;
7303     sys2et[ENOTDIR] = UAENOTDIR;
7304     sys2et[EISDIR] = UAEISDIR;
7305     sys2et[EINVAL] = UAEINVAL;
7306     sys2et[ENFILE] = UAENFILE;
7307     sys2et[EMFILE] = UAEMFILE;
7308     sys2et[ENOTTY] = UAENOTTY;
7309     sys2et[ETXTBSY] = UAETXTBSY;
7310     sys2et[EFBIG] = UAEFBIG;
7311     sys2et[ENOSPC] = UAENOSPC;
7312     sys2et[ESPIPE] = UAESPIPE;
7313     sys2et[EROFS] = UAEROFS;
7314     sys2et[EMLINK] = UAEMLINK;
7315     sys2et[EPIPE] = UAEPIPE;
7316     sys2et[EDOM] = UAEDOM;
7317     sys2et[ERANGE] = UAERANGE;
7318     sys2et[EDEADLK] = UAEDEADLK;
7319     sys2et[ENAMETOOLONG] = UAENAMETOOLONG;
7320     sys2et[ENOLCK] = UAENOLCK;
7321     sys2et[ENOSYS] = UAENOSYS;
7322 #if (ENOTEMPTY != EEXIST)
7323     sys2et[ENOTEMPTY] = UAENOTEMPTY;
7324 #endif
7325     sys2et[ELOOP] = UAELOOP;
7326 #if (EWOULDBLOCK != EAGAIN)
7327     sys2et[EWOULDBLOCK] = UAEWOULDBLOCK;
7328 #endif
7329     sys2et[ENOMSG] = UAENOMSG;
7330     sys2et[EIDRM] = UAEIDRM;
7331     sys2et[ECHRNG] = UAECHRNG;
7332     sys2et[EL2NSYNC] = UAEL2NSYNC;
7333     sys2et[EL3HLT] = UAEL3HLT;
7334     sys2et[EL3RST] = UAEL3RST;
7335     sys2et[ELNRNG] = UAELNRNG;
7336     sys2et[EUNATCH] = UAEUNATCH;
7337     sys2et[ENOCSI] = UAENOCSI;
7338     sys2et[EL2HLT] = UAEL2HLT;
7339     sys2et[EBADE] = UAEBADE;
7340     sys2et[EBADR] = UAEBADR;
7341     sys2et[EXFULL] = UAEXFULL;
7342     sys2et[ENOANO] = UAENOANO;
7343     sys2et[EBADRQC] = UAEBADRQC;
7344     sys2et[EBADSLT] = UAEBADSLT;
7345     sys2et[EDEADLK] = UAEDEADLK;
7346     sys2et[EBFONT] = UAEBFONT;
7347     sys2et[ENOSTR] = UAENOSTR;
7348     sys2et[ENODATA] = UAENODATA;
7349     sys2et[ETIME] = UAETIME;
7350     sys2et[ENOSR] = UAENOSR;
7351     sys2et[ENONET] = UAENONET;
7352     sys2et[ENOPKG] = UAENOPKG;
7353     sys2et[EREMOTE] = UAEREMOTE;
7354     sys2et[ENOLINK] = UAENOLINK;
7355     sys2et[EADV] = UAEADV;
7356     sys2et[ESRMNT] = UAESRMNT;
7357     sys2et[ECOMM] = UAECOMM;
7358     sys2et[EPROTO] = UAEPROTO;
7359     sys2et[EMULTIHOP] = UAEMULTIHOP;
7360     sys2et[EDOTDOT] = UAEDOTDOT;
7361     sys2et[EBADMSG] = UAEBADMSG;
7362     sys2et[EOVERFLOW] = UAEOVERFLOW;
7363     sys2et[ENOTUNIQ] = UAENOTUNIQ;
7364     sys2et[EBADFD] = UAEBADFD;
7365     sys2et[EREMCHG] = UAEREMCHG;
7366     sys2et[ELIBACC] = UAELIBACC;
7367     sys2et[ELIBBAD] = UAELIBBAD;
7368     sys2et[ELIBSCN] = UAELIBSCN;
7369     sys2et[ELIBMAX] = UAELIBMAX;
7370     sys2et[ELIBEXEC] = UAELIBEXEC;
7371     sys2et[EILSEQ] = UAEILSEQ;
7372     sys2et[ERESTART] = UAERESTART;
7373     sys2et[ESTRPIPE] = UAESTRPIPE;
7374     sys2et[EUSERS] = UAEUSERS;
7375     sys2et[ENOTSOCK] = UAENOTSOCK;
7376     sys2et[EDESTADDRREQ] = UAEDESTADDRREQ;
7377     sys2et[EMSGSIZE] = UAEMSGSIZE;
7378     sys2et[EPROTOTYPE] = UAEPROTOTYPE;
7379     sys2et[ENOPROTOOPT] = UAENOPROTOOPT;
7380     sys2et[EPROTONOSUPPORT] = UAEPROTONOSUPPORT;
7381     sys2et[ESOCKTNOSUPPORT] = UAESOCKTNOSUPPORT;
7382     sys2et[EOPNOTSUPP] = UAEOPNOTSUPP;
7383     sys2et[EPFNOSUPPORT] = UAEPFNOSUPPORT;
7384     sys2et[EAFNOSUPPORT] = UAEAFNOSUPPORT;
7385     sys2et[EADDRINUSE] = UAEADDRINUSE;
7386     sys2et[EADDRNOTAVAIL] = UAEADDRNOTAVAIL;
7387     sys2et[ENETDOWN] = UAENETDOWN;
7388     sys2et[ENETUNREACH] = UAENETUNREACH;
7389     sys2et[ENETRESET] = UAENETRESET;
7390     sys2et[ECONNABORTED] = UAECONNABORTED;
7391     sys2et[ECONNRESET] = UAECONNRESET;
7392     sys2et[ENOBUFS] = UAENOBUFS;
7393     sys2et[EISCONN] = UAEISCONN;
7394     sys2et[ENOTCONN] = UAENOTCONN;
7395     sys2et[ESHUTDOWN] = UAESHUTDOWN;
7396     sys2et[ETOOMANYREFS] = UAETOOMANYREFS;
7397     sys2et[ETIMEDOUT] = UAETIMEDOUT;
7398     sys2et[ECONNREFUSED] = UAECONNREFUSED;
7399     sys2et[EHOSTDOWN] = UAEHOSTDOWN;
7400     sys2et[EHOSTUNREACH] = UAEHOSTUNREACH;
7401     sys2et[EALREADY] = UAEALREADY;
7402     sys2et[EINPROGRESS] = UAEINPROGRESS;
7403     sys2et[ESTALE] = UAESTALE;
7404     sys2et[EUCLEAN] = UAEUCLEAN;
7405     sys2et[ENOTNAM] = UAENOTNAM;
7406     sys2et[ENAVAIL] = UAENAVAIL;
7407     sys2et[EISNAM] = UAEISNAM;
7408     sys2et[EREMOTEIO] = UAEREMOTEIO;
7409     sys2et[EDQUOT] = UAEDQUOT;
7410     sys2et[ENOMEDIUM] = UAENOMEDIUM;
7411     sys2et[EMEDIUMTYPE] = UAEMEDIUMTYPE;
7412
7413     sys2et[EIO] = UAEIO;
7414 }
7415
7416 /* NOTE:  2006-03-01                                                     
7417  *  SRXAFS_CallBackRxConnAddr should be re-written as follows:           
7418  *  - pass back the connection, client, and host from CallPreamble       
7419  *  - keep a ref on the client, which we don't now                       
7420  *  - keep a hold on the host, which we already do                       
7421  *  - pass the connection, client, and host down into SAFSS_*, and use   
7422  *    them instead of independently discovering them via rx_ConnectionOf 
7423  *    (safe) and rx_GetSpecific (not so safe)                            
7424  *  The idea being that we decide what client and host we're going to use
7425  *  when CallPreamble is called, and stay consistent throughout the call.
7426  *  This change is too invasive for 1.4.1 but should be made in 1.5.x.   
7427  */                                                                      
7428
7429 afs_int32
7430 SRXAFS_CallBackRxConnAddr (struct rx_call * acall, afs_int32 *addr)
7431 {
7432     Error errorCode = 0;
7433     struct rx_connection *tcon;
7434     struct host *tcallhost;
7435 #ifdef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7436     struct host *thost;
7437     struct client *tclient;
7438     static struct rx_securityClass *sc = 0;
7439     int i,j;
7440     struct rx_connection *conn;
7441 #endif
7442     
7443     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &tcallhost))
7444             goto Bad_CallBackRxConnAddr1;
7445     
7446 #ifndef __EXPERIMENTAL_CALLBACK_CONN_MOVING
7447     errorCode = 1;
7448 #else
7449     H_LOCK;
7450     tclient = h_FindClient_r(tcon);
7451     if (!tclient) {
7452         errorCode = VBUSY;
7453         goto Bad_CallBackRxConnAddr;
7454     }
7455     thost = tclient->host;
7456     
7457     /* nothing more can be done */
7458     if ( !thost->interface ) 
7459         goto Bad_CallBackRxConnAddr;
7460     
7461     assert(thost->interface->numberOfInterfaces > 0 );
7462     
7463     /* the only address is the primary interface */
7464     /* can't change when there's only 1 address, anyway */
7465     if ( thost->interface->numberOfInterfaces == 1 ) 
7466         goto Bad_CallBackRxConnAddr;
7467     
7468     /* initialise a security object only once */
7469     if ( !sc )
7470         sc = (struct rx_securityClass *) rxnull_NewClientSecurityObject();
7471     
7472     for ( i=0; i < thost->interface->numberOfInterfaces; i++)
7473     {
7474             if ( *addr == thost->interface->addr[i] ) {
7475                     break;
7476             }
7477     }
7478     
7479     if ( *addr != thost->interface->addr[i] ) 
7480         goto Bad_CallBackRxConnAddr;
7481
7482     conn = rx_NewConnection (thost->interface->addr[i],
7483                              thost->port, 1, sc, 0);
7484     rx_SetConnDeadTime(conn, 2); 
7485     rx_SetConnHardDeadTime(conn, AFS_HARDDEADTIME); 
7486     H_UNLOCK;
7487     errorCode = RXAFSCB_Probe(conn);
7488     H_LOCK;
7489     if (!errorCode) {
7490         if ( thost->callback_rxcon )
7491             rx_DestroyConnection(thost->callback_rxcon);
7492         thost->callback_rxcon = conn;
7493         thost->host           = addr;
7494         rx_SetConnDeadTime(thost->callback_rxcon, 50);
7495         rx_SetConnHardDeadTime(thost->callback_rxcon, AFS_HARDDEADTIME);
7496         h_ReleaseClient_r(tclient);
7497         /* The hold on thost will be released by CallPostamble */
7498         H_UNLOCK;
7499         errorCode = CallPostamble(tcon, errorCode, tcallhost);
7500         return errorCode;
7501     } else {
7502         rx_DestroyConnection(conn);
7503     }       
7504   Bad_CallBackRxConnAddr:
7505     h_ReleaseClient_r(tclient);
7506     /* The hold on thost will be released by CallPostamble */
7507     H_UNLOCK;
7508 #endif
7509
7510     errorCode = CallPostamble(tcon, errorCode, tcallhost);
7511  Bad_CallBackRxConnAddr1:
7512     return errorCode;          /* failure */
7513 }
7514
7515 afs_int32
7516 sys_error_to_et(afs_int32 in)
7517 {
7518     if (in == 0)
7519         return 0;
7520     if (in < 0 || in > 511)
7521         return in;
7522     if (in >= VICE_SPECIAL_ERRORS && in <= VIO || in == VRESTRICTED)
7523         return in;
7524     if (sys2et[in] != 0)
7525         return sys2et[in];
7526     return in;
7527 }