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