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