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