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