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