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