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