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