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