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