Don't split int64s when we don't need to
[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 <afs/afs_assert.h>
73 #include <lwp.h>
74 #include <lock.h>
75 #include <afs/afsint.h>
76 #include <afs/vldbint.h>
77 #include <afs/errors.h>
78 #include <afs/ihandle.h>
79 #include <afs/vnode.h>
80 #include <afs/volume.h>
81 #include <afs/ptclient.h>
82 #include <afs/ptuser.h>
83 #include <afs/prs_fs.h>
84 #include <afs/acl.h>
85 #include <rx/rx.h>
86 #include <rx/rx_globals.h>
87
88 #include <afs/cellconfig.h>
89 #include <afs/keys.h>
90
91 #include <afs/partition.h>
92 #include "viced_prototypes.h"
93 #include "viced.h"
94 #include "host.h"
95 #include "callback.h"
96 #include <afs/unified_afs.h>
97 #include <afs/audit.h>
98 #include <afs/afsutil.h>
99 #include <afs/dir.h>
100
101 extern void SetDirHandle(DirHandle * dir, Vnode * vnode);
102 extern void FidZap(DirHandle * file);
103 extern void FidZero(DirHandle * file);
104
105 #ifdef AFS_PTHREAD_ENV
106 pthread_mutex_t fileproc_glock_mutex;
107 #endif /* AFS_PTHREAD_ENV */
108
109 /* Useful local defines used by this module */
110
111 #define DONTCHECK       0
112 #define MustNOTBeDIR    1
113 #define MustBeDIR       2
114
115 #define TVS_SDATA       1
116 #define TVS_SSTATUS     2
117 #define TVS_CFILE       4
118 #define TVS_SLINK       8
119 #define TVS_MKDIR       0x10
120
121 #define CHK_FETCH       0x10
122 #define CHK_FETCHDATA   0x10
123 #define CHK_FETCHACL    0x11
124 #define CHK_FETCHSTATUS 0x12
125 #define CHK_STOREDATA   0x00
126 #define CHK_STOREACL    0x01
127 #define CHK_STORESTATUS 0x02
128
129 #define OWNERREAD       0400
130 #define OWNERWRITE      0200
131 #define OWNEREXEC       0100
132 #ifdef USE_GROUP_PERMS
133 #define GROUPREAD       0040
134 #define GROUPWRITE      0020
135 #define GROUPREXEC      0010
136 #endif
137
138 /* The following errors were not defined in NT. They are given unique
139  * names here to avoid any potential collision.
140  */
141 #define FSERR_ELOOP              90
142 #define FSERR_EOPNOTSUPP        122
143 #define FSERR_ECONNREFUSED      130
144
145 #define NOTACTIVECALL   0
146 #define ACTIVECALL      1
147
148 #define CREATE_SGUID_ADMIN_ONLY 1
149
150 extern struct afsconf_dir *confDir;
151 extern afs_int32 dataVersionHigh;
152
153 extern int SystemId;
154 static struct AFSCallStatistics AFSCallStats;
155 #if FS_STATS_DETAILED
156 struct fs_stats_FullPerfStats afs_FullPerfStats;
157 extern int AnonymousID;
158 #endif /* FS_STATS_DETAILED */
159 #if OPENAFS_VOL_STATS
160 static const char nullString[] = "";
161 #endif /* OPENAFS_VOL_STATS */
162
163 struct afs_FSStats {
164     afs_int32 NothingYet;
165 };
166
167 struct afs_FSStats afs_fsstats;
168
169 int LogLevel = 0;
170 int supported = 1;
171 int Console = 0;
172 afs_int32 BlocksSpare = 1024;   /* allow 1 MB overruns */
173 afs_int32 PctSpare;
174 extern afs_int32 implicitAdminRights;
175 extern afs_int32 readonlyServer;
176 extern int CopyOnWrite_calls, CopyOnWrite_off0, CopyOnWrite_size0;
177 extern afs_fsize_t CopyOnWrite_maxsize;
178
179 /*
180  * Externals used by the xstat code.
181  */
182 extern VolPkgStats VStats;
183 extern int CEs, CEBlocks;
184
185 extern int HTs, HTBlocks;
186
187 static afs_int32 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
188                                    struct rx_call *Call, afs_sfsize_t Pos,
189                                    afs_sfsize_t Len, afs_int32 Int64Mode,
190                                    afs_sfsize_t * a_bytesToFetchP,
191                                    afs_sfsize_t * a_bytesFetchedP);
192
193 static afs_int32 StoreData_RXStyle(Volume * volptr, Vnode * targetptr,
194                                    struct AFSFid *Fid, struct client *client,
195                                    struct rx_call *Call, afs_fsize_t Pos,
196                                    afs_fsize_t Length, afs_fsize_t FileLength,
197                                    int sync,
198                                    afs_sfsize_t * a_bytesToStoreP,
199                                    afs_sfsize_t * a_bytesStoredP);
200
201 #ifdef AFS_SGI_XFS_IOPS_ENV
202 #include <afs/xfsattrs.h>
203 static int
204 GetLinkCount(Volume * avp, struct stat *astat)
205 {
206     if (!strcmp("xfs", astat->st_fstype)) {
207         return (astat->st_mode & AFS_XFS_MODE_LINK_MASK);
208     } else
209         return astat->st_nlink;
210 }
211 #else
212 #define GetLinkCount(V, S) (S)->st_nlink
213 #endif
214
215 afs_int32
216 SpareComp(Volume * avolp)
217 {
218     afs_int32 temp;
219
220     FS_LOCK;
221     if (PctSpare) {
222         temp = V_maxquota(avolp);
223         if (temp == 0) {
224             /* no matter; doesn't check in this case */
225             FS_UNLOCK;
226             return 0;
227         }
228         temp = (temp * PctSpare) / 100;
229         FS_UNLOCK;
230         return temp;
231     } else {
232         FS_UNLOCK;
233         return BlocksSpare;
234     }
235
236 }                               /*SpareComp */
237
238 /*
239  * Set the volume synchronization parameter for this volume.  If it changes,
240  * the Cache Manager knows that the volume must be purged from the stat cache.
241  */
242 static void
243 SetVolumeSync(struct AFSVolSync *async, Volume * avol)
244 {
245     FS_LOCK;
246     /* date volume instance was created */
247     if (async) {
248         if (avol)
249             async->spare1 = avol->header->diskstuff.creationDate;
250         else
251             async->spare1 = 0;
252         async->spare2 = 0;
253         async->spare3 = 0;
254         async->spare4 = 0;
255         async->spare5 = 0;
256         async->spare6 = 0;
257     }
258     FS_UNLOCK;
259 }                               /*SetVolumeSync */
260
261 /**
262  * Verify that the on-disk size for a vnode matches the length in the vnode
263  * index.
264  *
265  * @param[in] vp   Volume pointer
266  * @param[in] vnp  Vnode pointer
267  * @param[in] alen Size of the vnode on disk, if known. If unknown, give -1,
268  *                 and CheckLength itself will determine the on-disk size.
269  *
270  * @return operation status
271  *  @retval 0 lengths match
272  *  @retval nonzero Error; either the lengths do not match or there was an
273  *                  error determining the on-disk size. The volume should be
274  *                  taken offline and salvaged.
275  */
276 static int
277 CheckLength(struct Volume *vp, struct Vnode *vnp, afs_sfsize_t alen)
278 {
279     afs_sfsize_t vlen;
280     VN_GET_LEN(vlen, vnp);
281
282     if (alen < 0) {
283         FdHandle_t *fdP;
284
285         fdP = IH_OPEN(vnp->handle);
286         if (fdP == NULL) {
287             ViceLog(0, ("CheckLength: cannot open inode for fid %lu.%lu.%lu\n",
288                         afs_printable_uint32_lu(vp->hashid),
289                         afs_printable_uint32_lu(Vn_id(vnp)),
290                         afs_printable_uint32_lu(vnp->disk.uniquifier)));
291             return -1;
292         }
293         alen = FDH_SIZE(fdP);
294         FDH_CLOSE(fdP);
295         if (alen < 0) {
296             afs_int64 alen64 = alen;
297             ViceLog(0, ("CheckLength: cannot get size for inode for fid "
298                         "%lu.%lu.%lu; FDH_SIZE returned %" AFS_INT64_FMT "\n",
299                         afs_printable_uint32_lu(vp->hashid),
300                         afs_printable_uint32_lu(Vn_id(vnp)),
301                         afs_printable_uint32_lu(vnp->disk.uniquifier),
302                         alen64));
303             return -1;
304         }
305     }
306
307     if (alen != vlen) {
308         afs_int64 alen64 = alen, vlen64 = vlen;
309         ViceLog(0, ("Fid %lu.%lu.%lu has inconsistent length (index "
310                     "%lld inode %lld ); volume must be salvaged\n",
311                     afs_printable_uint32_lu(vp->hashid),
312                     afs_printable_uint32_lu(Vn_id(vnp)),
313                     afs_printable_uint32_lu(vnp->disk.uniquifier),
314                     vlen64, alen64));
315         return -1;
316     }
317     return 0;
318 }
319
320 /*
321  * Note that this function always returns a held host, so
322  * that CallPostamble can block without the host's disappearing.
323  * Call returns rx connection in passed in *tconn
324  */
325 static int
326 CallPreamble(struct rx_call *acall, int activecall,
327              struct rx_connection **tconn, struct host **ahostp)
328 {
329     struct host *thost;
330     struct client *tclient;
331     int retry_flag = 1;
332     int code = 0;
333     char hoststr[16], hoststr2[16];
334 #ifdef AFS_PTHREAD_ENV
335     struct ubik_client *uclient;
336 #endif
337     *ahostp = NULL;
338
339     if (!tconn) {
340         ViceLog(0, ("CallPreamble: unexpected null tconn!\n"));
341         return -1;
342     }
343     *tconn = rx_ConnectionOf(acall);
344
345     H_LOCK;
346   retry:
347     tclient = h_FindClient_r(*tconn);
348     if (!tclient) {
349         ViceLog(0, ("CallPreamble: Couldn't get CPS. Too many lockers\n"));
350         H_UNLOCK;
351         return VBUSY;
352     }
353     thost = tclient->host;
354     if (tclient->prfail == 1) { /* couldn't get the CPS */
355         if (!retry_flag) {
356             h_ReleaseClient_r(tclient);
357             h_Release_r(thost);
358             ViceLog(0, ("CallPreamble: Couldn't get CPS. Fail\n"));
359             H_UNLOCK;
360             return -1001;
361         }
362         retry_flag = 0;         /* Retry once */
363
364         /* Take down the old connection and re-read the key file */
365         ViceLog(0,
366                 ("CallPreamble: Couldn't get CPS. Reconnect to ptserver\n"));
367 #ifdef AFS_PTHREAD_ENV
368         uclient = (struct ubik_client *)pthread_getspecific(viced_uclient_key);
369
370         /* Is it still necessary to drop this? We hit the net, we should... */
371         H_UNLOCK;
372         if (uclient) {
373             hpr_End(uclient);
374             uclient = NULL;
375         }
376         code = hpr_Initialize(&uclient);
377
378         if (!code)
379             osi_Assert(pthread_setspecific(viced_uclient_key, (void *)uclient) == 0);
380         H_LOCK;
381 #else
382         code = pr_Initialize(2, AFSDIR_SERVER_ETC_DIRPATH, 0);
383 #endif
384         if (code) {
385             h_ReleaseClient_r(tclient);
386             h_Release_r(thost);
387             H_UNLOCK;
388             ViceLog(0, ("CallPreamble: couldn't reconnect to ptserver\n"));
389             return -1001;
390         }
391
392         tclient->prfail = 2;    /* Means re-eval client's cps */
393         h_ReleaseClient_r(tclient);
394         h_Release_r(thost);
395         goto retry;
396     }
397
398     tclient->LastCall = thost->LastCall = FT_ApproxTime();
399     if (activecall)             /* For all but "GetTime", "GetStats", and "GetCaps" calls */
400         thost->ActiveCall = thost->LastCall;
401
402     h_Lock_r(thost);
403     if (thost->hostFlags & HOSTDELETED) {
404         ViceLog(3,
405                 ("Discarded a packet for deleted host %s:%d\n",
406                  afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port)));
407         code = VBUSY;           /* raced, so retry */
408     } else if ((thost->hostFlags & VENUSDOWN)
409                || (thost->hostFlags & HFE_LATER)) {
410         if (BreakDelayedCallBacks_r(thost)) {
411             ViceLog(0,
412                     ("BreakDelayedCallbacks FAILED for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
413                      afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2),
414                      ntohs(rxr_PortOf(*tconn))));
415             if (MultiProbeAlternateAddress_r(thost)) {
416                 ViceLog(0,
417                         ("MultiProbe failed to find new address for host %s:%d\n",
418                          afs_inet_ntoa_r(thost->host, hoststr),
419                          ntohs(thost->port)));
420                 code = -1;
421             } else {
422                 ViceLog(0,
423                         ("MultiProbe found new address for host %s:%d\n",
424                          afs_inet_ntoa_r(thost->host, hoststr),
425                          ntohs(thost->port)));
426                 if (BreakDelayedCallBacks_r(thost)) {
427                     ViceLog(0,
428                             ("BreakDelayedCallbacks FAILED AGAIN for host %s:%d which IS UP.  Connection from %s:%d.  Possible network or routing failure.\n",
429                               afs_inet_ntoa_r(thost->host, hoststr), ntohs(thost->port), afs_inet_ntoa_r(rxr_HostOf(*tconn), hoststr2),
430                               ntohs(rxr_PortOf(*tconn))));
431                     code = -1;
432                 }
433             }
434         }
435     } else {
436         code = 0;
437     }
438
439     h_ReleaseClient_r(tclient);
440     h_Unlock_r(thost);
441     H_UNLOCK;
442     *ahostp = thost;
443     return code;
444
445 }                               /*CallPreamble */
446
447
448 static afs_int32
449 CallPostamble(struct rx_connection *aconn, afs_int32 ret,
450               struct host *ahost)
451 {
452     struct host *thost;
453     struct client *tclient;
454     int translate = 0;
455
456     H_LOCK;
457     tclient = h_FindClient_r(aconn);
458     if (!tclient)
459         goto busyout;
460     thost = tclient->host;
461     if (thost->hostFlags & HERRORTRANS)
462         translate = 1;
463     h_ReleaseClient_r(tclient);
464
465     if (ahost) {
466             if (ahost != thost) {
467                     /* host/client recycle */
468                     char hoststr[16], hoststr2[16];
469                     ViceLog(0, ("CallPostamble: ahost %s:%d (%p) != thost "
470                                 "%s:%d (%p)\n",
471                                 afs_inet_ntoa_r(ahost->host, hoststr),
472                                 ntohs(ahost->port),
473                                 ahost,
474                                 afs_inet_ntoa_r(thost->host, hoststr2),
475                                 ntohs(thost->port),
476                                 thost));
477             }
478             /* return the reference taken in CallPreamble */
479             h_Release_r(ahost);
480     } else {
481             char hoststr[16];
482             ViceLog(0, ("CallPostamble: null ahost for thost %s:%d (%p)\n",
483                         afs_inet_ntoa_r(thost->host, hoststr),
484                         ntohs(thost->port),
485                         thost));
486     }
487
488     /* return the reference taken in local h_FindClient_r--h_ReleaseClient_r
489      * does not decrement refcount on client->host */
490     h_Release_r(thost);
491
492  busyout:
493     H_UNLOCK;
494     return (translate ? sys_error_to_et(ret) : ret);
495 }                               /*CallPostamble */
496
497 /*
498  * Returns the volume and vnode pointers associated with file Fid; the lock
499  * type on the vnode is set to lock. Note that both volume/vnode's ref counts
500  * are incremented and they must be eventualy released.
501  */
502 static afs_int32
503 CheckVnodeWithCall(AFSFid * fid, Volume ** volptr, struct VCallByVol *cbv,
504                    Vnode ** vptr, int lock)
505 {
506     Error fileCode = 0;
507     Error local_errorCode, errorCode = -1;
508     static struct timeval restartedat = { 0, 0 };
509
510     if (fid->Volume == 0 || fid->Vnode == 0)    /* not: || fid->Unique == 0) */
511         return (EINVAL);
512     if ((*volptr) == 0) {
513         extern int VInit;
514
515         while (1) {
516             int restarting =
517 #ifdef AFS_DEMAND_ATTACH_FS
518                 VSALVAGE
519 #else
520                 VRESTARTING
521 #endif
522                 ;
523 #ifdef AFS_PTHREAD_ENV
524             static const struct timespec timeout_ts = { 0, 0 };
525             static const struct timespec * const ts = &timeout_ts;
526 #else
527             static const struct timespec * const ts = NULL;
528 #endif
529
530             errorCode = 0;
531             *volptr = VGetVolumeWithCall(&local_errorCode, &errorCode,
532                                                fid->Volume, ts, cbv);
533             if (!errorCode) {
534                 osi_Assert(*volptr);
535                 break;
536             }
537             if ((errorCode == VOFFLINE) && (VInit < 2)) {
538                 /* The volume we want may not be attached yet because
539                  * the volume initialization is not yet complete.
540                  * We can do several things:
541                  *     1.  return -1, which will cause users to see
542                  *         "connection timed out".  This is more or
543                  *         less the same as always, except that the servers
544                  *         may appear to bounce up and down while they
545                  *         are actually restarting.
546                  *     2.  return VBUSY which will cause clients to
547                  *         sleep and retry for 6.5 - 15 minutes, depending
548                  *         on what version of the CM they are running.  If
549                  *         the file server takes longer than that interval
550                  *         to attach the desired volume, then the application
551                  *         will see an ENODEV or EIO.  This approach has
552                  *         the advantage that volumes which have been attached
553                  *         are immediately available, it keeps the server's
554                  *         immediate backlog low, and the call is interruptible
555                  *         by the user.  Users see "waiting for busy volume."
556                  *     3.  sleep here and retry.  Some people like this approach
557                  *         because there is no danger of seeing errors.  However,
558                  *         this approach only works with a bounded number of
559                  *         clients, since the pending queues will grow without
560                  *         stopping.  It might be better to find a way to take
561                  *         this call and stick it back on a queue in order to
562                  *         recycle this thread for a different request.
563                  *     4.  Return a new error code, which new cache managers will
564                  *         know enough to interpret as "sleep and retry", without
565                  *         the upper bound of 6-15 minutes that is imposed by the
566                  *         VBUSY handling.  Users will see "waiting for
567                  *         busy volume," so they know that something is
568                  *         happening.  Old cache managers must be able to do
569                  *         something reasonable with this, for instance, mark the
570                  *         server down.  Fortunately, any error code < 0
571                  *         will elicit that behavior. See #1.
572                  *     5.  Some combination of the above.  I like doing #2 for 10
573                  *         minutes, followed by #4.  3.1b and 3.2 cache managers
574                  *         will be fine as long as the restart period is
575                  *         not longer than 6.5 minutes, otherwise they may
576                  *         return ENODEV to users.  3.3 cache managers will be
577                  *         fine for 10 minutes, then will return
578                  *         ETIMEDOUT.  3.4 cache managers will just wait
579                  *         until the call works or fails definitively.
580                  *  NB. The problem with 2,3,4,5 is that old clients won't
581                  *  fail over to an alternate read-only replica while this
582                  *  server is restarting.  3.4 clients will fail over right away.
583                  */
584                 if (restartedat.tv_sec == 0) {
585                     /* I'm not really worried about when we restarted, I'm   */
586                     /* just worried about when the first VBUSY was returned. */
587                     FT_GetTimeOfDay(&restartedat, 0);
588                     if (busyonrst) {
589                         FS_LOCK;
590                         afs_perfstats.fs_nBusies++;
591                         FS_UNLOCK;
592                     }
593                     return (busyonrst ? VBUSY : restarting);
594                 } else {
595                     struct timeval now;
596                     FT_GetTimeOfDay(&now, 0);
597                     if ((now.tv_sec - restartedat.tv_sec) < (11 * 60)) {
598                         if (busyonrst) {
599                             FS_LOCK;
600                             afs_perfstats.fs_nBusies++;
601                             FS_UNLOCK;
602                         }
603                         return (busyonrst ? VBUSY : restarting);
604                     } else {
605                         return (restarting);
606                     }
607                 }
608             }
609             /* allow read operations on busy volume.
610              * must check local_errorCode because demand attach fs
611              * can have local_errorCode == VSALVAGING, errorCode == VBUSY */
612             else if (local_errorCode == VBUSY && lock == READ_LOCK) {
613 #ifdef AFS_DEMAND_ATTACH_FS
614                 /* DAFS case is complicated by the fact that local_errorCode can
615                  * be VBUSY in cases where the volume is truly offline */
616                 if (!*volptr) {
617                     /* volume is in VOL_STATE_UNATTACHED */
618                     return (errorCode);
619                 }
620 #endif /* AFS_DEMAND_ATTACH_FS */
621                 errorCode = 0;
622                 break;
623             } else if (errorCode)
624                 return (errorCode);
625         }
626     }
627     osi_Assert(*volptr);
628
629     /* get the vnode  */
630     *vptr = VGetVnode(&errorCode, *volptr, fid->Vnode, lock);
631     if (errorCode)
632         return (errorCode);
633     if ((*vptr)->disk.uniquifier != fid->Unique) {
634         VPutVnode(&fileCode, *vptr);
635         osi_Assert(fileCode == 0);
636         *vptr = 0;
637         return (VNOVNODE);      /* return the right error code, at least */
638     }
639     return (0);
640 }                               /*CheckVnode */
641
642 static_inline afs_int32
643 CheckVnode(AFSFid * fid, Volume ** volptr, Vnode ** vptr, int lock)
644 {
645     return CheckVnodeWithCall(fid, volptr, NULL, vptr, lock);
646 }
647
648 /*
649  * This routine returns the ACL associated with the targetptr. If the
650  * targetptr isn't a directory, we access its parent dir and get the ACL
651  * thru the parent; in such case the parent's vnode is returned in
652  * READ_LOCK mode.
653  */
654 static afs_int32
655 SetAccessList(Vnode ** targetptr, Volume ** volume,
656               struct acl_accessList **ACL, int *ACLSize, Vnode ** parent,
657               AFSFid * Fid, int Lock)
658 {
659     if ((*targetptr)->disk.type == vDirectory) {
660         *parent = 0;
661         *ACL = VVnodeACL(*targetptr);
662         *ACLSize = VAclSize(*targetptr);
663         return (0);
664     } else {
665         osi_Assert(Fid != 0);
666         while (1) {
667             VnodeId parentvnode;
668             Error errorCode = 0;
669
670             parentvnode = (*targetptr)->disk.parent;
671             VPutVnode(&errorCode, *targetptr);
672             *targetptr = 0;
673             if (errorCode)
674                 return (errorCode);
675             *parent = VGetVnode(&errorCode, *volume, parentvnode, READ_LOCK);
676             if (errorCode)
677                 return (errorCode);
678             *ACL = VVnodeACL(*parent);
679             *ACLSize = VAclSize(*parent);
680             if ((errorCode = CheckVnode(Fid, volume, targetptr, Lock)) != 0)
681                 return (errorCode);
682             if ((*targetptr)->disk.parent != parentvnode) {
683                 VPutVnode(&errorCode, *parent);
684                 *parent = 0;
685                 if (errorCode)
686                     return (errorCode);
687             } else
688                 return (0);
689         }
690     }
691
692 }                               /*SetAccessList */
693
694 /* Must not be called with H_LOCK held */
695 static void
696 client_CheckRights(struct client *client, struct acl_accessList *ACL,
697                    afs_int32 *rights)
698 {
699     *rights = 0;
700     ObtainReadLock(&client->lock);
701     if (client->CPS.prlist_len > 0 && !client->deleted &&
702         client->host && !(client->host->hostFlags & HOSTDELETED))
703         acl_CheckRights(ACL, &client->CPS, rights);
704     ReleaseReadLock(&client->lock);
705 }
706
707 /* Must not be called with H_LOCK held */
708 static afs_int32
709 client_HasAsMember(struct client *client, afs_int32 id)
710 {
711     afs_int32 code = 0;
712
713     ObtainReadLock(&client->lock);
714     if (client->CPS.prlist_len > 0 && !client->deleted &&
715         client->host && !(client->host->hostFlags & HOSTDELETED))
716         code = acl_IsAMember(id, &client->CPS);
717     ReleaseReadLock(&client->lock);
718     return code;
719 }
720
721 /*
722  * Compare the directory's ACL with the user's access rights in the client
723  * connection and return the user's and everybody else's access permissions
724  * in rights and anyrights, respectively
725  */
726 static afs_int32
727 GetRights(struct client *client, struct acl_accessList *ACL,
728           afs_int32 * rights, afs_int32 * anyrights)
729 {
730     extern prlist SystemAnyUserCPS;
731     afs_int32 hrights = 0;
732 #ifndef AFS_PTHREAD_ENV
733     int code;
734 #endif
735
736     if (acl_CheckRights(ACL, &SystemAnyUserCPS, anyrights) != 0) {
737         ViceLog(0, ("CheckRights failed\n"));
738         *anyrights = 0;
739     }
740     *rights = 0;
741
742     client_CheckRights(client, ACL, rights);
743
744     /* wait if somebody else is already doing the getCPS call */
745     H_LOCK;
746     while (client->host->hostFlags & HCPS_INPROGRESS) {
747         client->host->hostFlags |= HCPS_WAITING;        /* I am waiting */
748 #ifdef AFS_PTHREAD_ENV
749         CV_WAIT(&client->host->cond, &host_glock_mutex);
750 #else /* AFS_PTHREAD_ENV */
751         if ((code =
752              LWP_WaitProcess(&(client->host->hostFlags))) != LWP_SUCCESS)
753             ViceLog(0, ("LWP_WaitProcess returned %d\n", code));
754 #endif /* AFS_PTHREAD_ENV */
755     }
756
757     if (!client->host->hcps.prlist_len || !client->host->hcps.prlist_val) {
758         char hoststr[16];
759         ViceLog(5,
760                 ("CheckRights: len=%u, for host=%s:%d\n",
761                  client->host->hcps.prlist_len,
762                  afs_inet_ntoa_r(client->host->host, hoststr),
763                  ntohs(client->host->port)));
764     } else
765         acl_CheckRights(ACL, &client->host->hcps, &hrights);
766     H_UNLOCK;
767     /* Allow system:admin the rights given with the -implicit option */
768     if (client_HasAsMember(client, SystemId))
769         *rights |= implicitAdminRights;
770
771     *rights |= hrights;
772     *anyrights |= hrights;
773
774     return (0);
775
776 }                               /*GetRights */
777
778 /*
779  * VanillaUser returns 1 (true) if the user is a vanilla user (i.e., not
780  * a System:Administrator)
781  */
782 static afs_int32
783 VanillaUser(struct client *client)
784 {
785     if (client_HasAsMember(client, SystemId))
786         return (0);             /* not a system administrator, then you're "vanilla" */
787     return (1);
788
789 }                               /*VanillaUser */
790
791
792 /*
793  * This unusual afs_int32-parameter routine encapsulates all volume package related
794  * operations together in a single function; it's called by almost all AFS
795  * interface calls.
796  */
797 static afs_int32
798 GetVolumePackageWithCall(struct rx_connection *tcon, struct VCallByVol *cbv,
799                          AFSFid * Fid, Volume ** volptr, Vnode ** targetptr,
800                          int chkforDir, Vnode ** parent, struct client **client,
801                          int locktype, afs_int32 * rights, afs_int32 * anyrights)
802 {
803     struct acl_accessList *aCL; /* Internal access List */
804     int aCLSize;                /* size of the access list */
805     Error errorCode = 0;                /* return code to caller */
806
807     if ((errorCode = CheckVnodeWithCall(Fid, volptr, cbv, targetptr, locktype)))
808         return (errorCode);
809     if (chkforDir) {
810         if (chkforDir == MustNOTBeDIR
811             && ((*targetptr)->disk.type == vDirectory))
812             return (EISDIR);
813         else if (chkforDir == MustBeDIR
814                  && ((*targetptr)->disk.type != vDirectory))
815             return (ENOTDIR);
816     }
817     if ((errorCode =
818          SetAccessList(targetptr, volptr, &aCL, &aCLSize, parent,
819                        (chkforDir == MustBeDIR ? (AFSFid *) 0 : Fid),
820                        (chkforDir == MustBeDIR ? 0 : locktype))) != 0)
821         return (errorCode);
822     if (chkforDir == MustBeDIR)
823         osi_Assert((*parent) == 0);
824     if (!(*client)) {
825         if ((errorCode = GetClient(tcon, client)) != 0)
826             return (errorCode);
827         if (!(*client))
828             return (EINVAL);
829     }
830     GetRights(*client, aCL, rights, anyrights);
831     /* ok, if this is not a dir, set the PRSFS_ADMINISTER bit iff we're the owner */
832     if ((*targetptr)->disk.type != vDirectory) {
833         /* anyuser can't be owner, so only have to worry about rights, not anyrights */
834         if ((*targetptr)->disk.owner == (*client)->ViceId)
835             (*rights) |= PRSFS_ADMINISTER;
836         else
837             (*rights) &= ~PRSFS_ADMINISTER;
838     }
839 #ifdef ADMIN_IMPLICIT_LOOKUP
840     /* admins get automatic lookup on everything */
841     if (!VanillaUser(*client))
842         (*rights) |= PRSFS_LOOKUP;
843 #endif /* ADMIN_IMPLICIT_LOOKUP */
844     return errorCode;
845
846 }                               /*GetVolumePackage */
847
848 static_inline afs_int32
849 GetVolumePackage(struct rx_connection *tcon, AFSFid * Fid, Volume ** volptr,
850                  Vnode ** targetptr, int chkforDir, Vnode ** parent,
851                  struct client **client, int locktype, afs_int32 * rights,
852                  afs_int32 * anyrights)
853 {
854     return GetVolumePackageWithCall(tcon, NULL, Fid, volptr, targetptr,
855                                     chkforDir, parent, client, locktype,
856                                     rights, anyrights);
857 }
858
859
860 /*
861  * This is the opposite of GetVolumePackage(), and is always used at the end of
862  * AFS calls to put back all used vnodes and the volume in the proper order!
863  */
864 static void
865 PutVolumePackageWithCall(Vnode * parentwhentargetnotdir, Vnode * targetptr,
866                          Vnode * parentptr, Volume * volptr,
867                          struct client **client, struct VCallByVol *cbv)
868 {
869     Error fileCode = 0;         /* Error code returned by the volume package */
870
871     if (parentwhentargetnotdir) {
872         VPutVnode(&fileCode, parentwhentargetnotdir);
873         osi_Assert(!fileCode || (fileCode == VSALVAGE));
874     }
875     if (targetptr) {
876         VPutVnode(&fileCode, targetptr);
877         osi_Assert(!fileCode || (fileCode == VSALVAGE));
878     }
879     if (parentptr) {
880         VPutVnode(&fileCode, parentptr);
881         osi_Assert(!fileCode || (fileCode == VSALVAGE));
882     }
883     if (volptr) {
884         VPutVolumeWithCall(volptr, cbv);
885     }
886     if (*client) {
887         PutClient(client);
888     }
889 }                               /*PutVolumePackage */
890
891 static_inline void
892 PutVolumePackage(Vnode * parentwhentargetnotdir, Vnode * targetptr,
893                  Vnode * parentptr, Volume * volptr, struct client **client)
894 {
895     PutVolumePackageWithCall(parentwhentargetnotdir, targetptr, parentptr,
896                              volptr, client, NULL);
897 }
898
899 static int
900 VolumeOwner(struct client *client, Vnode * targetptr)
901 {
902     afs_int32 owner = V_owner(targetptr->volumePtr);    /* get volume owner */
903
904     if (owner >= 0)
905         return (client->ViceId == owner);
906     else {
907         /*
908          * We don't have to check for host's cps since only regular
909          * viceid are volume owners.
910          */
911         return (client_HasAsMember(client, owner));
912     }
913
914 }                               /*VolumeOwner */
915
916 static int
917 VolumeRootVnode(Vnode * targetptr)
918 {
919     return ((targetptr->vnodeNumber == ROOTVNODE)
920             && (targetptr->disk.uniquifier == 1));
921
922 }                               /*VolumeRootVnode */
923
924 /*
925  * Check if target file has the proper access permissions for the Fetch
926  * (FetchData, FetchACL, FetchStatus) and Store (StoreData, StoreACL,
927  * StoreStatus) related calls
928  */
929 /* this code should probably just set a "priv" flag where all the audit events
930  * are now, and only generate the audit event once at the end of the routine,
931  * thus only generating the event if all the checks succeed, but only because
932  * of the privilege       XXX
933  */
934 static afs_int32
935 Check_PermissionRights(Vnode * targetptr, struct client *client,
936                        afs_int32 rights, int CallingRoutine,
937                        AFSStoreStatus * InStatus)
938 {
939     Error errorCode = 0;
940 #define OWNSp(client, target) ((client)->ViceId == (target)->disk.owner)
941 #define CHOWN(i,t) (((i)->Mask & AFS_SETOWNER) &&((i)->Owner != (t)->disk.owner))
942 #define CHGRP(i,t) (((i)->Mask & AFS_SETGROUP) &&((i)->Group != (t)->disk.group))
943
944     if (CallingRoutine & CHK_FETCH) {
945         if (CallingRoutine == CHK_FETCHDATA || VanillaUser(client)) {
946             if (targetptr->disk.type == vDirectory
947                 || targetptr->disk.type == vSymlink) {
948                 if (!(rights & PRSFS_LOOKUP)
949 #ifdef ADMIN_IMPLICIT_LOOKUP
950                     /* grant admins fetch on all directories */
951                     && VanillaUser(client)
952 #endif /* ADMIN_IMPLICIT_LOOKUP */
953                     && !VolumeOwner(client, targetptr))
954                     return (EACCES);
955             } else {            /* file */
956                 /* must have read access, or be owner and have insert access */
957                 if (!(rights & PRSFS_READ)
958                     && !((OWNSp(client, targetptr) && (rights & PRSFS_INSERT)
959                           && (client->ViceId != AnonymousID))))
960                     return (EACCES);
961             }
962             if (CallingRoutine == CHK_FETCHDATA
963                 && targetptr->disk.type == vFile)
964 #ifdef USE_GROUP_PERMS
965                 if (!OWNSp(client, targetptr)
966                     && !client_HasAsMember(client, targetptr->disk.owner)) {
967                     errorCode =
968                         (((GROUPREAD | GROUPEXEC) & targetptr->disk.modeBits)
969                          ? 0 : EACCES);
970                 } else {
971                     errorCode =
972                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.modeBits)
973                          ? 0 : EACCES);
974                 }
975 #else
976                 /*
977                  * The check with the ownership below is a kludge to allow
978                  * reading of files created with no read permission. The owner
979                  * of the file is always allowed to read it.
980                  */
981                 if ((client->ViceId != targetptr->disk.owner)
982                     && VanillaUser(client))
983                     errorCode =
984                         (((OWNERREAD | OWNEREXEC) & targetptr->disk.
985                           modeBits) ? 0 : EACCES);
986 #endif
987         } else {                /*  !VanillaUser(client) && !FetchData */
988
989             osi_audit(PrivilegeEvent, 0, AUD_ID,
990                       (client ? client->ViceId : 0), AUD_INT, CallingRoutine,
991                       AUD_END);
992         }
993     } else {                    /* a store operation */
994         if ((rights & PRSFS_INSERT) && OWNSp(client, targetptr)
995             && (CallingRoutine != CHK_STOREACL)
996             && (targetptr->disk.type == vFile)) {
997             /* bypass protection checks on first store after a create
998              * for the creator; also prevent chowns during this time
999              * unless you are a system administrator */
1000           /******  InStatus->Owner && UnixModeBits better be SET!! */
1001             if (CHOWN(InStatus, targetptr) || CHGRP(InStatus, targetptr)) {
1002                 if (readonlyServer)
1003                     return (VREADONLY);
1004                 else if (VanillaUser(client))
1005                     return (EPERM);     /* Was EACCES */
1006                 else
1007                     osi_audit(PrivilegeEvent, 0, AUD_ID,
1008                               (client ? client->ViceId : 0), AUD_INT,
1009                               CallingRoutine, AUD_END);
1010             }
1011         } else {
1012             if (CallingRoutine != CHK_STOREDATA && !VanillaUser(client)) {
1013                 osi_audit(PrivilegeEvent, 0, AUD_ID,
1014                           (client ? client->ViceId : 0), AUD_INT,
1015                           CallingRoutine, AUD_END);
1016             } else {
1017                 if (readonlyServer) {
1018                     return (VREADONLY);
1019                 }
1020                 if (CallingRoutine == CHK_STOREACL) {
1021                     if (!(rights & PRSFS_ADMINISTER)
1022                         && !VolumeOwner(client, targetptr))
1023                         return (EACCES);
1024                 } else {        /* store data or status */
1025                     /* watch for chowns and chgrps */
1026                     if (CHOWN(InStatus, targetptr)
1027                         || CHGRP(InStatus, targetptr)) {
1028                         if (readonlyServer)
1029                             return (VREADONLY);
1030                         else if (VanillaUser(client))
1031                             return (EPERM);     /* Was EACCES */
1032                         else
1033                             osi_audit(PrivilegeEvent, 0, AUD_ID,
1034                                       (client ? client->ViceId : 0), AUD_INT,
1035                                       CallingRoutine, AUD_END);
1036                     }
1037                     /* must be sysadmin to set suid/sgid bits */
1038                     if ((InStatus->Mask & AFS_SETMODE) &&
1039 #ifdef AFS_NT40_ENV
1040                         (InStatus->UnixModeBits & 0xc00) != 0) {
1041 #else
1042                         (InStatus->UnixModeBits & (S_ISUID | S_ISGID)) != 0) {
1043 #endif
1044                         if (readonlyServer)
1045                             return (VREADONLY);
1046                         if (VanillaUser(client))
1047                             return (EACCES);
1048                         else
1049                             osi_audit(PrivSetID, 0, AUD_ID,
1050                                       (client ? client->ViceId : 0), AUD_INT,
1051                                       CallingRoutine, AUD_END);
1052                     }
1053                     if (CallingRoutine == CHK_STOREDATA) {
1054                         if (readonlyServer)
1055                             return (VREADONLY);
1056                         if (!(rights & PRSFS_WRITE))
1057                             return (EACCES);
1058                         /* Next thing is tricky.  We want to prevent people
1059                          * from writing files sans 0200 bit, but we want
1060                          * creating new files with 0444 mode to work.  We
1061                          * don't check the 0200 bit in the "you are the owner"
1062                          * path above, but here we check the bit.  However, if
1063                          * you're a system administrator, we ignore the 0200
1064                          * bit anyway, since you may have fchowned the file,
1065                          * too */
1066 #ifdef USE_GROUP_PERMS
1067                         if ((targetptr->disk.type == vFile)
1068                             && VanillaUser(client)) {
1069                             if (!OWNSp(client, targetptr)
1070                                 && !client_HasAsMember(client, targetptr->disk.owner)) {
1071                                 errorCode =
1072                                     ((GROUPWRITE & targetptr->disk.modeBits)
1073                                      ? 0 : EACCES);
1074                             } else {
1075                                 errorCode =
1076                                     ((OWNERWRITE & targetptr->disk.modeBits)
1077                                      ? 0 : EACCES);
1078                             }
1079                         } else
1080 #endif
1081                             if ((targetptr->disk.type != vDirectory)
1082                                 && (!(targetptr->disk.modeBits & OWNERWRITE))) {
1083                             if (readonlyServer)
1084                                 return (VREADONLY);
1085                             if (VanillaUser(client))
1086                                 return (EACCES);
1087                             else
1088                                 osi_audit(PrivilegeEvent, 0, AUD_ID,
1089                                           (client ? client->ViceId : 0),
1090                                           AUD_INT, CallingRoutine, AUD_END);
1091                         }
1092                     } else {    /* a status store */
1093                         if (readonlyServer)
1094                             return (VREADONLY);
1095                         if (targetptr->disk.type == vDirectory) {
1096                             if (!(rights & PRSFS_DELETE)
1097                                 && !(rights & PRSFS_INSERT))
1098                                 return (EACCES);
1099                         } else {        /* a file  or symlink */
1100                             if (!(rights & PRSFS_WRITE))
1101                                 return (EACCES);
1102                         }
1103                     }
1104                 }
1105             }
1106         }
1107     }
1108     return (errorCode);
1109
1110 }                               /*Check_PermissionRights */
1111
1112
1113 /*
1114  * The Access List information is converted from its internal form in the
1115  * target's vnode buffer (or its parent vnode buffer if not a dir), to an
1116  * external form and returned back to the caller, via the AccessList
1117  * structure
1118  */
1119 static afs_int32
1120 RXFetch_AccessList(Vnode * targetptr, Vnode * parentwhentargetnotdir,
1121                    struct AFSOpaque *AccessList)
1122 {
1123     char *eACL;                 /* External access list placeholder */
1124
1125     if (acl_Externalize_pr
1126         (hpr_IdToName, (targetptr->disk.type ==
1127           vDirectory ? VVnodeACL(targetptr) :
1128           VVnodeACL(parentwhentargetnotdir)), &eACL) != 0) {
1129         return EIO;
1130     }
1131     if ((strlen(eACL) + 1) > AFSOPAQUEMAX) {
1132         acl_FreeExternalACL(&eACL);
1133         return (E2BIG);
1134     } else {
1135         strcpy((char *)(AccessList->AFSOpaque_val), (char *)eACL);
1136         AccessList->AFSOpaque_len = strlen(eACL) + 1;
1137     }
1138     acl_FreeExternalACL(&eACL);
1139     return (0);
1140
1141 }                               /*RXFetch_AccessList */
1142
1143
1144 /*
1145  * The Access List information is converted from its external form in the
1146  * input AccessList structure to the internal representation and copied into
1147  * the target dir's vnode storage.
1148  */
1149 static afs_int32
1150 RXStore_AccessList(Vnode * targetptr, struct AFSOpaque *AccessList)
1151 {
1152     struct acl_accessList *newACL;      /* PlaceHolder for new access list */
1153
1154     if (acl_Internalize_pr(hpr_NameToId, AccessList->AFSOpaque_val, &newACL)
1155         != 0)
1156         return (EINVAL);
1157     if ((newACL->size + 4) > VAclSize(targetptr))
1158         return (E2BIG);
1159     memcpy((char *)VVnodeACL(targetptr), (char *)newACL, (int)(newACL->size));
1160     acl_FreeACL(&newACL);
1161     return (0);
1162
1163 }                               /*RXStore_AccessList */
1164
1165
1166 /* In our current implementation, each successive data store (new file
1167  * data version) creates a new inode. This function creates the new
1168  * inode, copies the old inode's contents to the new one, remove the old
1169  * inode (i.e. decrement inode count -- if it's currently used the delete
1170  * will be delayed), and modify some fields (i.e. vnode's
1171  * disk.inodeNumber and cloned)
1172  */
1173 #define COPYBUFFSIZE    8192
1174 #define MAXFSIZE (~(afs_fsize_t) 0)
1175 static int
1176 CopyOnWrite(Vnode * targetptr, Volume * volptr, afs_foff_t off, afs_fsize_t len)
1177 {
1178     Inode ino, nearInode;
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;            /* 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);
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);
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     }
3771
3772     /* If the new name exists already, delete it and the file it points to */
3773     doDelete = 0;
3774     if (newfileptr) {
3775         /* Delete NewName from its directory */
3776         code = afs_dir_Delete(&newdir, NewName);
3777         osi_Assert(code == 0);
3778
3779         /* Drop the link count */
3780         newfileptr->disk.linkCount--;
3781         if (newfileptr->disk.linkCount == 0) {  /* Link count 0 - delete */
3782             afs_fsize_t newSize;
3783             VN_GET_LEN(newSize, newfileptr);
3784             VAdjustDiskUsage((Error *) & errorCode, volptr,
3785                              (afs_sfsize_t) - nBlocks(newSize), 0);
3786             if (VN_GET_INO(newfileptr)) {
3787                 IH_REALLYCLOSE(newfileptr->handle);
3788                 errorCode =
3789                     IH_DEC(V_linkHandle(volptr), VN_GET_INO(newfileptr),
3790                            V_parentId(volptr));
3791                 IH_RELEASE(newfileptr->handle);
3792                 if (errorCode == -1) {
3793                     ViceLog(0,
3794                             ("Del: inode=%s, name=%s, errno=%d\n",
3795                              PrintInode(stmp, VN_GET_INO(newfileptr)),
3796                              NewName, errno));
3797                     if ((errno != ENOENT) && (errno != EIO)
3798                         && (errno != ENXIO))
3799                         ViceLog(0, ("Do we need to fsck?"));
3800                 }
3801             }
3802             VN_SET_INO(newfileptr, (Inode) 0);
3803             newfileptr->delete = 1;     /* Mark NewName vnode to delete */
3804             doDelete = 1;
3805         } else {
3806             /* Link count did not drop to zero.
3807              * Mark NewName vnode as changed - updates stime.
3808              */
3809             newfileptr->changed_newTime = 1;
3810         }
3811     }
3812
3813     /*
3814      * If the create below fails, and the delete above worked, we have
3815      * removed the new name and not replaced it.  This is not very likely,
3816      * but possible.  We could try to put the old file back, but it is
3817      * highly unlikely that it would work since it would involve issuing
3818      * another create.
3819      */
3820     if ((errorCode = afs_dir_Create(&newdir, NewName, &fileFid)))
3821         goto Bad_Rename;
3822
3823     /* Delete the old name */
3824     osi_Assert(afs_dir_Delete(&olddir, OldName) == 0);
3825
3826     /* if the directory length changes, reflect it in the statistics */
3827 #if FS_STATS_DETAILED
3828     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
3829                              oldvptr->disk.linkCount, client->InSameNetwork);
3830     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
3831                              newvptr->disk.linkCount, client->InSameNetwork);
3832 #else
3833     Update_ParentVnodeStatus(oldvptr, volptr, &olddir, client->ViceId,
3834                              oldvptr->disk.linkCount);
3835     Update_ParentVnodeStatus(newvptr, volptr, &newdir, client->ViceId,
3836                              newvptr->disk.linkCount);
3837 #endif /* FS_STATS_DETAILED */
3838
3839     if (oldvptr == newvptr)
3840         oldvptr->disk.dataVersion--;    /* Since it was bumped by 2! */
3841
3842     if (fileptr->disk.parent != newvptr->vnodeNumber) {
3843         fileptr->disk.parent = newvptr->vnodeNumber;
3844         fileptr->changed_newTime = 1;
3845     }
3846
3847     /* if we are dealing with a rename of a directory, and we need to
3848      * update the .. entry of that directory */
3849     if (updatefile) {
3850         osi_Assert(!fileptr->disk.cloned);
3851
3852         fileptr->changed_newTime = 1;   /* status change of moved file */
3853
3854         /* fix .. to point to the correct place */
3855         afs_dir_Delete(&filedir, ".."); /* No assert--some directories may be bad */
3856         osi_Assert(afs_dir_Create(&filedir, "..", NewDirFid) == 0);
3857         fileptr->disk.dataVersion++;
3858
3859         /* if the parent directories are different the link counts have to be   */
3860         /* changed due to .. in the renamed directory */
3861         if (oldvptr != newvptr) {
3862             oldvptr->disk.linkCount--;
3863             newvptr->disk.linkCount++;
3864         }
3865     }
3866
3867     /* set up return status */
3868     GetStatus(oldvptr, OutOldDirStatus, rights, anyrights, 0);
3869     GetStatus(newvptr, OutNewDirStatus, newrights, newanyrights, 0);
3870     if (newfileptr && doDelete) {
3871         DeleteFileCallBacks(&newFileFid);       /* no other references */
3872     }
3873
3874     DFlush();
3875
3876     /* convert the write locks to a read locks before breaking callbacks */
3877     VVnodeWriteToRead(&errorCode, newvptr);
3878     osi_Assert(!errorCode || errorCode == VSALVAGE);
3879     if (oldvptr != newvptr) {
3880         VVnodeWriteToRead(&errorCode, oldvptr);
3881         osi_Assert(!errorCode || errorCode == VSALVAGE);
3882     }
3883     if (newfileptr && !doDelete) {
3884         /* convert the write lock to a read lock before breaking callbacks */
3885         VVnodeWriteToRead(&errorCode, newfileptr);
3886         osi_Assert(!errorCode || errorCode == VSALVAGE);
3887     }
3888
3889     /* break call back on NewDirFid, OldDirFid, NewDirFid and newFileFid  */
3890     BreakCallBack(client->host, NewDirFid, 0);
3891     if (oldvptr != newvptr) {
3892         BreakCallBack(client->host, OldDirFid, 0);
3893     }
3894     if (updatefile) {
3895         /* if a dir moved, .. changed */
3896         /* we do not give an AFSFetchStatus structure back to the
3897          * originating client, and the file's status has changed, so be
3898          * sure to send a callback break. In theory the client knows
3899          * enough to know that the callback could be broken implicitly,
3900          * but that may not be clear, and some client implementations
3901          * may not know to. */
3902         BreakCallBack(client->host, &fileFid, 1);
3903     }
3904     if (newfileptr) {
3905         /* Note:  it is not necessary to break the callback */
3906         if (doDelete)
3907             DeleteFileCallBacks(&newFileFid);   /* no other references */
3908         else
3909             /* other's still exist (with wrong link count) */
3910             BreakCallBack(client->host, &newFileFid, 1);
3911     }
3912
3913   Bad_Rename:
3914     if (newfileptr) {
3915         VPutVnode(&fileCode, newfileptr);
3916         osi_Assert(fileCode == 0);
3917     }
3918     (void)PutVolumePackage(fileptr, (newvptr && newvptr != oldvptr ?
3919                                      newvptr : 0), oldvptr, volptr, &client);
3920     FidZap(&olddir);
3921     FidZap(&newdir);
3922     FidZap(&filedir);
3923     FidZap(&newfiledir);
3924     ViceLog(2, ("SAFS_Rename returns %d\n", errorCode));
3925     return errorCode;
3926
3927 }                               /*SAFSS_Rename */
3928
3929
3930 afs_int32
3931 SRXAFS_Rename(struct rx_call * acall, struct AFSFid * OldDirFid,
3932               char *OldName, struct AFSFid * NewDirFid, char *NewName,
3933               struct AFSFetchStatus * OutOldDirStatus,
3934               struct AFSFetchStatus * OutNewDirStatus,
3935               struct AFSVolSync * Sync)
3936 {
3937     afs_int32 code;
3938     struct rx_connection *tcon;
3939     struct host *thost;
3940     struct client *t_client = NULL;     /* tmp ptr to client data */
3941     struct fsstats fsstats;
3942
3943     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_RENAME);
3944
3945     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
3946         goto Bad_Rename;
3947
3948     code =
3949         SAFSS_Rename(acall, OldDirFid, OldName, NewDirFid, NewName,
3950                      OutOldDirStatus, OutNewDirStatus, Sync);
3951
3952   Bad_Rename:
3953     code = CallPostamble(tcon, code, thost);
3954
3955     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3956
3957     fsstats_FinishOp(&fsstats, code);
3958
3959     osi_auditU(acall, RenameFileEvent, code,
3960                AUD_ID, t_client ? t_client->ViceId : 0,
3961                AUD_FID, OldDirFid, AUD_STR, OldName,
3962                AUD_FID, NewDirFid, AUD_STR, NewName, AUD_END);
3963     return code;
3964
3965 }                               /*SRXAFS_Rename */
3966
3967
3968 /*
3969  * This routine is called exclusively by SRXAFS_Symlink(), and should be
3970  * merged into it when possible.
3971  */
3972 static afs_int32
3973 SAFSS_Symlink(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
3974               char *LinkContents, struct AFSStoreStatus *InStatus,
3975               struct AFSFid *OutFid, struct AFSFetchStatus *OutFidStatus,
3976               struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
3977 {
3978     Vnode *parentptr = 0;       /* vnode of input Directory */
3979     Vnode *targetptr = 0;       /* vnode of the new link */
3980     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
3981     Error errorCode = 0;                /* error code */
3982     afs_sfsize_t len;
3983     int code = 0;
3984     DirHandle dir;              /* Handle for dir package I/O */
3985     Volume *volptr = 0;         /* pointer to the volume header */
3986     struct client *client = 0;  /* pointer to client structure */
3987     afs_int32 rights, anyrights;        /* rights for this and any user */
3988     struct client *t_client;    /* tmp ptr to client data */
3989     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
3990     FdHandle_t *fdP;
3991     struct rx_connection *tcon = rx_ConnectionOf(acall);
3992
3993     FidZero(&dir);
3994
3995     /* Get ptr to client data for user Id for logging */
3996     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
3997     logHostAddr.s_addr = rxr_HostOf(tcon);
3998     ViceLog(1,
3999             ("SAFS_Symlink %s to %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4000              LinkContents, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4001              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4002     FS_LOCK;
4003     AFSCallStats.Symlink++, AFSCallStats.TotalCalls++;
4004     FS_UNLOCK;
4005     if (!FileNameOK(Name)) {
4006         errorCode = EINVAL;
4007         goto Bad_SymLink;
4008     }
4009
4010     /*
4011      * Get the vnode and volume for the parent dir along with the caller's
4012      * rights to it
4013      */
4014     if ((errorCode =
4015          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4016                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4017                           &rights, &anyrights))) {
4018         goto Bad_SymLink;
4019     }
4020
4021     /* set volume synchronization information */
4022     SetVolumeSync(Sync, volptr);
4023
4024     /* Does the caller has insert (and write) access to the parent directory? */
4025     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4026         goto Bad_SymLink;
4027     }
4028
4029     /*
4030      * If we're creating a mount point (any x bits clear), we must have
4031      * administer access to the directory, too.  Always allow sysadmins
4032      * to do this.
4033      */
4034     if ((InStatus->Mask & AFS_SETMODE) && !(InStatus->UnixModeBits & 0111)) {
4035         if (readonlyServer) {
4036             errorCode = VREADONLY;
4037             goto Bad_SymLink;
4038         }
4039         /*
4040          * We have a mountpoint, 'cause we're trying to set the Unix mode
4041          * bits to something with some x bits missing (default mode bits
4042          * if AFS_SETMODE is false is 0777)
4043          */
4044         if (VanillaUser(client) && !(rights & PRSFS_ADMINISTER)) {
4045             errorCode = EACCES;
4046             goto Bad_SymLink;
4047         }
4048     }
4049
4050     /* get a new vnode for the symlink and set it up */
4051     if ((errorCode =
4052          Alloc_NewVnode(parentptr, &dir, volptr, &targetptr, Name, OutFid,
4053                         vSymlink, nBlocks(strlen((char *)LinkContents))))) {
4054         goto Bad_SymLink;
4055     }
4056
4057     /* update the status of the parent vnode */
4058 #if FS_STATS_DETAILED
4059     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4060                              parentptr->disk.linkCount,
4061                              client->InSameNetwork);
4062 #else
4063     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4064                              parentptr->disk.linkCount);
4065 #endif /* FS_STATS_DETAILED */
4066
4067     /* update the status of the new symbolic link file vnode */
4068     Update_TargetVnodeStatus(targetptr, TVS_SLINK, client, InStatus,
4069                              parentptr, volptr, strlen((char *)LinkContents));
4070
4071     /* Write the contents of the symbolic link name into the target inode */
4072     fdP = IH_OPEN(targetptr->handle);
4073     if (fdP == NULL) {
4074         (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4075                                volptr, &client);
4076         VTakeOffline(volptr);
4077         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
4078                     volptr->hashid));
4079         return EIO;
4080     }
4081     len = strlen((char *) LinkContents);
4082     code = (len == FDH_PWRITE(fdP, (char *) LinkContents, len, 0)) ? 0 : VDISKFULL;
4083     if (code)
4084         ViceLog(0, ("SAFSS_Symlink FDH_PWRITE failed for len=%d, Fid=%u.%d.%d\n", (int)len, OutFid->Volume, OutFid->Vnode, OutFid->Unique));
4085     FDH_CLOSE(fdP);
4086     /*
4087      * Set up and return modified status for the parent dir and new symlink
4088      * to caller.
4089      */
4090     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4091     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4092
4093     /* convert the write lock to a read lock before breaking callbacks */
4094     VVnodeWriteToRead(&errorCode, parentptr);
4095     osi_Assert(!errorCode || errorCode == VSALVAGE);
4096
4097     /* break call back on the parent dir */
4098     BreakCallBack(client->host, DirFid, 0);
4099
4100   Bad_SymLink:
4101     /* Write the all modified vnodes (parent, new files) and volume back */
4102     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4103                            volptr, &client);
4104     FidZap(&dir);
4105     ViceLog(2, ("SAFS_Symlink returns %d\n", errorCode));
4106     return ( errorCode ? errorCode : code );
4107
4108 }                               /*SAFSS_Symlink */
4109
4110
4111 afs_int32
4112 SRXAFS_Symlink(struct rx_call *acall,   /* Rx call */
4113                struct AFSFid *DirFid,   /* Parent dir's fid */
4114                char *Name,              /* File name to create */
4115                char *LinkContents,      /* Contents of the new created file */
4116                struct AFSStoreStatus *InStatus, /* Input status for the new symbolic link */
4117                struct AFSFid *OutFid,   /* Fid for newly created symbolic link */
4118                struct AFSFetchStatus *OutFidStatus,     /* Output status for new symbolic link */
4119                struct AFSFetchStatus *OutDirStatus,     /* Output status for parent dir */
4120                struct AFSVolSync *Sync)
4121 {
4122     afs_int32 code;
4123     struct rx_connection *tcon;
4124     struct host *thost;
4125     struct client *t_client = NULL;     /* tmp ptr to client data */
4126     struct fsstats fsstats;
4127
4128     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_SYMLINK);
4129
4130     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4131         goto Bad_Symlink;
4132
4133     code =
4134         SAFSS_Symlink(acall, DirFid, Name, LinkContents, InStatus, OutFid,
4135                       OutFidStatus, OutDirStatus, Sync);
4136
4137   Bad_Symlink:
4138     code = CallPostamble(tcon, code, thost);
4139
4140     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4141
4142     fsstats_FinishOp(&fsstats, code);
4143
4144     osi_auditU(acall, SymlinkEvent, code,
4145                AUD_ID, t_client ? t_client->ViceId : 0,
4146                AUD_FID, DirFid, AUD_STR, Name,
4147                AUD_FID, OutFid, AUD_STR, LinkContents, AUD_END);
4148     return code;
4149
4150 }                               /*SRXAFS_Symlink */
4151
4152
4153 /*
4154  * This routine is called exclusively by SRXAFS_Link(), and should be
4155  * merged into it when possible.
4156  */
4157 static afs_int32
4158 SAFSS_Link(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4159            struct AFSFid *ExistingFid, struct AFSFetchStatus *OutFidStatus,
4160            struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4161 {
4162     Vnode *parentptr = 0;       /* vnode of input Directory */
4163     Vnode *targetptr = 0;       /* vnode of the new file */
4164     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4165     Volume *volptr = 0;         /* pointer to the volume header */
4166     Error errorCode = 0;                /* error code */
4167     DirHandle dir;              /* Handle for dir package I/O */
4168     struct client *client = 0;  /* pointer to client structure */
4169     afs_int32 rights, anyrights;        /* rights for this and any user */
4170     struct client *t_client;    /* tmp ptr to client data */
4171     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4172     struct rx_connection *tcon = rx_ConnectionOf(acall);
4173
4174     FidZero(&dir);
4175
4176     /* Get ptr to client data for user Id for logging */
4177     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4178     logHostAddr.s_addr = rxr_HostOf(tcon);
4179     ViceLog(1,
4180             ("SAFS_Link %s,     Did = %u.%u.%u, Fid = %u.%u.%u, Host %s:%d, Id %d\n",
4181              Name, DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4182              ExistingFid->Volume, ExistingFid->Vnode, ExistingFid->Unique,
4183              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4184     FS_LOCK;
4185     AFSCallStats.Link++, AFSCallStats.TotalCalls++;
4186     FS_UNLOCK;
4187     if (DirFid->Volume != ExistingFid->Volume) {
4188         errorCode = EXDEV;
4189         goto Bad_Link;
4190     }
4191     if (!FileNameOK(Name)) {
4192         errorCode = EINVAL;
4193         goto Bad_Link;
4194     }
4195
4196     /*
4197      * Get the vnode and volume for the parent dir along with the caller's
4198      * rights to it
4199      */
4200     if ((errorCode =
4201          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4202                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4203                           &rights, &anyrights))) {
4204         goto Bad_Link;
4205     }
4206
4207     /* set volume synchronization information */
4208     SetVolumeSync(Sync, volptr);
4209
4210     /* Can the caller insert into the parent directory? */
4211     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4212         goto Bad_Link;
4213     }
4214
4215     if (((DirFid->Vnode & 1) && (ExistingFid->Vnode & 1)) || (DirFid->Vnode == ExistingFid->Vnode)) {   /* at present, */
4216         /* AFS fileservers always have directory vnodes that are odd.   */
4217         errorCode = EISDIR;
4218         goto Bad_Link;
4219     }
4220
4221     if (CheckLength(volptr, parentptr, -1)) {
4222         VTakeOffline(volptr);
4223         errorCode = VSALVAGE;
4224         goto Bad_Link;
4225     }
4226
4227     /* get the file vnode  */
4228     if ((errorCode =
4229          CheckVnode(ExistingFid, &volptr, &targetptr, WRITE_LOCK))) {
4230         goto Bad_Link;
4231     }
4232     if (targetptr->disk.type != vFile) {
4233         errorCode = EISDIR;
4234         goto Bad_Link;
4235     }
4236     if (targetptr->disk.parent != DirFid->Vnode) {
4237         errorCode = EXDEV;
4238         goto Bad_Link;
4239     }
4240     if (parentptr->disk.cloned) {
4241         ViceLog(25, ("Link : calling CopyOnWrite on  target dir\n"));
4242         if ((errorCode = CopyOnWrite(parentptr, volptr, 0, MAXFSIZE)))
4243             goto Bad_Link;      /* disk full error */
4244     }
4245
4246     /* add the name to the directory */
4247     SetDirHandle(&dir, parentptr);
4248     if ((errorCode = afs_dir_Create(&dir, Name, ExistingFid)))
4249         goto Bad_Link;
4250     DFlush();
4251
4252     /* update the status in the parent vnode */
4253     /**WARNING** --> disk.author SHOULDN'T be modified???? */
4254 #if FS_STATS_DETAILED
4255     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4256                              parentptr->disk.linkCount,
4257                              client->InSameNetwork);
4258 #else
4259     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4260                              parentptr->disk.linkCount);
4261 #endif /* FS_STATS_DETAILED */
4262
4263     targetptr->disk.linkCount++;
4264     targetptr->disk.author = client->ViceId;
4265     targetptr->changed_newTime = 1;     /* Status change of linked-to file */
4266
4267     /* set up return status */
4268     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4269     GetStatus(parentptr, OutDirStatus, rights, anyrights, 0);
4270
4271     /* convert the write locks to read locks before breaking callbacks */
4272     VVnodeWriteToRead(&errorCode, targetptr);
4273     osi_Assert(!errorCode || errorCode == VSALVAGE);
4274     VVnodeWriteToRead(&errorCode, parentptr);
4275     osi_Assert(!errorCode || errorCode == VSALVAGE);
4276
4277     /* break call back on DirFid */
4278     BreakCallBack(client->host, DirFid, 0);
4279     /*
4280      * We also need to break the callback for the file that is hard-linked since part
4281      * of its status (like linkcount) is changed
4282      */
4283     BreakCallBack(client->host, ExistingFid, 0);
4284
4285   Bad_Link:
4286     /* Write the all modified vnodes (parent, new files) and volume back */
4287     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4288                            volptr, &client);
4289     FidZap(&dir);
4290     ViceLog(2, ("SAFS_Link returns %d\n", errorCode));
4291     return errorCode;
4292
4293 }                               /*SAFSS_Link */
4294
4295
4296 afs_int32
4297 SRXAFS_Link(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4298             struct AFSFid * ExistingFid, struct AFSFetchStatus * OutFidStatus,
4299             struct AFSFetchStatus * OutDirStatus, struct AFSVolSync * Sync)
4300 {
4301     afs_int32 code;
4302     struct rx_connection *tcon;
4303     struct host *thost;
4304     struct client *t_client = NULL;     /* tmp ptr to client data */
4305     struct fsstats fsstats;
4306
4307     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_LINK);
4308
4309     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4310         goto Bad_Link;
4311
4312     code =
4313         SAFSS_Link(acall, DirFid, Name, ExistingFid, OutFidStatus,
4314                    OutDirStatus, Sync);
4315
4316   Bad_Link:
4317     code = CallPostamble(tcon, code, thost);
4318
4319     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4320
4321     fsstats_FinishOp(&fsstats, code);
4322
4323     osi_auditU(acall, LinkEvent, code,
4324                AUD_ID, t_client ? t_client->ViceId : 0,
4325                AUD_FID, DirFid, AUD_STR, Name,
4326                AUD_FID, ExistingFid, AUD_END);
4327     return code;
4328
4329 }                               /*SRXAFS_Link */
4330
4331
4332 /*
4333  * This routine is called exclusively by SRXAFS_MakeDir(), and should be
4334  * merged into it when possible.
4335  */
4336 static afs_int32
4337 SAFSS_MakeDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4338               struct AFSStoreStatus *InStatus, struct AFSFid *OutFid,
4339               struct AFSFetchStatus *OutFidStatus,
4340               struct AFSFetchStatus *OutDirStatus,
4341               struct AFSCallBack *CallBack, struct AFSVolSync *Sync)
4342 {
4343     Vnode *parentptr = 0;       /* vnode of input Directory */
4344     Vnode *targetptr = 0;       /* vnode of the new file */
4345     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4346     Volume *volptr = 0;         /* pointer to the volume header */
4347     Error errorCode = 0;                /* error code */
4348     struct acl_accessList *newACL;      /* Access list */
4349     int newACLSize;             /* Size of access list */
4350     DirHandle dir;              /* Handle for dir package I/O */
4351     DirHandle parentdir;        /* Handle for dir package I/O */
4352     struct client *client = 0;  /* pointer to client structure */
4353     afs_int32 rights, anyrights;        /* rights for this and any user */
4354     struct client *t_client;    /* tmp ptr to client data */
4355     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4356     struct rx_connection *tcon = rx_ConnectionOf(acall);
4357
4358     FidZero(&dir);
4359     FidZero(&parentdir);
4360
4361     /* Get ptr to client data for user Id for logging */
4362     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4363     logHostAddr.s_addr = rxr_HostOf(tcon);
4364     ViceLog(1,
4365             ("SAFS_MakeDir %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4366              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4367              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4368     FS_LOCK;
4369     AFSCallStats.MakeDir++, AFSCallStats.TotalCalls++;
4370     FS_UNLOCK;
4371     if (!FileNameOK(Name)) {
4372         errorCode = EINVAL;
4373         goto Bad_MakeDir;
4374     }
4375
4376     /*
4377      * Get the vnode and volume for the parent dir along with the caller's
4378      * rights to it.
4379      */
4380     if ((errorCode =
4381          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4382                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4383                           &rights, &anyrights))) {
4384         goto Bad_MakeDir;
4385     }
4386
4387     /* set volume synchronization information */
4388     SetVolumeSync(Sync, volptr);
4389
4390     /* Write access to the parent directory? */
4391 #ifdef DIRCREATE_NEED_WRITE
4392     /*
4393      * requires w access for the user to create a directory. this
4394      * closes a loophole in the current security arrangement, since a
4395      * user with i access only can create a directory and get the
4396      * implcit a access that goes with dir ownership, and proceed to
4397      * subvert quota in the volume.
4398      */
4399     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))
4400         || (errorCode = CheckWriteMode(parentptr, rights, PRSFS_WRITE))) {
4401 #else
4402     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_INSERT))) {
4403 #endif /* DIRCREATE_NEED_WRITE */
4404         goto Bad_MakeDir;
4405     }
4406 #define EMPTYDIRBLOCKS 2
4407     /* get a new vnode and set it up */
4408     if ((errorCode =
4409          Alloc_NewVnode(parentptr, &parentdir, volptr, &targetptr, Name,
4410                         OutFid, vDirectory, EMPTYDIRBLOCKS))) {
4411         goto Bad_MakeDir;
4412     }
4413
4414     /* Update the status for the parent dir */
4415 #if FS_STATS_DETAILED
4416     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4417                              parentptr->disk.linkCount + 1,
4418                              client->InSameNetwork);
4419 #else
4420     Update_ParentVnodeStatus(parentptr, volptr, &parentdir, client->ViceId,
4421                              parentptr->disk.linkCount + 1);
4422 #endif /* FS_STATS_DETAILED */
4423
4424     /* Point to target's ACL buffer and copy the parent's ACL contents to it */
4425     osi_Assert((SetAccessList
4426             (&targetptr, &volptr, &newACL, &newACLSize,
4427              &parentwhentargetnotdir, (AFSFid *) 0, 0)) == 0);
4428     osi_Assert(parentwhentargetnotdir == 0);
4429     memcpy((char *)newACL, (char *)VVnodeACL(parentptr), VAclSize(parentptr));
4430
4431     /* update the status for the target vnode */
4432     Update_TargetVnodeStatus(targetptr, TVS_MKDIR, client, InStatus,
4433                              parentptr, volptr, 0);
4434
4435     /* Actually create the New directory in the directory package */
4436     SetDirHandle(&dir, targetptr);
4437     osi_Assert(!(afs_dir_MakeDir(&dir, (afs_int32 *)OutFid, (afs_int32 *)DirFid)));
4438     DFlush();
4439     VN_SET_LEN(targetptr, (afs_fsize_t) afs_dir_Length(&dir));
4440
4441     /* set up return status */
4442     GetStatus(targetptr, OutFidStatus, rights, anyrights, parentptr);
4443     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4444
4445     /* convert the write lock to a read lock before breaking callbacks */
4446     VVnodeWriteToRead(&errorCode, parentptr);
4447     osi_Assert(!errorCode || errorCode == VSALVAGE);
4448
4449     /* break call back on DirFid */
4450     BreakCallBack(client->host, DirFid, 0);
4451
4452     /* Return a callback promise to caller */
4453     SetCallBackStruct(AddCallBack(client->host, OutFid), CallBack);
4454
4455   Bad_MakeDir:
4456     /* Write the all modified vnodes (parent, new files) and volume back */
4457     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4458                            volptr, &client);
4459     FidZap(&dir);
4460     FidZap(&parentdir);
4461     ViceLog(2, ("SAFS_MakeDir returns %d\n", errorCode));
4462     return errorCode;
4463
4464 }                               /*SAFSS_MakeDir */
4465
4466
4467 afs_int32
4468 SRXAFS_MakeDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4469                struct AFSStoreStatus * InStatus, struct AFSFid * OutFid,
4470                struct AFSFetchStatus * OutFidStatus,
4471                struct AFSFetchStatus * OutDirStatus,
4472                struct AFSCallBack * CallBack, struct AFSVolSync * Sync)
4473 {
4474     afs_int32 code;
4475     struct rx_connection *tcon;
4476     struct host *thost;
4477     struct client *t_client = NULL;     /* tmp ptr to client data */
4478     struct fsstats fsstats;
4479
4480     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_MAKEDIR);
4481
4482     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4483         goto Bad_MakeDir;
4484
4485     code =
4486         SAFSS_MakeDir(acall, DirFid, Name, InStatus, OutFid, OutFidStatus,
4487                       OutDirStatus, CallBack, Sync);
4488
4489   Bad_MakeDir:
4490     code = CallPostamble(tcon, code, thost);
4491
4492     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4493
4494     fsstats_FinishOp(&fsstats, code);
4495
4496     osi_auditU(acall, MakeDirEvent, code,
4497                AUD_ID, t_client ? t_client->ViceId : 0,
4498                AUD_FID, DirFid, AUD_STR, Name,
4499                AUD_FID, OutFid, AUD_END);
4500     return code;
4501
4502 }                               /*SRXAFS_MakeDir */
4503
4504
4505 /*
4506  * This routine is called exclusively by SRXAFS_RemoveDir(), and should be
4507  * merged into it when possible.
4508  */
4509 static afs_int32
4510 SAFSS_RemoveDir(struct rx_call *acall, struct AFSFid *DirFid, char *Name,
4511                 struct AFSFetchStatus *OutDirStatus, struct AFSVolSync *Sync)
4512 {
4513     Vnode *parentptr = 0;       /* vnode of input Directory */
4514     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4515     Vnode *targetptr = 0;       /* file to be deleted */
4516     AFSFid fileFid;             /* area for Fid from the directory */
4517     Error errorCode = 0;                /* error code */
4518     DirHandle dir;              /* Handle for dir package I/O */
4519     Volume *volptr = 0;         /* pointer to the volume header */
4520     struct client *client = 0;  /* pointer to client structure */
4521     afs_int32 rights, anyrights;        /* rights for this and any user */
4522     struct client *t_client;    /* tmp ptr to client data */
4523     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4524     struct rx_connection *tcon = rx_ConnectionOf(acall);
4525
4526     FidZero(&dir);
4527
4528     /* Get ptr to client data for user Id for logging */
4529     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4530     logHostAddr.s_addr = rxr_HostOf(tcon);
4531     ViceLog(1,
4532             ("SAFS_RemoveDir    %s,  Did = %u.%u.%u, Host %s:%d, Id %d\n", Name,
4533              DirFid->Volume, DirFid->Vnode, DirFid->Unique,
4534              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4535     FS_LOCK;
4536     AFSCallStats.RemoveDir++, AFSCallStats.TotalCalls++;
4537     FS_UNLOCK;
4538     /*
4539      * Get the vnode and volume for the parent dir along with the caller's
4540      * rights to it
4541      */
4542     if ((errorCode =
4543          GetVolumePackage(tcon, DirFid, &volptr, &parentptr, MustBeDIR,
4544                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4545                           &rights, &anyrights))) {
4546         goto Bad_RemoveDir;
4547     }
4548
4549     /* set volume synchronization information */
4550     SetVolumeSync(Sync, volptr);
4551
4552     /* Does the caller has delete (&write) access to the parent dir? */
4553     if ((errorCode = CheckWriteMode(parentptr, rights, PRSFS_DELETE))) {
4554         goto Bad_RemoveDir;
4555     }
4556
4557     /* Do the actual delete of the desired (empty) directory, Name */
4558     if ((errorCode =
4559          DeleteTarget(parentptr, volptr, &targetptr, &dir, &fileFid, Name,
4560                       MustBeDIR))) {
4561         goto Bad_RemoveDir;
4562     }
4563
4564     /* Update the status for the parent dir; link count is also adjusted */
4565 #if FS_STATS_DETAILED
4566     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4567                              parentptr->disk.linkCount - 1,
4568                              client->InSameNetwork);
4569 #else
4570     Update_ParentVnodeStatus(parentptr, volptr, &dir, client->ViceId,
4571                              parentptr->disk.linkCount - 1);
4572 #endif /* FS_STATS_DETAILED */
4573
4574     /* Return to the caller the updated parent dir status */
4575     GetStatus(parentptr, OutDirStatus, rights, anyrights, NULL);
4576
4577     /*
4578      * Note: it is not necessary to break the callback on fileFid, since
4579      * refcount is now 0, so no one should be able to refer to the dir
4580      * any longer
4581      */
4582     DeleteFileCallBacks(&fileFid);
4583
4584     /* convert the write lock to a read lock before breaking callbacks */
4585     VVnodeWriteToRead(&errorCode, parentptr);
4586     osi_Assert(!errorCode || errorCode == VSALVAGE);
4587
4588     /* break call back on DirFid and fileFid */
4589     BreakCallBack(client->host, DirFid, 0);
4590
4591   Bad_RemoveDir:
4592     /* Write the all modified vnodes (parent, new files) and volume back */
4593     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, parentptr,
4594                            volptr, &client);
4595     FidZap(&dir);
4596     ViceLog(2, ("SAFS_RemoveDir returns %d\n", errorCode));
4597     return errorCode;
4598
4599 }                               /*SAFSS_RemoveDir */
4600
4601
4602 afs_int32
4603 SRXAFS_RemoveDir(struct rx_call * acall, struct AFSFid * DirFid, char *Name,
4604                  struct AFSFetchStatus * OutDirStatus,
4605                  struct AFSVolSync * Sync)
4606 {
4607     afs_int32 code;
4608     struct rx_connection *tcon;
4609     struct host *thost;
4610     struct client *t_client = NULL;     /* tmp ptr to client data */
4611     struct fsstats fsstats;
4612
4613     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_REMOVEDIR);
4614
4615     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4616         goto Bad_RemoveDir;
4617
4618     code = SAFSS_RemoveDir(acall, DirFid, Name, OutDirStatus, Sync);
4619
4620   Bad_RemoveDir:
4621     code = CallPostamble(tcon, code, thost);
4622
4623     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4624
4625     fsstats_FinishOp(&fsstats, code);
4626
4627     osi_auditU(acall, RemoveDirEvent, code,
4628                AUD_ID, t_client ? t_client->ViceId : 0,
4629                AUD_FID, DirFid, AUD_STR, Name, AUD_END);
4630     return code;
4631
4632 }                               /*SRXAFS_RemoveDir */
4633
4634
4635 /*
4636  * This routine is called exclusively by SRXAFS_SetLock(), and should be
4637  * merged into it when possible.
4638  */
4639 static afs_int32
4640 SAFSS_SetLock(struct rx_call *acall, struct AFSFid *Fid, ViceLockType type,
4641               struct AFSVolSync *Sync)
4642 {
4643     Vnode *targetptr = 0;       /* vnode of input file */
4644     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4645     Error errorCode = 0;                /* error code */
4646     Volume *volptr = 0;         /* pointer to the volume header */
4647     struct client *client = 0;  /* pointer to client structure */
4648     afs_int32 rights, anyrights;        /* rights for this and any user */
4649     struct client *t_client;    /* tmp ptr to client data */
4650     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4651     static char *locktype[4] = { "LockRead", "LockWrite", "LockExtend", "LockRelease" };
4652     struct rx_connection *tcon = rx_ConnectionOf(acall);
4653
4654     if (type != LockRead && type != LockWrite) {
4655         errorCode = EINVAL;
4656         goto Bad_SetLock;
4657     }
4658     /* Get ptr to client data for user Id for logging */
4659     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4660     logHostAddr.s_addr = rxr_HostOf(tcon);
4661     ViceLog(1,
4662             ("SAFS_SetLock type = %s Fid = %u.%u.%u, Host %s:%d, Id %d\n",
4663              locktype[(int)type], Fid->Volume, Fid->Vnode, Fid->Unique,
4664              inet_ntoa(logHostAddr), ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4665     FS_LOCK;
4666     AFSCallStats.SetLock++, AFSCallStats.TotalCalls++;
4667     FS_UNLOCK;
4668     /*
4669      * Get the vnode and volume for the desired file along with the caller's
4670      * rights to it
4671      */
4672     if ((errorCode =
4673          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
4674                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4675                           &rights, &anyrights))) {
4676         goto Bad_SetLock;
4677     }
4678
4679     /* set volume synchronization information */
4680     SetVolumeSync(Sync, volptr);
4681
4682     /* Handle the particular type of set locking, type */
4683     errorCode = HandleLocking(targetptr, client, rights, type);
4684
4685   Bad_SetLock:
4686     /* Write the all modified vnodes (parent, new files) and volume back */
4687     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
4688                            volptr, &client);
4689
4690     if ((errorCode == VREADONLY) && (type == LockRead))
4691         errorCode = 0;          /* allow read locks on RO volumes without saving state */
4692
4693     ViceLog(2, ("SAFS_SetLock returns %d\n", errorCode));
4694     return (errorCode);
4695
4696 }                               /*SAFSS_SetLock */
4697
4698
4699 afs_int32
4700 SRXAFS_OldSetLock(struct rx_call * acall, struct AFSFid * Fid,
4701                   ViceLockType type, struct AFSVolSync * Sync)
4702 {
4703     return SRXAFS_SetLock(acall, Fid, type, Sync);
4704 }                               /*SRXAFS_OldSetLock */
4705
4706
4707 afs_int32
4708 SRXAFS_SetLock(struct rx_call * acall, struct AFSFid * Fid, ViceLockType type,
4709                struct AFSVolSync * Sync)
4710 {
4711     afs_int32 code;
4712     struct rx_connection *tcon;
4713     struct host *thost;
4714     struct client *t_client = NULL;     /* tmp ptr to client data */
4715     struct fsstats fsstats;
4716
4717     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_SETLOCK);
4718
4719     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4720         goto Bad_SetLock;
4721
4722     code = SAFSS_SetLock(acall, Fid, type, Sync);
4723
4724   Bad_SetLock:
4725     code = CallPostamble(tcon, code, thost);
4726
4727     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4728
4729     fsstats_FinishOp(&fsstats, code);
4730
4731     osi_auditU(acall, SetLockEvent, code,
4732                AUD_ID, t_client ? t_client->ViceId : 0,
4733                AUD_FID, Fid, AUD_LONG, type, AUD_END);
4734     return code;
4735 }                               /*SRXAFS_SetLock */
4736
4737
4738 /*
4739  * This routine is called exclusively by SRXAFS_ExtendLock(), and should be
4740  * merged into it when possible.
4741  */
4742 static afs_int32
4743 SAFSS_ExtendLock(struct rx_call *acall, struct AFSFid *Fid,
4744                  struct AFSVolSync *Sync)
4745 {
4746     Vnode *targetptr = 0;       /* vnode of input file */
4747     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4748     Error errorCode = 0;                /* error code */
4749     Volume *volptr = 0;         /* pointer to the volume header */
4750     struct client *client = 0;  /* pointer to client structure */
4751     afs_int32 rights, anyrights;        /* rights for this and any user */
4752     struct client *t_client;    /* tmp ptr to client data */
4753     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4754     struct rx_connection *tcon = rx_ConnectionOf(acall);
4755
4756     /* Get ptr to client data for user Id for logging */
4757     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4758     logHostAddr.s_addr = rxr_HostOf(tcon);
4759     ViceLog(1,
4760             ("SAFS_ExtendLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
4761              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
4762              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4763     FS_LOCK;
4764     AFSCallStats.ExtendLock++, AFSCallStats.TotalCalls++;
4765     FS_UNLOCK;
4766     /*
4767      * Get the vnode and volume for the desired file along with the caller's
4768      * rights to it
4769      */
4770     if ((errorCode =
4771          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
4772                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4773                           &rights, &anyrights))) {
4774         goto Bad_ExtendLock;
4775     }
4776
4777     /* set volume synchronization information */
4778     SetVolumeSync(Sync, volptr);
4779
4780     /* Handle the actual lock extension */
4781     errorCode = HandleLocking(targetptr, client, rights, LockExtend);
4782
4783   Bad_ExtendLock:
4784     /* Put back file's vnode and volume */
4785     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
4786                            volptr, &client);
4787
4788     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
4789         errorCode = 0;          /* under our generous policy re RO vols */
4790
4791     ViceLog(2, ("SAFS_ExtendLock returns %d\n", errorCode));
4792     return (errorCode);
4793
4794 }                               /*SAFSS_ExtendLock */
4795
4796
4797 afs_int32
4798 SRXAFS_OldExtendLock(struct rx_call * acall, struct AFSFid * Fid,
4799                      struct AFSVolSync * Sync)
4800 {
4801     return SRXAFS_ExtendLock(acall, Fid, Sync);
4802 }                               /*SRXAFS_OldExtendLock */
4803
4804
4805 afs_int32
4806 SRXAFS_ExtendLock(struct rx_call * acall, struct AFSFid * Fid,
4807                   struct AFSVolSync * Sync)
4808 {
4809     afs_int32 code;
4810     struct rx_connection *tcon;
4811     struct host *thost;
4812     struct client *t_client = NULL;     /* tmp ptr to client data */
4813     struct fsstats fsstats;
4814
4815     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_EXTENDLOCK);
4816
4817     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4818         goto Bad_ExtendLock;
4819
4820     code = SAFSS_ExtendLock(acall, Fid, Sync);
4821
4822   Bad_ExtendLock:
4823     code = CallPostamble(tcon, code, thost);
4824
4825     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4826
4827     fsstats_FinishOp(&fsstats, code);
4828
4829     osi_auditU(acall, ExtendLockEvent, code,
4830                AUD_ID, t_client ? t_client->ViceId : 0,
4831                AUD_FID, Fid, AUD_END);
4832     return code;
4833
4834 }                               /*SRXAFS_ExtendLock */
4835
4836
4837 /*
4838  * This routine is called exclusively by SRXAFS_ReleaseLock(), and should be
4839  * merged into it when possible.
4840  */
4841 static afs_int32
4842 SAFSS_ReleaseLock(struct rx_call *acall, struct AFSFid *Fid,
4843                   struct AFSVolSync *Sync)
4844 {
4845     Vnode *targetptr = 0;       /* vnode of input file */
4846     Vnode *parentwhentargetnotdir = 0;  /* parent for use in SetAccessList */
4847     Error errorCode = 0;                /* error code */
4848     Volume *volptr = 0;         /* pointer to the volume header */
4849     struct client *client = 0;  /* pointer to client structure */
4850     afs_int32 rights, anyrights;        /* rights for this and any user */
4851     struct client *t_client;    /* tmp ptr to client data */
4852     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
4853     struct rx_connection *tcon = rx_ConnectionOf(acall);
4854
4855     /* Get ptr to client data for user Id for logging */
4856     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4857     logHostAddr.s_addr = rxr_HostOf(tcon);
4858     ViceLog(1,
4859             ("SAFS_ReleaseLock Fid = %u.%u.%u, Host %s:%d, Id %d\n", Fid->Volume,
4860              Fid->Vnode, Fid->Unique, inet_ntoa(logHostAddr),
4861              ntohs(rxr_PortOf(tcon)), t_client->ViceId));
4862     FS_LOCK;
4863     AFSCallStats.ReleaseLock++, AFSCallStats.TotalCalls++;
4864     FS_UNLOCK;
4865     /*
4866      * Get the vnode and volume for the desired file along with the caller's
4867      * rights to it
4868      */
4869     if ((errorCode =
4870          GetVolumePackage(tcon, Fid, &volptr, &targetptr, DONTCHECK,
4871                           &parentwhentargetnotdir, &client, WRITE_LOCK,
4872                           &rights, &anyrights))) {
4873         goto Bad_ReleaseLock;
4874     }
4875
4876     /* set volume synchronization information */
4877     SetVolumeSync(Sync, volptr);
4878
4879     /* Handle the actual lock release */
4880     if ((errorCode = HandleLocking(targetptr, client, rights, LockRelease)))
4881         goto Bad_ReleaseLock;
4882
4883     /* if no more locks left, a callback would be triggered here */
4884     if (targetptr->disk.lock.lockCount <= 0) {
4885         /* convert the write lock to a read lock before breaking callbacks */
4886         VVnodeWriteToRead(&errorCode, targetptr);
4887         osi_Assert(!errorCode || errorCode == VSALVAGE);
4888         BreakCallBack(client->host, Fid, 0);
4889     }
4890
4891   Bad_ReleaseLock:
4892     /* Put back file's vnode and volume */
4893     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
4894                            volptr, &client);
4895
4896     if ((errorCode == VREADONLY))       /* presumably, we already granted this lock */
4897         errorCode = 0;          /* under our generous policy re RO vols */
4898
4899     ViceLog(2, ("SAFS_ReleaseLock returns %d\n", errorCode));
4900     return (errorCode);
4901
4902 }                               /*SAFSS_ReleaseLock */
4903
4904
4905 afs_int32
4906 SRXAFS_OldReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
4907                       struct AFSVolSync * Sync)
4908 {
4909     return SRXAFS_ReleaseLock(acall, Fid, Sync);
4910 }                               /*SRXAFS_OldReleaseLock */
4911
4912
4913 afs_int32
4914 SRXAFS_ReleaseLock(struct rx_call * acall, struct AFSFid * Fid,
4915                    struct AFSVolSync * Sync)
4916 {
4917     afs_int32 code;
4918     struct rx_connection *tcon;
4919     struct host *thost;
4920     struct client *t_client = NULL;     /* tmp ptr to client data */
4921     struct fsstats fsstats;
4922
4923     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_RELEASELOCK);
4924
4925     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
4926         goto Bad_ReleaseLock;
4927
4928     code = SAFSS_ReleaseLock(acall, Fid, Sync);
4929
4930   Bad_ReleaseLock:
4931     code = CallPostamble(tcon, code, thost);
4932
4933     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
4934
4935     fsstats_FinishOp(&fsstats, code);
4936
4937     osi_auditU(acall, ReleaseLockEvent, code,
4938                AUD_ID, t_client ? t_client->ViceId : 0,
4939                AUD_FID, Fid, AUD_END);
4940     return code;
4941
4942 }                               /*SRXAFS_ReleaseLock */
4943
4944
4945 void
4946 SetSystemStats(struct AFSStatistics *stats)
4947 {
4948     /* Fix this sometime soon.. */
4949     /* Because hey, it's not like we have a network monitoring protocol... */
4950     struct timeval time;
4951
4952     /* this works on all system types */
4953     FT_GetTimeOfDay(&time, 0);
4954     stats->CurrentTime = time.tv_sec;
4955 }                               /*SetSystemStats */
4956
4957 void
4958 SetAFSStats(struct AFSStatistics *stats)
4959 {
4960     extern afs_int32 StartTime, CurrentConnections;
4961     int seconds;
4962
4963     FS_LOCK;
4964     stats->CurrentMsgNumber = 0;
4965     stats->OldestMsgNumber = 0;
4966     stats->StartTime = StartTime;
4967     stats->CurrentConnections = CurrentConnections;
4968     stats->TotalAFSCalls = AFSCallStats.TotalCalls;
4969     stats->TotalFetchs =
4970         AFSCallStats.FetchData + AFSCallStats.FetchACL +
4971         AFSCallStats.FetchStatus;
4972     stats->FetchDatas = AFSCallStats.FetchData;
4973     stats->FetchedBytes = AFSCallStats.TotalFetchedBytes;
4974     seconds = AFSCallStats.AccumFetchTime / 1000;
4975     if (seconds <= 0)
4976         seconds = 1;
4977     stats->FetchDataRate = AFSCallStats.TotalFetchedBytes / seconds;
4978     stats->TotalStores =
4979         AFSCallStats.StoreData + AFSCallStats.StoreACL +
4980         AFSCallStats.StoreStatus;
4981     stats->StoreDatas = AFSCallStats.StoreData;
4982     stats->StoredBytes = AFSCallStats.TotalStoredBytes;
4983     seconds = AFSCallStats.AccumStoreTime / 1000;
4984     if (seconds <= 0)
4985         seconds = 1;
4986     stats->StoreDataRate = AFSCallStats.TotalStoredBytes / seconds;
4987 #ifdef AFS_NT40_ENV
4988     stats->ProcessSize = -1;    /* TODO: */
4989 #else
4990     stats->ProcessSize = (afs_int32) ((long)sbrk(0) >> 10);
4991 #endif
4992     FS_UNLOCK;
4993     h_GetWorkStats((int *)&(stats->WorkStations),
4994                    (int *)&(stats->ActiveWorkStations), (int *)0,
4995                    (afs_int32) (FT_ApproxTime()) - (15 * 60));
4996
4997 }                               /*SetAFSStats */
4998
4999 /* Get disk related information from all AFS partitions. */
5000
5001 void
5002 SetVolumeStats(struct AFSStatistics *stats)
5003 {
5004     struct DiskPartition64 *part;
5005     int i = 0;
5006
5007     for (part = DiskPartitionList; part && i < AFS_MSTATDISKS;
5008          part = part->next) {
5009         stats->Disks[i].TotalBlocks = RoundInt64ToInt32(part->totalUsable);
5010         stats->Disks[i].BlocksAvailable = RoundInt64ToInt32(part->free);
5011         memset(stats->Disks[i].Name, 0, AFS_DISKNAMESIZE);
5012         strncpy(stats->Disks[i].Name, part->name, AFS_DISKNAMESIZE);
5013         i++;
5014     }
5015     while (i < AFS_MSTATDISKS) {
5016         stats->Disks[i].TotalBlocks = -1;
5017         i++;
5018     }
5019 }                               /*SetVolumeStats */
5020
5021 afs_int32
5022 SRXAFS_GetStatistics(struct rx_call *acall, struct ViceStatistics *Statistics)
5023 {
5024     afs_int32 code;
5025     struct rx_connection *tcon = rx_ConnectionOf(acall);
5026     struct host *thost;
5027     struct client *t_client = NULL;     /* tmp ptr to client data */
5028     struct fsstats fsstats;
5029
5030     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETSTATISTICS);
5031
5032     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5033         goto Bad_GetStatistics;
5034
5035     ViceLog(1, ("SAFS_GetStatistics Received\n"));
5036     FS_LOCK;
5037     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5038     FS_UNLOCK;
5039     memset(Statistics, 0, sizeof(*Statistics));
5040     SetAFSStats((struct AFSStatistics *)Statistics);
5041     SetVolumeStats((struct AFSStatistics *)Statistics);
5042     SetSystemStats((struct AFSStatistics *)Statistics);
5043
5044   Bad_GetStatistics:
5045     code = CallPostamble(tcon, code, thost);
5046
5047     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5048
5049     fsstats_FinishOp(&fsstats, code);
5050
5051     osi_auditU(acall, GetStatisticsEvent, code,
5052                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5053     return code;
5054 }                               /*SRXAFS_GetStatistics */
5055
5056
5057 afs_int32
5058 SRXAFS_GetStatistics64(struct rx_call *acall, afs_int32 statsVersion, ViceStatistics64 *Statistics)
5059 {
5060     extern afs_int32 StartTime, CurrentConnections;
5061     int seconds;
5062     afs_int32 code;
5063     struct rx_connection *tcon = rx_ConnectionOf(acall);
5064     struct host *thost;
5065     struct client *t_client = NULL;     /* tmp ptr to client data */
5066     struct timeval time;
5067     struct fsstats fsstats;
5068
5069     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETSTATISTICS);
5070
5071     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5072         goto Bad_GetStatistics64;
5073
5074     ViceLog(1, ("SAFS_GetStatistics64 Received\n"));
5075     Statistics->ViceStatistics64_val =
5076         malloc(statsVersion*sizeof(afs_int64));
5077     Statistics->ViceStatistics64_len = statsVersion;
5078     FS_LOCK;
5079     AFSCallStats.GetStatistics++, AFSCallStats.TotalCalls++;
5080     Statistics->ViceStatistics64_val[STATS64_STARTTIME] = StartTime;
5081     Statistics->ViceStatistics64_val[STATS64_CURRENTCONNECTIONS] =
5082         CurrentConnections;
5083     Statistics->ViceStatistics64_val[STATS64_TOTALVICECALLS] =
5084         AFSCallStats.TotalCalls;
5085     Statistics->ViceStatistics64_val[STATS64_TOTALFETCHES] =
5086        AFSCallStats.FetchData + AFSCallStats.FetchACL +
5087        AFSCallStats.FetchStatus;
5088     Statistics->ViceStatistics64_val[STATS64_FETCHDATAS] =
5089         AFSCallStats.FetchData;
5090     Statistics->ViceStatistics64_val[STATS64_FETCHEDBYTES] =
5091         AFSCallStats.TotalFetchedBytes;
5092     seconds = AFSCallStats.AccumFetchTime / 1000;
5093     if (seconds <= 0)
5094         seconds = 1;
5095     Statistics->ViceStatistics64_val[STATS64_FETCHDATARATE] =
5096         AFSCallStats.TotalFetchedBytes / seconds;
5097     Statistics->ViceStatistics64_val[STATS64_TOTALSTORES] =
5098         AFSCallStats.StoreData + AFSCallStats.StoreACL +
5099         AFSCallStats.StoreStatus;
5100     Statistics->ViceStatistics64_val[STATS64_STOREDATAS] =
5101         AFSCallStats.StoreData;
5102     Statistics->ViceStatistics64_val[STATS64_STOREDBYTES] =
5103         AFSCallStats.TotalStoredBytes;
5104     seconds = AFSCallStats.AccumStoreTime / 1000;
5105     if (seconds <= 0)
5106         seconds = 1;
5107     Statistics->ViceStatistics64_val[STATS64_STOREDATARATE] =
5108         AFSCallStats.TotalStoredBytes / seconds;
5109 #ifdef AFS_NT40_ENV
5110     Statistics->ViceStatistics64_val[STATS64_PROCESSSIZE] = -1;
5111 #else
5112     Statistics->ViceStatistics64_val[STATS64_PROCESSSIZE] =
5113         (afs_int32) ((long)sbrk(0) >> 10);
5114 #endif
5115     FS_UNLOCK;
5116     h_GetWorkStats64(&(Statistics->ViceStatistics64_val[STATS64_WORKSTATIONS]),
5117                      &(Statistics->ViceStatistics64_val[STATS64_ACTIVEWORKSTATIONS]),
5118                      0,
5119                      (afs_int32) (FT_ApproxTime()) - (15 * 60));
5120
5121
5122
5123     /* this works on all system types */
5124     FT_GetTimeOfDay(&time, 0);
5125     Statistics->ViceStatistics64_val[STATS64_CURRENTTIME] = time.tv_sec;
5126
5127   Bad_GetStatistics64:
5128     code = CallPostamble(tcon, code, thost);
5129
5130     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5131
5132     fsstats_FinishOp(&fsstats, code);
5133
5134     osi_auditU(acall, GetStatisticsEvent, code,
5135                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5136     return code;
5137 }                               /*SRXAFS_GetStatistics */
5138
5139
5140 /*------------------------------------------------------------------------
5141  * EXPORTED SRXAFS_XStatsVersion
5142  *
5143  * Description:
5144  *      Routine called by the server-side RPC interface to implement
5145  *      pulling out the xstat version number for the File Server.
5146  *
5147  * Arguments:
5148  *      a_versionP : Ptr to the version number variable to set.
5149  *
5150  * Returns:
5151  *      0 (always)
5152  *
5153  * Environment:
5154  *      Nothing interesting.
5155  *
5156  * Side Effects:
5157  *      As advertised.
5158  *------------------------------------------------------------------------*/
5159
5160 afs_int32
5161 SRXAFS_XStatsVersion(struct rx_call * a_call, afs_int32 * a_versionP)
5162 {                               /*SRXAFS_XStatsVersion */
5163
5164     struct client *t_client = NULL;     /* tmp ptr to client data */
5165     struct rx_connection *tcon = rx_ConnectionOf(a_call);
5166     struct fsstats fsstats;
5167
5168     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_XSTATSVERSION);
5169
5170     *a_versionP = AFS_XSTAT_VERSION;
5171
5172     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5173
5174     fsstats_FinishOp(&fsstats, 0);
5175
5176     osi_auditU(a_call, XStatsVersionEvent, 0,
5177                AUD_ID, t_client ? t_client->ViceId : 0, AUD_END);
5178     return (0);
5179 }                               /*SRXAFS_XStatsVersion */
5180
5181
5182 /*------------------------------------------------------------------------
5183  * PRIVATE FillPerfValues
5184  *
5185  * Description:
5186  *      Routine called to fill a regular performance data structure.
5187  *
5188  * Arguments:
5189  *      a_perfP : Ptr to perf structure to fill
5190  *
5191  * Returns:
5192  *      Nothing.
5193  *
5194  * Environment:
5195  *      Various collections need this info, so the guts were put in
5196  *      this separate routine.
5197  *
5198  * Side Effects:
5199  *      As advertised.
5200  *------------------------------------------------------------------------*/
5201
5202 static void
5203 FillPerfValues(struct afs_PerfStats *a_perfP)
5204 {                               /*FillPerfValues */
5205     int dir_Buffers;            /*# buffers in use by dir package */
5206     int dir_Calls;              /*# read calls in dir package */
5207     int dir_IOs;                /*# I/O ops in dir package */
5208     struct rx_statistics *stats;
5209
5210     /*
5211      * Vnode cache section.
5212      */
5213     a_perfP->vcache_L_Entries = VnodeClassInfo[vLarge].cacheSize;
5214     a_perfP->vcache_L_Allocs = VnodeClassInfo[vLarge].allocs;
5215     a_perfP->vcache_L_Gets = VnodeClassInfo[vLarge].gets;
5216     a_perfP->vcache_L_Reads = VnodeClassInfo[vLarge].reads;
5217     a_perfP->vcache_L_Writes = VnodeClassInfo[vLarge].writes;
5218     a_perfP->vcache_S_Entries = VnodeClassInfo[vSmall].cacheSize;
5219     a_perfP->vcache_S_Allocs = VnodeClassInfo[vSmall].allocs;
5220     a_perfP->vcache_S_Gets = VnodeClassInfo[vSmall].gets;
5221     a_perfP->vcache_S_Reads = VnodeClassInfo[vSmall].reads;
5222     a_perfP->vcache_S_Writes = VnodeClassInfo[vSmall].writes;
5223     a_perfP->vcache_H_Entries = VStats.hdr_cache_size;
5224     a_perfP->vcache_H_Gets = (int)VStats.hdr_gets;
5225     a_perfP->vcache_H_Replacements = (int)VStats.hdr_loads;
5226
5227     /*
5228      * Directory section.
5229      */
5230     DStat(&dir_Buffers, &dir_Calls, &dir_IOs);
5231     a_perfP->dir_Buffers = (afs_int32) dir_Buffers;
5232     a_perfP->dir_Calls = (afs_int32) dir_Calls;
5233     a_perfP->dir_IOs = (afs_int32) dir_IOs;
5234
5235     /*
5236      * Rx section.
5237      */
5238     stats = rx_GetStatistics();
5239
5240     a_perfP->rx_packetRequests = (afs_int32) stats->packetRequests;
5241     a_perfP->rx_noPackets_RcvClass =
5242         (afs_int32) stats->receivePktAllocFailures;
5243     a_perfP->rx_noPackets_SendClass =
5244         (afs_int32) stats->sendPktAllocFailures;
5245     a_perfP->rx_noPackets_SpecialClass =
5246         (afs_int32) stats->specialPktAllocFailures;
5247     a_perfP->rx_socketGreedy = (afs_int32) stats->socketGreedy;
5248     a_perfP->rx_bogusPacketOnRead = (afs_int32) stats->bogusPacketOnRead;
5249     a_perfP->rx_bogusHost = (afs_int32) stats->bogusHost;
5250     a_perfP->rx_noPacketOnRead = (afs_int32) stats->noPacketOnRead;
5251     a_perfP->rx_noPacketBuffersOnRead =
5252         (afs_int32) stats->noPacketBuffersOnRead;
5253     a_perfP->rx_selects = (afs_int32) stats->selects;
5254     a_perfP->rx_sendSelects = (afs_int32) stats->sendSelects;
5255     a_perfP->rx_packetsRead_RcvClass =
5256         (afs_int32) stats->packetsRead[RX_PACKET_CLASS_RECEIVE];
5257     a_perfP->rx_packetsRead_SendClass =
5258         (afs_int32) stats->packetsRead[RX_PACKET_CLASS_SEND];
5259     a_perfP->rx_packetsRead_SpecialClass =
5260         (afs_int32) stats->packetsRead[RX_PACKET_CLASS_SPECIAL];
5261     a_perfP->rx_dataPacketsRead = (afs_int32) stats->dataPacketsRead;
5262     a_perfP->rx_ackPacketsRead = (afs_int32) stats->ackPacketsRead;
5263     a_perfP->rx_dupPacketsRead = (afs_int32) stats->dupPacketsRead;
5264     a_perfP->rx_spuriousPacketsRead =
5265         (afs_int32) stats->spuriousPacketsRead;
5266     a_perfP->rx_packetsSent_RcvClass =
5267         (afs_int32) stats->packetsSent[RX_PACKET_CLASS_RECEIVE];
5268     a_perfP->rx_packetsSent_SendClass =
5269         (afs_int32) stats->packetsSent[RX_PACKET_CLASS_SEND];
5270     a_perfP->rx_packetsSent_SpecialClass =
5271         (afs_int32) stats->packetsSent[RX_PACKET_CLASS_SPECIAL];
5272     a_perfP->rx_ackPacketsSent = (afs_int32) stats->ackPacketsSent;
5273     a_perfP->rx_pingPacketsSent = (afs_int32) stats->pingPacketsSent;
5274     a_perfP->rx_abortPacketsSent = (afs_int32) stats->abortPacketsSent;
5275     a_perfP->rx_busyPacketsSent = (afs_int32) stats->busyPacketsSent;
5276     a_perfP->rx_dataPacketsSent = (afs_int32) stats->dataPacketsSent;
5277     a_perfP->rx_dataPacketsReSent = (afs_int32) stats->dataPacketsReSent;
5278     a_perfP->rx_dataPacketsPushed = (afs_int32) stats->dataPacketsPushed;
5279     a_perfP->rx_ignoreAckedPacket = (afs_int32) stats->ignoreAckedPacket;
5280     a_perfP->rx_totalRtt_Sec = (afs_int32) stats->totalRtt.sec;
5281     a_perfP->rx_totalRtt_Usec = (afs_int32) stats->totalRtt.usec;
5282     a_perfP->rx_minRtt_Sec = (afs_int32) stats->minRtt.sec;
5283     a_perfP->rx_minRtt_Usec = (afs_int32) stats->minRtt.usec;
5284     a_perfP->rx_maxRtt_Sec = (afs_int32) stats->maxRtt.sec;
5285     a_perfP->rx_maxRtt_Usec = (afs_int32) stats->maxRtt.usec;
5286     a_perfP->rx_nRttSamples = (afs_int32) stats->nRttSamples;
5287     a_perfP->rx_nServerConns = (afs_int32) stats->nServerConns;
5288     a_perfP->rx_nClientConns = (afs_int32) stats->nClientConns;
5289     a_perfP->rx_nPeerStructs = (afs_int32) stats->nPeerStructs;
5290     a_perfP->rx_nCallStructs = (afs_int32) stats->nCallStructs;
5291     a_perfP->rx_nFreeCallStructs = (afs_int32) stats->nFreeCallStructs;
5292
5293     a_perfP->host_NumHostEntries = HTs;
5294     a_perfP->host_HostBlocks = HTBlocks;
5295     h_GetHostNetStats(&(a_perfP->host_NonDeletedHosts),
5296                       &(a_perfP->host_HostsInSameNetOrSubnet),
5297                       &(a_perfP->host_HostsInDiffSubnet),
5298                       &(a_perfP->host_HostsInDiffNetwork));
5299     a_perfP->host_NumClients = CEs;
5300     a_perfP->host_ClientBlocks = CEBlocks;
5301
5302     a_perfP->sysname_ID = afs_perfstats.sysname_ID;
5303     a_perfP->rx_nBusies = (afs_int32) stats->nBusies;
5304     a_perfP->fs_nBusies = afs_perfstats.fs_nBusies;
5305     rx_FreeStatistics(&stats);
5306 }                               /*FillPerfValues */
5307
5308
5309 /*------------------------------------------------------------------------
5310  * EXPORTED SRXAFS_GetXStats
5311  *
5312  * Description:
5313  *      Routine called by the server-side callback RPC interface to
5314  *      implement getting the given data collection from the extended
5315  *      File Server statistics.
5316  *
5317  * Arguments:
5318  *      a_call              : Ptr to Rx call on which this request came in.
5319  *      a_clientVersionNum  : Client version number.
5320  *      a_opCode            : Desired operation.
5321  *      a_serverVersionNumP : Ptr to version number to set.
5322  *      a_timeP             : Ptr to time value (seconds) to set.
5323  *      a_dataP             : Ptr to variable array structure to return
5324  *                            stuff in.
5325  *
5326  * Returns:
5327  *      0 (always).
5328  *
5329  * Environment:
5330  *      Nothing interesting.
5331  *
5332  * Side Effects:
5333  *      As advertised.
5334  *------------------------------------------------------------------------*/
5335
5336 afs_int32
5337 SRXAFS_GetXStats(struct rx_call *a_call, afs_int32 a_clientVersionNum,
5338                  afs_int32 a_collectionNumber, afs_int32 * a_srvVersionNumP,
5339                  afs_int32 * a_timeP, AFS_CollData * a_dataP)
5340 {                               /*SRXAFS_GetXStats */
5341
5342     int code;           /*Return value */
5343     afs_int32 *dataBuffP;       /*Ptr to data to be returned */
5344     afs_int32 dataBytes;        /*Bytes in data buffer */
5345     struct fsstats fsstats;
5346
5347     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETXSTATS);
5348
5349     /*
5350      * Record the time of day and the server version number.
5351      */
5352     *a_srvVersionNumP = AFS_XSTAT_VERSION;
5353     *a_timeP = FT_ApproxTime();
5354
5355     /*
5356      * Stuff the appropriate data in there (assume victory)
5357      */
5358     code = 0;
5359
5360     ViceLog(1,
5361             ("Received GetXStats call for collection %d\n",
5362              a_collectionNumber));
5363
5364 #if 0
5365     /*
5366      * We're not keeping stats, so just return successfully with
5367      * no data.
5368      */
5369     a_dataP->AFS_CollData_len = 0;
5370     a_dataP->AFS_CollData_val = NULL;
5371 #endif /* 0 */
5372
5373     switch (a_collectionNumber) {
5374     case AFS_XSTATSCOLL_CALL_INFO:
5375         /*
5376          * Pass back all the call-count-related data.
5377          *
5378          * >>> We are forced to allocate a separate area in which to
5379          * >>> put this stuff in by the RPC stub generator, since it
5380          * >>> will be freed at the tail end of the server stub code.
5381          */
5382 #if 0
5383         /*
5384          * I don't think call-level stats are being collected yet
5385          * for the File Server.
5386          */
5387         dataBytes = sizeof(struct afs_Stats);
5388         dataBuffP = (afs_int32 *) malloc(dataBytes);
5389         memcpy(dataBuffP, &afs_cmstats, dataBytes);
5390         a_dataP->AFS_CollData_len = dataBytes >> 2;
5391         a_dataP->AFS_CollData_val = dataBuffP;
5392 #else
5393         a_dataP->AFS_CollData_len = 0;
5394         a_dataP->AFS_CollData_val = NULL;
5395 #endif /* 0 */
5396         break;
5397
5398     case AFS_XSTATSCOLL_PERF_INFO:
5399         /*
5400          * Pass back all the regular performance-related data.
5401          *
5402          * >>> We are forced to allocate a separate area in which to
5403          * >>> put this stuff in by the RPC stub generator, since it
5404          * >>> will be freed at the tail end of the server stub code.
5405          */
5406
5407         afs_perfstats.numPerfCalls++;
5408         FillPerfValues(&afs_perfstats);
5409
5410         /*
5411          * Don't overwrite the spares at the end.
5412          */
5413
5414         dataBytes = sizeof(struct afs_PerfStats);
5415         dataBuffP = (afs_int32 *) malloc(dataBytes);
5416         memcpy(dataBuffP, &afs_perfstats, dataBytes);
5417         a_dataP->AFS_CollData_len = dataBytes >> 2;
5418         a_dataP->AFS_CollData_val = dataBuffP;
5419         break;
5420
5421     case AFS_XSTATSCOLL_FULL_PERF_INFO:
5422         /*
5423          * Pass back the full collection of performance-related data.
5424          * We have to stuff the basic, overall numbers in, but the
5425          * detailed numbers are kept in the structure already.
5426          *
5427          * >>> We are forced to allocate a separate area in which to
5428          * >>> put this stuff in by the RPC stub generator, since it
5429          * >>> will be freed at the tail end of the server stub code.
5430          */
5431
5432         afs_perfstats.numPerfCalls++;
5433 #if FS_STATS_DETAILED
5434         afs_FullPerfStats.overall.numPerfCalls = afs_perfstats.numPerfCalls;
5435         FillPerfValues(&afs_FullPerfStats.overall);
5436
5437         /*
5438          * Don't overwrite the spares at the end.
5439          */
5440
5441         dataBytes = sizeof(struct fs_stats_FullPerfStats);
5442         dataBuffP = (afs_int32 *) malloc(dataBytes);
5443         memcpy(dataBuffP, &afs_FullPerfStats, dataBytes);
5444         a_dataP->AFS_CollData_len = dataBytes >> 2;
5445         a_dataP->AFS_CollData_val = dataBuffP;
5446 #endif
5447         break;
5448
5449     case AFS_XSTATSCOLL_CBSTATS:
5450         afs_perfstats.numPerfCalls++;
5451
5452         dataBytes = sizeof(struct cbcounters);
5453         dataBuffP = (afs_int32 *) malloc(dataBytes);
5454         {
5455             extern struct cbcounters cbstuff;
5456             dataBuffP[0]=cbstuff.DeleteFiles;
5457             dataBuffP[1]=cbstuff.DeleteCallBacks;
5458             dataBuffP[2]=cbstuff.BreakCallBacks;
5459             dataBuffP[3]=cbstuff.AddCallBacks;
5460             dataBuffP[4]=cbstuff.GotSomeSpaces;
5461             dataBuffP[5]=cbstuff.DeleteAllCallBacks;
5462             dataBuffP[6]=cbstuff.nFEs;
5463             dataBuffP[7]=cbstuff.nCBs;
5464             dataBuffP[8]=cbstuff.nblks;
5465             dataBuffP[9]=cbstuff.CBsTimedOut;
5466             dataBuffP[10]=cbstuff.nbreakers;
5467             dataBuffP[11]=cbstuff.GSS1;
5468             dataBuffP[12]=cbstuff.GSS2;
5469             dataBuffP[13]=cbstuff.GSS3;
5470             dataBuffP[14]=cbstuff.GSS4;
5471             dataBuffP[15]=cbstuff.GSS5;
5472         }
5473
5474         a_dataP->AFS_CollData_len = dataBytes >> 2;
5475         a_dataP->AFS_CollData_val = dataBuffP;
5476         break;
5477
5478
5479     default:
5480         /*
5481          * Illegal collection number.
5482          */
5483         a_dataP->AFS_CollData_len = 0;
5484         a_dataP->AFS_CollData_val = NULL;
5485         code = 1;
5486     }                           /*Switch on collection number */
5487
5488     fsstats_FinishOp(&fsstats, code);
5489
5490     return (code);
5491
5492 }                               /*SRXAFS_GetXStats */
5493
5494
5495 static afs_int32
5496 common_GiveUpCallBacks(struct rx_call *acall, struct AFSCBFids *FidArray,
5497                        struct AFSCBs *CallBackArray)
5498 {
5499     afs_int32 errorCode = 0;
5500     int i;
5501     struct client *client = 0;
5502     struct rx_connection *tcon;
5503     struct host *thost;
5504     struct fsstats fsstats;
5505
5506     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GIVEUPCALLBACKS);
5507
5508     if (FidArray)
5509         ViceLog(1,
5510                 ("SAFS_GiveUpCallBacks (Noffids=%d)\n",
5511                  FidArray->AFSCBFids_len));
5512
5513     FS_LOCK;
5514     AFSCallStats.GiveUpCallBacks++, AFSCallStats.TotalCalls++;
5515     FS_UNLOCK;
5516     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5517         goto Bad_GiveUpCallBacks;
5518
5519     if (!FidArray && !CallBackArray) {
5520         ViceLog(1,
5521                 ("SAFS_GiveUpAllCallBacks: host=%x\n",
5522                  (tcon->peer ? tcon->peer->host : 0)));
5523         errorCode = GetClient(tcon, &client);
5524         if (!errorCode) {
5525             H_LOCK;
5526             DeleteAllCallBacks_r(client->host, 1);
5527             H_UNLOCK;
5528             PutClient(&client);
5529         }
5530     } else {
5531         if (FidArray->AFSCBFids_len < CallBackArray->AFSCBs_len) {
5532             ViceLog(0,
5533                     ("GiveUpCallBacks: #Fids %d < #CallBacks %d, host=%x\n",
5534                      FidArray->AFSCBFids_len, CallBackArray->AFSCBs_len,
5535                      (tcon->peer ? tcon->peer->host : 0)));
5536             errorCode = EINVAL;
5537             goto Bad_GiveUpCallBacks;
5538         }
5539
5540         errorCode = GetClient(tcon, &client);
5541         if (!errorCode) {
5542             for (i = 0; i < FidArray->AFSCBFids_len; i++) {
5543                 struct AFSFid *fid = &(FidArray->AFSCBFids_val[i]);
5544                 DeleteCallBack(client->host, fid);
5545             }
5546             PutClient(&client);
5547         }
5548     }
5549
5550   Bad_GiveUpCallBacks:
5551     errorCode = CallPostamble(tcon, errorCode, thost);
5552
5553     fsstats_FinishOp(&fsstats, errorCode);
5554
5555     return errorCode;
5556
5557 }                               /*common_GiveUpCallBacks */
5558
5559
5560 afs_int32
5561 SRXAFS_GiveUpCallBacks(struct rx_call * acall, struct AFSCBFids * FidArray,
5562                        struct AFSCBs * CallBackArray)
5563 {
5564     return common_GiveUpCallBacks(acall, FidArray, CallBackArray);
5565 }                               /*SRXAFS_GiveUpCallBacks */
5566
5567 afs_int32
5568 SRXAFS_GiveUpAllCallBacks(struct rx_call * acall)
5569 {
5570     return common_GiveUpCallBacks(acall, 0, 0);
5571 }                               /*SRXAFS_GiveUpAllCallBacks */
5572
5573
5574 afs_int32
5575 SRXAFS_NGetVolumeInfo(struct rx_call * acall, char *avolid,
5576                       struct AFSVolumeInfo * avolinfo)
5577 {
5578     return (VNOVOL);            /* XXX Obsolete routine XXX */
5579
5580 }                               /*SRXAFS_NGetVolumeInfo */
5581
5582
5583 /*
5584  * Dummy routine. Should never be called (the cache manager should only
5585  * invoke this interface when communicating with a AFS/DFS Protocol
5586  * Translator).
5587  */
5588 afs_int32
5589 SRXAFS_Lookup(struct rx_call * call_p, struct AFSFid * afs_dfid_p,
5590               char *afs_name_p, struct AFSFid * afs_fid_p,
5591               struct AFSFetchStatus * afs_status_p,
5592               struct AFSFetchStatus * afs_dir_status_p,
5593               struct AFSCallBack * afs_callback_p,
5594               struct AFSVolSync * afs_sync_p)
5595 {
5596     return EINVAL;
5597 }
5598
5599
5600 afs_int32
5601 SRXAFS_GetCapabilities(struct rx_call * acall, Capabilities * capabilities)
5602 {
5603     afs_int32 code;
5604     struct rx_connection *tcon;
5605     struct host *thost;
5606     afs_uint32 *dataBuffP;
5607     afs_int32 dataBytes;
5608
5609     FS_LOCK;
5610     AFSCallStats.GetCapabilities++, AFSCallStats.TotalCalls++;
5611     afs_FullPerfStats.overall.fs_nGetCaps++;
5612     FS_UNLOCK;
5613     ViceLog(2, ("SAFS_GetCapabilties\n"));
5614
5615     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
5616         goto Bad_GetCaps;
5617
5618     dataBytes = 1 * sizeof(afs_int32);
5619     dataBuffP = (afs_uint32 *) malloc(dataBytes);
5620     dataBuffP[0] = VICED_CAPABILITY_ERRORTRANS | VICED_CAPABILITY_WRITELOCKACL;
5621     dataBuffP[0] |= VICED_CAPABILITY_64BITFILES;
5622     if (saneacls)
5623         dataBuffP[0] |= VICED_CAPABILITY_SANEACLS;
5624
5625     capabilities->Capabilities_len = dataBytes / sizeof(afs_int32);
5626     capabilities->Capabilities_val = dataBuffP;
5627
5628   Bad_GetCaps:
5629     code = CallPostamble(tcon, code, thost);
5630
5631
5632     return 0;
5633 }
5634
5635 afs_int32
5636 SRXAFS_FlushCPS(struct rx_call * acall, struct ViceIds * vids,
5637                 struct IPAddrs * addrs, afs_int32 spare1, afs_int32 * spare2,
5638                 afs_int32 * spare3)
5639 {
5640     int i;
5641     afs_int32 nids, naddrs;
5642     afs_int32 *vd, *addr;
5643     Error errorCode = 0;                /* return code to caller */
5644     struct client *client = 0;
5645
5646     ViceLog(1, ("SRXAFS_FlushCPS\n"));
5647     FS_LOCK;
5648     AFSCallStats.TotalCalls++;
5649     FS_UNLOCK;
5650     nids = vids->ViceIds_len;   /* # of users in here */
5651     naddrs = addrs->IPAddrs_len;        /* # of hosts in here */
5652     if (nids < 0 || naddrs < 0) {
5653         errorCode = EINVAL;
5654         goto Bad_FlushCPS;
5655     }
5656
5657     vd = vids->ViceIds_val;
5658     for (i = 0; i < nids; i++, vd++) {
5659         if (!*vd)
5660             continue;
5661         client = h_ID2Client(*vd);      /* returns write locked and refCounted, or NULL */
5662         if (!client)
5663             continue;
5664
5665         client->prfail = 2;     /* Means re-eval client's cps */
5666 #ifdef  notdef
5667         if (client->tcon) {
5668             rx_SetRock(((struct rx_connection *)client->tcon), 0);
5669         }
5670 #endif
5671         if ((client->ViceId != ANONYMOUSID) && client->CPS.prlist_val) {
5672             free(client->CPS.prlist_val);
5673             client->CPS.prlist_val = NULL;
5674             client->CPS.prlist_len = 0;
5675         }
5676         ReleaseWriteLock(&client->lock);
5677         PutClient(&client);
5678     }
5679
5680     addr = addrs->IPAddrs_val;
5681     for (i = 0; i < naddrs; i++, addr++) {
5682         if (*addr)
5683             h_flushhostcps(*addr, htons(7001));
5684     }
5685
5686   Bad_FlushCPS:
5687     ViceLog(2, ("SAFS_FlushCPS  returns %d\n", errorCode));
5688     return errorCode;
5689 }                               /*SRXAFS_FlushCPS */
5690
5691 /* worthless hack to let CS keep running ancient software */
5692 static int
5693 afs_vtoi(char *aname)
5694 {
5695     afs_int32 temp;
5696     int tc;
5697
5698     temp = 0;
5699     while ((tc = *aname++)) {
5700         if (tc > '9' || tc < '0')
5701             return 0;           /* invalid name */
5702         temp *= 10;
5703         temp += tc - '0';
5704     }
5705     return temp;
5706 }
5707
5708 /*
5709  * may get name or #, but must handle all weird cases (recognize readonly
5710  * or backup volumes by name or #
5711  */
5712 static afs_int32
5713 CopyVolumeEntry(char *aname, struct vldbentry *ave,
5714                 struct VolumeInfo *av)
5715 {
5716     int i, j, vol;
5717     afs_int32 mask, whichType;
5718     afs_uint32 *serverHost, *typePtr;
5719
5720     /* figure out what type we want if by name */
5721     i = strlen(aname);
5722     if (i >= 8 && strcmp(aname + i - 7, ".backup") == 0)
5723         whichType = BACKVOL;
5724     else if (i >= 10 && strcmp(aname + i - 9, ".readonly") == 0)
5725         whichType = ROVOL;
5726     else
5727         whichType = RWVOL;
5728
5729     vol = afs_vtoi(aname);
5730     if (vol == 0)
5731         vol = ave->volumeId[whichType];
5732
5733     /*
5734      * Now vol has volume # we're interested in.  Next, figure out the type
5735      * of the volume by looking finding it in the vldb entry
5736      */
5737     if ((ave->flags & VLF_RWEXISTS) && vol == ave->volumeId[RWVOL]) {
5738         mask = VLSF_RWVOL;
5739         whichType = RWVOL;
5740     } else if ((ave->flags & VLF_ROEXISTS) && vol == ave->volumeId[ROVOL]) {
5741         mask = VLSF_ROVOL;
5742         whichType = ROVOL;
5743     } else if ((ave->flags & VLF_BACKEXISTS) && vol == ave->volumeId[BACKVOL]) {
5744         mask = VLSF_RWVOL;      /* backup always is on the same volume as parent */
5745         whichType = BACKVOL;
5746     } else
5747         return EINVAL;          /* error: can't find volume in vldb entry */
5748
5749     typePtr = &av->Type0;
5750     serverHost = &av->Server0;
5751     av->Vid = vol;
5752     av->Type = whichType;
5753     av->Type0 = av->Type1 = av->Type2 = av->Type3 = av->Type4 = 0;
5754     if (ave->flags & VLF_RWEXISTS)
5755         typePtr[RWVOL] = ave->volumeId[RWVOL];
5756     if (ave->flags & VLF_ROEXISTS)
5757         typePtr[ROVOL] = ave->volumeId[ROVOL];
5758     if (ave->flags & VLF_BACKEXISTS)
5759         typePtr[BACKVOL] = ave->volumeId[BACKVOL];
5760
5761     for (i = 0, j = 0; i < ave->nServers; i++) {
5762         if ((ave->serverFlags[i] & mask) == 0)
5763             continue;           /* wrong volume */
5764         serverHost[j] = ave->serverNumber[i];
5765         j++;
5766     }
5767     av->ServerCount = j;
5768     if (j < 8)
5769         serverHost[j++] = 0;    /* bogus 8, but compat only now */
5770     return 0;
5771 }
5772
5773 static afs_int32
5774 TryLocalVLServer(char *avolid, struct VolumeInfo *avolinfo)
5775 {
5776     static struct rx_connection *vlConn = 0;
5777     static int down = 0;
5778     static afs_int32 lastDownTime = 0;
5779     struct vldbentry tve;
5780     struct rx_securityClass *vlSec;
5781     afs_int32 code;
5782
5783     if (!vlConn) {
5784         vlSec = rxnull_NewClientSecurityObject();
5785         vlConn =
5786             rx_NewConnection(htonl(0x7f000001), htons(7003), 52, vlSec, 0);
5787         rx_SetConnDeadTime(vlConn, 15); /* don't wait long */
5788     }
5789     if (down && (FT_ApproxTime() < lastDownTime + 180)) {
5790         return 1;               /* failure */
5791     }
5792
5793     code = VL_GetEntryByNameO(vlConn, avolid, &tve);
5794     if (code >= 0)
5795         down = 0;               /* call worked */
5796     if (code) {
5797         if (code < 0) {
5798             lastDownTime = FT_ApproxTime();     /* last time we tried an RPC */
5799             down = 1;
5800         }
5801         return code;
5802     }
5803
5804     /* otherwise convert to old format vldb entry */
5805     code = CopyVolumeEntry(avolid, &tve, avolinfo);
5806     return code;
5807 }
5808
5809
5810
5811
5812
5813
5814 afs_int32
5815 SRXAFS_GetVolumeInfo(struct rx_call * acall, char *avolid,
5816                      struct VolumeInfo * avolinfo)
5817 {
5818     afs_int32 code;
5819     struct rx_connection *tcon;
5820     struct host *thost;
5821     struct fsstats fsstats;
5822
5823     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETVOLUMEINFO);
5824
5825     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5826         goto Bad_GetVolumeInfo;
5827
5828     FS_LOCK;
5829     AFSCallStats.GetVolumeInfo++, AFSCallStats.TotalCalls++;
5830     FS_UNLOCK;
5831     code = TryLocalVLServer(avolid, avolinfo);
5832     ViceLog(1,
5833             ("SAFS_GetVolumeInfo returns %d, Volume %u, type %x, servers %x %x %x %x...\n",
5834              code, avolinfo->Vid, avolinfo->Type, avolinfo->Server0,
5835              avolinfo->Server1, avolinfo->Server2, avolinfo->Server3));
5836     avolinfo->Type4 = 0xabcd9999;       /* tell us to try new vldb */
5837
5838   Bad_GetVolumeInfo:
5839     code = CallPostamble(tcon, code, thost);
5840
5841     fsstats_FinishOp(&fsstats, code);
5842
5843     return code;
5844
5845 }                               /*SRXAFS_GetVolumeInfo */
5846
5847
5848 afs_int32
5849 SRXAFS_GetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
5850                        AFSFetchVolumeStatus * FetchVolStatus, char **Name,
5851                        char **OfflineMsg, char **Motd)
5852 {
5853     Vnode *targetptr = 0;       /* vnode of the new file */
5854     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
5855     Error errorCode = 0;                /* error code */
5856     Volume *volptr = 0;         /* pointer to the volume header */
5857     struct client *client = 0;  /* pointer to client entry */
5858     afs_int32 rights, anyrights;        /* rights for this and any user */
5859     AFSFid dummyFid;
5860     struct rx_connection *tcon;
5861     struct host *thost;
5862     struct client *t_client = NULL;     /* tmp ptr to client data */
5863     struct fsstats fsstats;
5864
5865     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETVOLUMESTATUS);
5866
5867     ViceLog(1, ("SAFS_GetVolumeStatus for volume %u\n", avolid));
5868     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5869         goto Bad_GetVolumeStatus;
5870
5871     FS_LOCK;
5872     AFSCallStats.GetVolumeStatus++, AFSCallStats.TotalCalls++;
5873     FS_UNLOCK;
5874     if (avolid == 0) {
5875         errorCode = EINVAL;
5876         goto Bad_GetVolumeStatus;
5877     }
5878     dummyFid.Volume = avolid, dummyFid.Vnode =
5879         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
5880
5881     if ((errorCode =
5882          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
5883                           &parentwhentargetnotdir, &client, READ_LOCK,
5884                           &rights, &anyrights)))
5885         goto Bad_GetVolumeStatus;
5886
5887     if ((VanillaUser(client)) && (!(rights & PRSFS_READ))) {
5888         errorCode = EACCES;
5889         goto Bad_GetVolumeStatus;
5890     }
5891     (void)RXGetVolumeStatus(FetchVolStatus, Name, OfflineMsg, Motd, volptr);
5892
5893   Bad_GetVolumeStatus:
5894     (void)PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5895                            volptr, &client);
5896     ViceLog(2, ("SAFS_GetVolumeStatus returns %d\n", errorCode));
5897     /* next is to guarantee out strings exist for stub */
5898     if (*Name == 0) {
5899         *Name = (char *)malloc(1);
5900         **Name = 0;
5901     }
5902     if (*Motd == 0) {
5903         *Motd = (char *)malloc(1);
5904         **Motd = 0;
5905     }
5906     if (*OfflineMsg == 0) {
5907         *OfflineMsg = (char *)malloc(1);
5908         **OfflineMsg = 0;
5909     }
5910     errorCode = CallPostamble(tcon, errorCode, thost);
5911
5912     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5913
5914     fsstats_FinishOp(&fsstats, errorCode);
5915
5916     osi_auditU(acall, GetVolumeStatusEvent, errorCode,
5917                AUD_ID, t_client ? t_client->ViceId : 0,
5918                AUD_LONG, avolid, AUD_STR, *Name, AUD_END);
5919     return (errorCode);
5920
5921 }                               /*SRXAFS_GetVolumeStatus */
5922
5923
5924 afs_int32
5925 SRXAFS_SetVolumeStatus(struct rx_call * acall, afs_int32 avolid,
5926                        AFSStoreVolumeStatus * StoreVolStatus, char *Name,
5927                        char *OfflineMsg, char *Motd)
5928 {
5929     Vnode *targetptr = 0;       /* vnode of the new file */
5930     Vnode *parentwhentargetnotdir = 0;  /* vnode of parent */
5931     Error errorCode = 0;                /* error code */
5932     Volume *volptr = 0;         /* pointer to the volume header */
5933     struct client *client = 0;  /* pointer to client entry */
5934     afs_int32 rights, anyrights;        /* rights for this and any user */
5935     AFSFid dummyFid;
5936     struct rx_connection *tcon = rx_ConnectionOf(acall);
5937     struct host *thost;
5938     struct client *t_client = NULL;     /* tmp ptr to client data */
5939     struct fsstats fsstats;
5940
5941     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_SETVOLUMESTATUS);
5942
5943     ViceLog(1, ("SAFS_SetVolumeStatus for volume %u\n", avolid));
5944     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
5945         goto Bad_SetVolumeStatus;
5946
5947     FS_LOCK;
5948     AFSCallStats.SetVolumeStatus++, AFSCallStats.TotalCalls++;
5949     FS_UNLOCK;
5950     if (avolid == 0) {
5951         errorCode = EINVAL;
5952         goto Bad_SetVolumeStatus;
5953     }
5954     dummyFid.Volume = avolid, dummyFid.Vnode =
5955         (afs_int32) ROOTVNODE, dummyFid.Unique = 1;
5956
5957     if ((errorCode =
5958          GetVolumePackage(tcon, &dummyFid, &volptr, &targetptr, MustBeDIR,
5959                           &parentwhentargetnotdir, &client, READ_LOCK,
5960                           &rights, &anyrights)))
5961         goto Bad_SetVolumeStatus;
5962
5963     if (readonlyServer) {
5964         errorCode = VREADONLY;
5965         goto Bad_SetVolumeStatus;
5966     }
5967     if (VanillaUser(client)) {
5968         errorCode = EACCES;
5969         goto Bad_SetVolumeStatus;
5970     }
5971
5972     errorCode =
5973         RXUpdate_VolumeStatus(volptr, StoreVolStatus, Name, OfflineMsg, Motd);
5974
5975   Bad_SetVolumeStatus:
5976     PutVolumePackage(parentwhentargetnotdir, targetptr, (Vnode *) 0,
5977                      volptr, &client);
5978     ViceLog(2, ("SAFS_SetVolumeStatus returns %d\n", errorCode));
5979     errorCode = CallPostamble(tcon, errorCode, thost);
5980
5981     t_client = (struct client *)rx_GetSpecific(tcon, rxcon_client_key);
5982
5983     fsstats_FinishOp(&fsstats, errorCode);
5984
5985     osi_auditU(acall, SetVolumeStatusEvent, errorCode,
5986                AUD_ID, t_client ? t_client->ViceId : 0,
5987                AUD_LONG, avolid, AUD_STR, Name, AUD_END);
5988     return (errorCode);
5989 }                               /*SRXAFS_SetVolumeStatus */
5990
5991 #define DEFAULTVOLUME   "root.afs"
5992
5993 afs_int32
5994 SRXAFS_GetRootVolume(struct rx_call * acall, char **VolumeName)
5995 {
5996 #ifdef notdef
5997     int fd;
5998     int len;
5999     char *temp;
6000     struct rx_connection *tcon;
6001     struct host *thost;
6002     Error errorCode = 0;
6003 #endif
6004     struct fsstats fsstats;
6005
6006     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETROOTVOLUME);
6007
6008     return FSERR_EOPNOTSUPP;
6009
6010 #ifdef  notdef
6011     if (errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &thost))
6012         goto Bad_GetRootVolume;
6013     FS_LOCK;
6014     AFSCallStats.GetRootVolume++, AFSCallStats.TotalCalls++;
6015     FS_UNLOCK;
6016     temp = malloc(256);
6017     fd = afs_open(AFSDIR_SERVER_ROOTVOL_FILEPATH, O_RDONLY, 0666);
6018     if (fd <= 0)
6019         strcpy(temp, DEFAULTVOLUME);
6020     else {
6021 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6022         lockf(fd, F_LOCK, 0);
6023 #else
6024         flock(fd, LOCK_EX);
6025 #endif
6026         len = read(fd, temp, 256);
6027 #if defined (AFS_AIX_ENV) || defined (AFS_HPUX_ENV)
6028         lockf(fd, F_ULOCK, 0);
6029 #else
6030         flock(fd, LOCK_UN);
6031 #endif
6032         close(fd);
6033         if (temp[len - 1] == '\n')
6034             len--;
6035         temp[len] = '\0';
6036     }
6037     *VolumeName = temp;         /* freed by rx server-side stub */
6038
6039   Bad_GetRootVolume:
6040     errorCode = CallPostamble(tcon, errorCode, thost);
6041
6042     fsstats_FinishOp(&fsstats, errorCode);
6043
6044     return (errorCode);
6045 #endif /* notdef */
6046
6047 }                               /*SRXAFS_GetRootVolume */
6048
6049
6050 /* still works because a struct CBS is the same as a struct AFSOpaque */
6051 afs_int32
6052 SRXAFS_CheckToken(struct rx_call * acall, afs_int32 AfsId,
6053                   struct AFSOpaque * Token)
6054 {
6055     afs_int32 code;
6056     struct rx_connection *tcon;
6057     struct host *thost;
6058     struct fsstats fsstats;
6059
6060     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_CHECKTOKEN);
6061
6062     if ((code = CallPreamble(acall, ACTIVECALL, &tcon, &thost)))
6063         goto Bad_CheckToken;
6064
6065     code = FSERR_ECONNREFUSED;
6066
6067   Bad_CheckToken:
6068     code = CallPostamble(tcon, code, thost);
6069
6070     fsstats_FinishOp(&fsstats, code);
6071
6072     return code;
6073
6074 }                               /*SRXAFS_CheckToken */
6075
6076 afs_int32
6077 SRXAFS_GetTime(struct rx_call * acall, afs_uint32 * Seconds,
6078                afs_uint32 * USeconds)
6079 {
6080     afs_int32 code;
6081     struct rx_connection *tcon;
6082     struct host *thost;
6083     struct timeval tpl;
6084     struct fsstats fsstats;
6085
6086     fsstats_StartOp(&fsstats, FS_STATS_RPCIDX_GETTIME);
6087
6088     if ((code = CallPreamble(acall, NOTACTIVECALL, &tcon, &thost)))
6089         goto Bad_GetTime;
6090
6091     FS_LOCK;
6092     AFSCallStats.GetTime++, AFSCallStats.TotalCalls++;
6093     FS_UNLOCK;
6094     FT_GetTimeOfDay(&tpl, 0);
6095     *Seconds = tpl.tv_sec;
6096     *USeconds = tpl.tv_usec;
6097
6098     ViceLog(2, ("SAFS_GetTime returns %u, %u\n", *Seconds, *USeconds));
6099
6100   Bad_GetTime:
6101     code = CallPostamble(tcon, code, thost);
6102
6103     fsstats_FinishOp(&fsstats, code);
6104
6105     return code;
6106
6107 }                               /*SRXAFS_GetTime */
6108
6109
6110 /*
6111  * FetchData_RXStyle
6112  *
6113  * Purpose:
6114  *      Implement a client's data fetch using Rx.
6115  *
6116  * Arguments:
6117  *      volptr          : Ptr to the given volume's info.
6118  *      targetptr       : Pointer to the vnode involved.
6119  *      Call            : Ptr to the Rx call involved.
6120  *      Pos             : Offset within the file.
6121  *      Len             : Length in bytes to read; this value is bogus!
6122  *      a_bytesToFetchP : Set to the number of bytes to be fetched from
6123  *                        the File Server.
6124  *      a_bytesFetchedP : Set to the actual number of bytes fetched from
6125  *                        the File Server.
6126  */
6127
6128 static afs_int32
6129 FetchData_RXStyle(Volume * volptr, Vnode * targetptr,
6130                   struct rx_call * Call, afs_sfsize_t Pos,
6131                   afs_sfsize_t Len, afs_int32 Int64Mode,
6132                   afs_sfsize_t * a_bytesToFetchP,
6133                   afs_sfsize_t * a_bytesFetchedP)
6134 {
6135     struct timeval StartTime, StopTime; /* used to calculate file  transfer rates */
6136     IHandle_t *ihP;
6137     FdHandle_t *fdP;
6138 #ifndef HAVE_PIOV
6139     char *tbuffer;
6140 #else /* HAVE_PIOV */
6141     struct iovec tiov[RX_MAXIOVECS];
6142     int tnio;
6143 #endif /* HAVE_PIOV */
6144     afs_sfsize_t tlen;
6145     afs_int32 optSize;
6146
6147     /*
6148      * Initialize the byte count arguments.
6149      */
6150     (*a_bytesToFetchP) = 0;
6151     (*a_bytesFetchedP) = 0;
6152
6153     ViceLog(25,
6154             ("FetchData_RXStyle: Pos %llu, Len %llu\n", (afs_uintmax_t) Pos,
6155              (afs_uintmax_t) Len));
6156
6157     if (!VN_GET_INO(targetptr)) {
6158         afs_int32 zero = htonl(0);
6159         /*
6160          * This is used for newly created files; we simply send 0 bytes
6161          * back to make the cache manager happy...
6162          */
6163         if (Int64Mode)
6164             rx_Write(Call, (char *)&zero, sizeof(afs_int32));   /* send 0-length  */
6165         rx_Write(Call, (char *)&zero, sizeof(afs_int32));       /* send 0-length  */
6166         return (0);
6167     }
6168     FT_GetTimeOfDay(&StartTime, 0);
6169     ihP = targetptr->handle;
6170     fdP = IH_OPEN(ihP);
6171     if (fdP == NULL) {
6172         VTakeOffline(volptr);
6173         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6174                     volptr->hashid));
6175         return EIO;
6176     }
6177     optSize = sendBufSize;
6178     tlen = FDH_SIZE(fdP);
6179     ViceLog(25,
6180             ("FetchData_RXStyle: file size %llu\n", (afs_uintmax_t) tlen));
6181     if (tlen < 0) {
6182         FDH_CLOSE(fdP);
6183         VTakeOffline(volptr);
6184         ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6185                     volptr->hashid));
6186         return EIO;
6187     }
6188     if (CheckLength(volptr, targetptr, tlen)) {
6189         FDH_CLOSE(fdP);
6190         VTakeOffline(volptr);
6191         return VSALVAGE;
6192     }
6193     if (Pos > tlen) {
6194         Len = 0;
6195     }
6196
6197     if (Pos + Len > tlen) /* get length we should send */
6198         Len = ((tlen - Pos) < 0) ? 0 : tlen - Pos;
6199
6200     {
6201         afs_int32 high, low;
6202         SplitOffsetOrSize(Len, high, low);
6203         osi_Assert(Int64Mode || (Len >= 0 && high == 0) || Len < 0);
6204         if (Int64Mode) {
6205             high = htonl(high);
6206             rx_Write(Call, (char *)&high, sizeof(afs_int32));   /* High order bits */
6207         }
6208         low = htonl(low);
6209         rx_Write(Call, (char *)&low, sizeof(afs_int32));        /* send length on fetch */
6210     }
6211     (*a_bytesToFetchP) = Len;
6212 #ifndef HAVE_PIOV
6213     tbuffer = AllocSendBuffer();
6214 #endif /* HAVE_PIOV */
6215     while (Len > 0) {
6216         size_t wlen;
6217         ssize_t nBytes;
6218         if (Len > optSize)
6219             wlen = optSize;
6220         else
6221             wlen = Len;
6222 #ifndef HAVE_PIOV
6223         nBytes = FDH_PREAD(fdP, tbuffer, wlen, Pos);
6224         if (nBytes != wlen) {
6225             FDH_CLOSE(fdP);
6226             FreeSendBuffer((struct afs_buffer *)tbuffer);
6227             VTakeOffline(volptr);
6228             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6229                         volptr->hashid));
6230             return EIO;
6231         }
6232         nBytes = rx_Write(Call, tbuffer, wlen);
6233 #else /* HAVE_PIOV */
6234         nBytes = rx_WritevAlloc(Call, tiov, &tnio, RX_MAXIOVECS, wlen);
6235         if (nBytes <= 0) {
6236             FDH_CLOSE(fdP);
6237             return EIO;
6238         }
6239         wlen = nBytes;
6240         nBytes = FDH_PREADV(fdP, tiov, tnio, Pos);
6241         if (nBytes != wlen) {
6242             FDH_CLOSE(fdP);
6243             VTakeOffline(volptr);
6244             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6245                         volptr->hashid));
6246             return EIO;
6247         }
6248         nBytes = rx_Writev(Call, tiov, tnio, wlen);
6249 #endif /* HAVE_PIOV */
6250         Pos += wlen;
6251         /*
6252          * Bump the number of bytes actually sent by the number from this
6253          * latest iteration
6254          */
6255         (*a_bytesFetchedP) += nBytes;
6256         if (nBytes != wlen) {
6257             afs_int32 err;
6258             FDH_CLOSE(fdP);
6259 #ifndef HAVE_PIOV
6260             FreeSendBuffer((struct afs_buffer *)tbuffer);
6261 #endif /* HAVE_PIOV */
6262             err = VIsGoingOffline(volptr);
6263             if (err) {
6264                 return err;
6265             }
6266             return -31;
6267         }
6268         Len -= wlen;
6269     }
6270 #ifndef HAVE_PIOV
6271     FreeSendBuffer((struct afs_buffer *)tbuffer);
6272 #endif /* HAVE_PIOV */
6273     FDH_CLOSE(fdP);
6274     FT_GetTimeOfDay(&StopTime, 0);
6275
6276     /* Adjust all Fetch Data related stats */
6277     FS_LOCK;
6278     if (AFSCallStats.TotalFetchedBytes > 2000000000)    /* Reset if over 2 billion */
6279         AFSCallStats.TotalFetchedBytes = AFSCallStats.AccumFetchTime = 0;
6280     AFSCallStats.AccumFetchTime +=
6281         ((StopTime.tv_sec - StartTime.tv_sec) * 1000) +
6282         ((StopTime.tv_usec - StartTime.tv_usec) / 1000);
6283     {
6284         afs_fsize_t targLen;
6285         VN_GET_LEN(targLen, targetptr);
6286         AFSCallStats.TotalFetchedBytes += targLen;
6287         AFSCallStats.FetchSize1++;
6288         if (targLen < SIZE2)
6289             AFSCallStats.FetchSize2++;
6290         else if (targLen < SIZE3)
6291             AFSCallStats.FetchSize3++;
6292         else if (targLen < SIZE4)
6293             AFSCallStats.FetchSize4++;
6294         else
6295             AFSCallStats.FetchSize5++;
6296     }
6297     FS_UNLOCK;
6298     return (0);
6299
6300 }                               /*FetchData_RXStyle */
6301
6302 static int
6303 GetLinkCountAndSize(Volume * vp, FdHandle_t * fdP, int *lc,
6304                     afs_sfsize_t * size)
6305 {
6306 #ifdef AFS_NAMEI_ENV
6307     FdHandle_t *lhp;
6308     lhp = IH_OPEN(V_linkHandle(vp));
6309     if (!lhp)
6310         return EIO;
6311     *lc = namei_GetLinkCount(lhp, fdP->fd_ih->ih_ino, 0, 0, 1);
6312     FDH_CLOSE(lhp);
6313     if (*lc < 0)
6314         return -1;
6315     *size = OS_SIZE(fdP->fd_fd);
6316     return (*size == -1) ? -1 : 0;
6317 #else
6318     struct afs_stat status;
6319
6320     if (afs_fstat(fdP->fd_fd, &status) < 0) {
6321         return -1;
6322     }
6323
6324     *lc = GetLinkCount(vp, &status);
6325     *size = status.st_size;
6326     return 0;
6327 #endif
6328 }
6329
6330 /*
6331  * StoreData_RXStyle
6332  *
6333  * Purpose:
6334  *      Implement a client's data store using Rx.
6335  *
6336  * Arguments:
6337  *      volptr          : Ptr to the given volume's info.
6338  *      targetptr       : Pointer to the vnode involved.
6339  *      Call            : Ptr to the Rx call involved.
6340  *      Pos             : Offset within the file.
6341  *      Len             : Length in bytes to store; this value is bogus!
6342  *      a_bytesToStoreP : Set to the number of bytes to be stored to
6343  *                        the File Server.
6344  *      a_bytesStoredP  : Set to the actual number of bytes stored to
6345  *                        the File Server.
6346  */
6347 afs_int32
6348 StoreData_RXStyle(Volume * volptr, Vnode * targetptr, struct AFSFid * Fid,
6349                   struct client * client, struct rx_call * Call,
6350                   afs_fsize_t Pos, afs_fsize_t Length, afs_fsize_t FileLength,
6351                   int sync,
6352                   afs_sfsize_t * a_bytesToStoreP,
6353                   afs_sfsize_t * a_bytesStoredP)
6354 {
6355     afs_sfsize_t bytesTransfered;       /* number of bytes actually transfered */
6356     struct timeval StartTime, StopTime; /* Used to measure how long the store takes */
6357     Error errorCode = 0;                /* Returned error code to caller */
6358 #ifndef HAVE_PIOV
6359     char *tbuffer;      /* data copying buffer */
6360 #else /* HAVE_PIOV */
6361     struct iovec tiov[RX_MAXIOVECS];    /* no data copying with iovec */
6362     int tnio;                   /* temp for iovec size */
6363 #endif /* HAVE_PIOV */
6364     afs_sfsize_t tlen;          /* temp for xfr length */
6365     Inode tinode;               /* inode for I/O */
6366     afs_int32 optSize;          /* optimal transfer size */
6367     afs_sfsize_t DataLength = 0;        /* size of inode */
6368     afs_sfsize_t TruncatedLength;       /* size after ftruncate */
6369     afs_fsize_t NewLength;      /* size after this store completes */
6370     afs_sfsize_t adjustSize;    /* bytes to call VAdjust... with */
6371     int linkCount = 0;          /* link count on inode */
6372     afs_fsize_t CoW_off, CoW_len;
6373     ssize_t nBytes;
6374     FdHandle_t *fdP, *origfdP = NULL;
6375     struct in_addr logHostAddr; /* host ip holder for inet_ntoa */
6376     afs_ino_str_t stmp;
6377
6378     /*
6379      * Initialize the byte count arguments.
6380      */
6381     (*a_bytesToStoreP) = 0;
6382     (*a_bytesStoredP) = 0;
6383
6384     /*
6385      * We break the callbacks here so that the following signal will not
6386      * leave a window.
6387      */
6388     BreakCallBack(client->host, Fid, 0);
6389
6390     if (Pos == -1 || VN_GET_INO(targetptr) == 0) {
6391         /* the inode should have been created in Alloc_NewVnode */
6392         logHostAddr.s_addr = rxr_HostOf(rx_ConnectionOf(Call));
6393         ViceLog(0,
6394                 ("StoreData_RXStyle : Inode non-existent Fid = %u.%u.%u, inode = %llu, Pos %llu Host %s:%d\n",
6395                  Fid->Volume, Fid->Vnode, Fid->Unique,
6396                  (afs_uintmax_t) VN_GET_INO(targetptr), (afs_uintmax_t) Pos,
6397                  inet_ntoa(logHostAddr), ntohs(rxr_PortOf(rx_ConnectionOf(Call)))));
6398         return ENOENT;          /* is this proper error code? */
6399     } else {
6400         /*
6401          * See if the file has several links (from other volumes).  If it
6402          * does, then we have to make a copy before changing it to avoid
6403          *changing read-only clones of this dude
6404          */
6405         ViceLog(25,
6406                 ("StoreData_RXStyle : Opening inode %s\n",
6407                  PrintInode(stmp, VN_GET_INO(targetptr))));
6408         fdP = IH_OPEN(targetptr->handle);
6409         if (fdP == NULL)
6410             return ENOENT;
6411         if (GetLinkCountAndSize(volptr, fdP, &linkCount, &DataLength) < 0) {
6412             FDH_CLOSE(fdP);
6413             VTakeOffline(volptr);
6414             ViceLog(0, ("Volume %u now offline, must be salvaged.\n",
6415                         volptr->hashid));
6416             return EIO;
6417         }
6418         if (CheckLength(volptr, targetptr, DataLength)) {
6419             FDH_CLOSE(fdP);
6420             VTakeOffline(volptr);
6421             return VSALVAGE;
6422         }
6423
6424         if (linkCount != 1) {
6425             afs_fsize_t size;
6426             ViceLog(25,
6427                     ("StoreData_RXStyle : inode %s has more than onelink\n",
6428                      PrintInode(stmp, VN_GET_INO(targetptr))));
6429             /* other volumes share this data, better copy it first */
6430
6431             /* Adjust the disk block count by the creation of the new inode.
6432              * We call the special VDiskUsage so we don't adjust the volume's
6433              * quota since we don't want to penalyze the user for afs's internal
6434              * mechanisms (i.e. copy on write overhead.) Also the right size
6435              * of the disk will be recorded...
6436              */
6437             origfdP = fdP;
6438             VN_GET_LEN(size, targetptr);
6439             volptr->partition->flags &= ~PART_DONTUPDATE;
6440             VSetPartitionDiskUsage(volptr->partition);
6441             volptr->partition->flags |= PART_DONTUPDATE;
6442             if ((errorCode = VDiskUsage(volptr, nBlocks(size)))) {
6443                 volptr->partition->flags &= ~PART_DONTUPDATE;
6444                 FDH_CLOSE(origfdP);
6445                 return (errorCode);
6446             }
6447
6448             CoW_len = (FileLength >= (Length + Pos)) ? FileLength - Length : Pos;
6449             CopyOnWrite_calls++;
6450             if (CoW_len == 0) CopyOnWrite_size0++;
6451             if (Pos == 0) CopyOnWrite_off0++;
6452             if (CoW_len > CopyOnWrite_maxsize) CopyOnWrite_maxsize = CoW_len;
6453
6454             ViceLog(1, ("StoreData : calling CopyOnWrite on vnode %u.%u (%s) "
6455                         "off 0x0 size 0x%llx\n",
6456                         afs_printable_VolumeId_u(V_id(volptr)),
6457                         afs_printable_VnodeId_u(targetptr->vnodeNumber),
6458                         V_name(volptr), Pos));
6459             if ((errorCode = CopyOnWrite(targetptr, volptr, 0, Pos))) {
6460                 ViceLog(25, ("StoreData : CopyOnWrite failed\n"));
6461                 volptr->partition->flags &= ~PART_DONTUPDATE;
6462                 FDH_CLOSE(origfdP);
6463                 return (errorCode);
6464             }
6465             volptr->partition->flags &= ~PART_DONTUPDATE;
6466             VSetPartitionDiskUsage(volptr->partition);
6467             fdP = IH_OPEN(targetptr->handle);
6468             if (fdP == NULL) {
6469                 ViceLog(25,
6470                         ("StoreData : Reopen after CopyOnWrite failed\n"));
6471                 FDH_REALLYCLOSE(origfdP);
6472                 return ENOENT;
6473             }
6474         }
6475         tinode = VN_GET_INO(targetptr);
6476     }
6477     if (!VALID_INO(tinode)) {
6478         VTakeOffline(volptr);
6479         ViceLog(0,("Volume %u now offline, must be salvaged.\n",
6480                    volptr->hashid));
6481         return EIO;
6482     }
6483
6484     /* compute new file length */
6485     NewLength = DataLength;
6486     if (FileLength < NewLength)
6487         /* simulate truncate */
6488         NewLength = FileLength;
6489     TruncatedLength = NewLength;        /* remember length after possible ftruncate */
6490     if (Pos + Length > NewLength)
6491         NewLength = Pos + Length;       /* and write */
6492
6493     /* adjust the disk block count by the difference in the files */
6494     {
6495         afs_fsize_t targSize;
6496         VN_GET_LEN(targSize, targetptr);
6497         adjustSize = nBlocks(NewLength) - nBlocks(targSize);
6498     }
6499     if ((errorCode =
6500          AdjustDiskUsage(volptr, adjustSize,
6501                          adjustSize - SpareComp(volptr)))) {
6502         FDH_CLOSE(fdP);
6503         if (origfdP) FDH_REALLYCLOSE(origfdP);
6504         return (errorCode);
6505     }
6506
6507     /* can signal cache manager to proceed from close now */
6508     /* this bit means that the locks are set and protections are OK */
6509     rx_SetLocalStatus(Call, 1);
6510
6511     FT_GetTimeOfDay(&StartTime, 0);
6512
6513     optSize = sendBufSize;
6514     ViceLog(25,
6515             ("StoreData_RXStyle: Pos %llu, DataLength %llu, FileLength %llu, Length %llu\n",
6516              (afs_uintmax_t) Pos, (afs_uintmax_t) DataLength,
6517              (afs_uintmax_t) FileLength, (afs_uintmax_t) Length));
6518
6519     /* truncate the file iff it needs it (ftruncate is slow even when its a noop) */
6520     if (FileLength < DataLength)
6521         FDH_TRUNC(fdP, FileLength);
6522     bytesTransfered = 0;
6523 #ifndef HAVE_PIOV
6524     tbuffer = AllocSendBuffer();
6525 #endif /* HAVE_PIOV */
6526     /* if length == 0, the loop below isn't going to do anything, including
6527      * extend the length of the inode, which it must do, since the file system
6528      * assumes that the inode length == vnode's file length.  So, we extend
6529      * the file length manually if need be.  Note that if file is bigger than
6530      * Pos+(Length==0), we dont' have to do anything, and certainly shouldn't
6531      * do what we're going to do below.
6532      */
6533     if (Length == 0 && Pos > TruncatedLength) {
6534         /* Set the file's length; we've already done an lseek to the right
6535          * spot above.
6536          */
6537         nBytes = FDH_PWRITE(fdP, &tlen, 1, Pos);
6538         if (nBytes != 1) {
6539             errorCode = -1;
6540             goto done;
6541         }
6542         errorCode = FDH_TRUNC(fdP, Pos);
6543     } else {
6544         /* have some data to copy */
6545         (*a_bytesToStoreP) = Length;
6546         while (1) {
6547             int rlen;
6548             if (bytesTransfered >= Length) {
6549                 errorCode = 0;
6550                 break;
6551             }
6552             tlen = Length - bytesTransfered;    /* how much more to do */
6553             if (tlen > optSize)
6554                 rlen = optSize; /* bound by buffer size */
6555             else
6556                 rlen = (int)tlen;
6557 #ifndef HAVE_PIOV
6558             errorCode = rx_Read(Call, tbuffer, rlen);
6559 #else /* HAVE_PIOV */
6560             errorCode = rx_Readv(Call, tiov, &tnio, RX_MAXIOVECS, rlen);
6561 #endif /* HAVE_PIOV */
6562             if (errorCode <= 0) {
6563                 errorCode = -32;
6564                 break;
6565             }
6566             (*a_bytesStoredP) += errorCode;
6567             rlen = errorCode;
6568 #ifndef HAVE_PIOV
6569             nBytes = FDH_PWRITE(fdP, tbuffer, rlen, Pos);
6570 #else /* HAVE_PIOV */
6571             nBytes = FDH_PWRITEV(fdP, tiov, tnio, Pos);
6572 #endif /* HAVE_PIOV */
6573             if (nBytes != rlen) {
6574                 errorCode = VDISKFULL;
6575                 break;
6576             }
6577             bytesTransfered += rlen;
6578             Pos += rlen;
6579         }
6580     }
6581   done:
6582 #ifndef HAVE_PIOV
6583     FreeSendBuffer((struct afs_buffer *)tbuffer);
6584 #endif /* HAVE_PIOV */
6585     if (sync) {
6586         FDH_SYNC(fdP);
6587     }
6588     if (errorCode) {
6589         afs_sfsize_t nfSize = FDH_SIZE(fdP);
6590         osi_Assert(nfSize >= 0);
6591         /* something went wrong: adjust size and return */
6592         VN_SET_LEN(targetptr, nfSize);  /* set new file size. */
6593         /* changed_newTime is tested in StoreData to detemine if we
6594          * need to update the target vnode.
6595          */
6596         targetptr->changed_newTime = 1;
6597         if (origfdP && (bytesTransfered < Length))      /* Need to "finish" CopyOnWrite still */
6598             CopyOnWrite2(origfdP, fdP, Pos + bytesTransfered, NewLength - Pos - bytesTransfered);
6599         if (origfdP) FDH_REALLYCLOSE(origfdP);
6600         FDH_CLOSE(fdP);
6601         /* set disk usage to be correct */
6602         VAdjustDiskUsage(&errorCode, volptr,
6603                          (afs_sfsize_t) (nBlocks(nfSize) -
6604                                          nBlocks(NewLength)), 0);
6605         return errorCode;
6606     }
6607     if (origfdP) {                                      /* finish CopyOnWrite */
6608         if ( (CoW_off = Pos + Length) < NewLength) {
6609             errorCode = CopyOnWrite2(origfdP, fdP, CoW_off, CoW_len = NewLength - CoW_off);
6610             ViceLog(1, ("StoreData : CopyOnWrite2 on vnode %u.%u (%s) "
6611                         "off 0x%llx size 0x%llx returns %d\n",
6612                         afs_printable_VolumeId_u(V_id(volptr)),
6613                         afs_printable_VnodeId_u(targetptr->vnodeNumber),
6614                         V_name(volptr), CoW_off, CoW_len, errorCode));
6615         }
6616         FDH_REALLYCLOSE(origfdP);
6617     }
6618     FDH_CLOSE(fdP);
6619
6620     FT_GetTimeOfDay(&StopTime, 0);
6621
6622     VN_SET_LEN(targetptr, NewLength);
6623
6624     /* Update all StoreData related stats */
6625     FS_LOCK;
6626     if (AFSCallStats.TotalStoredBytes > 2000000000)     /* reset if over 2 billion */
6627         AFSCallStats.TotalStoredBytes = AFSCallStats.AccumStoreTime = 0;
6628     AFSCallStats.StoreSize1++;  /* Piggybacked data */
6629     {
6630         afs_fsize_t targLen;
6631         VN_GET_LEN(targLen, targetptr);
6632         if (targLen < SIZE2)
6633             AFSCallStats.StoreSize2++;
6634         else if (targLen < SIZE3)
6635             AFSCallStats.StoreSize3++;
6636         else if (targLen < SIZE4)
6637             AFSCallStats.StoreSize4++;
6638         else
6639             AFSCallStats.StoreSize5++;
6640     }
6641     FS_UNLOCK;
6642     return (errorCode);
6643
6644 }                               /*StoreData_RXStyle */
6645
6646 static int sys2et[512];
6647
6648 void
6649 init_sys_error_to_et(void)
6650 {
6651     memset(&sys2et, 0, sizeof(sys2et));
6652     sys2et[EPERM] = UAEPERM;
6653     sys2et[ENOENT] = UAENOENT;
6654     sys2et[ESRCH] = UAESRCH;
6655     sys2et[EINTR] = UAEINTR;
6656     sys2et[EIO] = UAEIO;
6657     sys2et[ENXIO] = UAENXIO;
6658     sys2et[E2BIG] = UAE2BIG;
6659     sys2et[ENOEXEC] = UAENOEXEC;
6660     sys2et[EBADF] = UAEBADF;
6661     sys2et[ECHILD] = UAECHILD;
6662     sys2et[EAGAIN] = UAEAGAIN;
6663     sys2et[ENOMEM] = UAENOMEM;
6664     sys2et[EACCES] = UAEACCES;
6665     sys2et[EFAULT] = UAEFAULT;
6666     sys2et[ENOTBLK] = UAENOTBLK;
6667     sys2et[EBUSY] = UAEBUSY;
6668     sys2et[EEXIST] = UAEEXIST;
6669     sys2et[EXDEV] = UAEXDEV;
6670     sys2et[ENODEV] = UAENODEV;
6671     sys2et[ENOTDIR] = UAENOTDIR;
6672     sys2et[EISDIR] = UAEISDIR;
6673     sys2et[EINVAL] = UAEINVAL;
6674     sys2et[ENFILE] = UAENFILE;
6675     sys2et[EMFILE] = UAEMFILE;
6676     sys2et[ENOTTY] = UAENOTTY;
6677     sys2et[ETXTBSY] = UAETXTBSY;
6678     sys2et[EFBIG] = UAEFBIG;
6679     sys2et[ENOSPC] = UAENOSPC;
6680     sys2et[ESPIPE] = UAESPIPE;
6681     sys2et[EROFS] = UAEROFS;
6682     sys2et[EMLINK] = UAEMLINK;
6683     sys2et[EPIPE] = UAEPIPE;
6684     sys2et[EDOM] = UAEDOM;
6685     sys2et[ERANGE] = UAERANGE;
6686     sys2et[EDEADLK] = UAEDEADLK;
6687     sys2et[ENAMETOOLONG] = UAENAMETOOLONG;
6688     sys2et[ENOLCK] = UAENOLCK;
6689     sys2et[ENOSYS] = UAENOSYS;
6690 #if (ENOTEMPTY != EEXIST)
6691     sys2et[ENOTEMPTY] = UAENOTEMPTY;
6692 #endif
6693     sys2et[ELOOP] = UAELOOP;
6694 #if (EWOULDBLOCK != EAGAIN)
6695     sys2et[EWOULDBLOCK] = UAEWOULDBLOCK;
6696 #endif
6697     sys2et[ENOMSG] = UAENOMSG;
6698     sys2et[EIDRM] = UAEIDRM;
6699     sys2et[ECHRNG] = UAECHRNG;
6700     sys2et[EL2NSYNC] = UAEL2NSYNC;
6701     sys2et[EL3HLT] = UAEL3HLT;
6702     sys2et[EL3RST] = UAEL3RST;
6703     sys2et[ELNRNG] = UAELNRNG;
6704     sys2et[EUNATCH] = UAEUNATCH;
6705     sys2et[ENOCSI] = UAENOCSI;
6706     sys2et[EL2HLT] = UAEL2HLT;
6707     sys2et[EBADE] = UAEBADE;
6708     sys2et[EBADR] = UAEBADR;
6709     sys2et[EXFULL] = UAEXFULL;
6710     sys2et[ENOANO] = UAENOANO;
6711     sys2et[EBADRQC] = UAEBADRQC;
6712     sys2et[EBADSLT] = UAEBADSLT;
6713     sys2et[EDEADLK] = UAEDEADLK;
6714     sys2et[EBFONT] = UAEBFONT;
6715     sys2et[ENOSTR] = UAENOSTR;
6716     sys2et[ENODATA] = UAENODATA;
6717     sys2et[ETIME] = UAETIME;
6718     sys2et[ENOSR] = UAENOSR;
6719     sys2et[ENONET] = UAENONET;
6720     sys2et[ENOPKG] = UAENOPKG;
6721     sys2et[EREMOTE] = UAEREMOTE;
6722     sys2et[ENOLINK] = UAENOLINK;
6723     sys2et[EADV] = UAEADV;
6724     sys2et[ESRMNT] = UAESRMNT;
6725     sys2et[ECOMM] = UAECOMM;
6726     sys2et[EPROTO] = UAEPROTO;
6727     sys2et[EMULTIHOP] = UAEMULTIHOP;
6728     sys2et[EDOTDOT] = UAEDOTDOT;
6729     sys2et[EBADMSG] = UAEBADMSG;
6730     sys2et[EOVERFLOW] = UAEOVERFLOW;
6731     sys2et[ENOTUNIQ] = UAENOTUNIQ;
6732     sys2et[EBADFD] = UAEBADFD;
6733     sys2et[EREMCHG] = UAEREMCHG;
6734     sys2et[ELIBACC] = UAELIBACC;
6735     sys2et[ELIBBAD] = UAELIBBAD;
6736     sys2et[ELIBSCN] = UAELIBSCN;
6737     sys2et[ELIBMAX] = UAELIBMAX;
6738     sys2et[ELIBEXEC] = UAELIBEXEC;
6739     sys2et[EILSEQ] = UAEILSEQ;
6740     sys2et[ERESTART] = UAERESTART;
6741     sys2et[ESTRPIPE] = UAESTRPIPE;
6742     sys2et[EUSERS] = UAEUSERS;
6743     sys2et[ENOTSOCK] = UAENOTSOCK;
6744     sys2et[EDESTADDRREQ] = UAEDESTADDRREQ;
6745     sys2et[EMSGSIZE] = UAEMSGSIZE;
6746     sys2et[EPROTOTYPE] = UAEPROTOTYPE;
6747     sys2et[ENOPROTOOPT] = UAENOPROTOOPT;
6748     sys2et[EPROTONOSUPPORT] = UAEPROTONOSUPPORT;
6749     sys2et[ESOCKTNOSUPPORT] = UAESOCKTNOSUPPORT;
6750     sys2et[EOPNOTSUPP] = UAEOPNOTSUPP;
6751     sys2et[EPFNOSUPPORT] = UAEPFNOSUPPORT;
6752     sys2et[EAFNOSUPPORT] = UAEAFNOSUPPORT;
6753     sys2et[EADDRINUSE] = UAEADDRINUSE;
6754     sys2et[EADDRNOTAVAIL] = UAEADDRNOTAVAIL;
6755     sys2et[ENETDOWN] = UAENETDOWN;
6756     sys2et[ENETUNREACH] = UAENETUNREACH;
6757     sys2et[ENETRESET] = UAENETRESET;
6758     sys2et[ECONNABORTED] = UAECONNABORTED;
6759     sys2et[ECONNRESET] = UAECONNRESET;
6760     sys2et[ENOBUFS] = UAENOBUFS;
6761     sys2et[EISCONN] = UAEISCONN;
6762     sys2et[ENOTCONN] = UAENOTCONN;
6763     sys2et[ESHUTDOWN] = UAESHUTDOWN;
6764     sys2et[ETOOMANYREFS] = UAETOOMANYREFS;
6765     sys2et[ETIMEDOUT] = UAETIMEDOUT;
6766     sys2et[ECONNREFUSED] = UAECONNREFUSED;
6767     sys2et[EHOSTDOWN] = UAEHOSTDOWN;
6768     sys2et[EHOSTUNREACH] = UAEHOSTUNREACH;
6769     sys2et[EALREADY] = UAEALREADY;
6770     sys2et[EINPROGRESS] = UAEINPROGRESS;
6771     sys2et[ESTALE] = UAESTALE;
6772     sys2et[EUCLEAN] = UAEUCLEAN;
6773     sys2et[ENOTNAM] = UAENOTNAM;
6774     sys2et[ENAVAIL] = UAENAVAIL;
6775     sys2et[EISNAM] = UAEISNAM;
6776     sys2et[EREMOTEIO] = UAEREMOTEIO;
6777     sys2et[EDQUOT] = UAEDQUOT;
6778     sys2et[ENOMEDIUM] = UAENOMEDIUM;
6779     sys2et[EMEDIUMTYPE] = UAEMEDIUMTYPE;
6780
6781     sys2et[EIO] = UAEIO;
6782 }
6783
6784 /* NOTE:  2006-03-01
6785  *  SRXAFS_CallBackRxConnAddr should be re-written as follows:
6786  *  - pass back the connection, client, and host from CallPreamble
6787  *  - keep a ref on the client, which we don't now
6788  *  - keep a hold on the host, which we already do
6789  *  - pass the connection, client, and host down into SAFSS_*, and use
6790  *    them instead of independently discovering them via rx_ConnectionOf
6791  *    (safe) and rx_GetSpecific (not so safe)
6792  *  The idea being that we decide what client and host we're going to use
6793  *  when CallPreamble is called, and stay consistent throughout the call.
6794  *  This change is too invasive for 1.4.1 but should be made in 1.5.x.
6795  */
6796
6797 afs_int32
6798 SRXAFS_CallBackRxConnAddr (struct rx_call * acall, afs_int32 *addr)
6799 {
6800     Error errorCode = 0;
6801     struct rx_connection *tcon;
6802     struct host *tcallhost;
6803 #ifdef __EXPERIMENTAL_CALLBACK_CONN_MOVING
6804     struct host *thost;
6805     struct client *tclient;
6806     static struct rx_securityClass *sc = 0;
6807     int i,j;
6808     struct rx_connection *conn;
6809 #endif
6810
6811     if ((errorCode = CallPreamble(acall, ACTIVECALL, &tcon, &tcallhost)))
6812             goto Bad_CallBackRxConnAddr1;
6813
6814 #ifndef __EXPERIMENTAL_CALLBACK_CONN_MOVING
6815     errorCode = 1;
6816 #else
6817     H_LOCK;
6818     tclient = h_FindClient_r(tcon);
6819     if (!tclient) {
6820         errorCode = VBUSY;
6821         goto Bad_CallBackRxConnAddr;
6822     }
6823     thost = tclient->host;
6824
6825     /* nothing more can be done */
6826     if ( !thost->interface )
6827         goto Bad_CallBackRxConnAddr;
6828
6829     /* the only address is the primary interface */
6830     /* can't change when there's only 1 address, anyway */
6831     if ( thost->interface->numberOfInterfaces <= 1 )
6832         goto Bad_CallBackRxConnAddr;
6833
6834     /* initialise a security object only once */
6835     if ( !sc )
6836         sc = (struct rx_securityClass *) rxnull_NewClientSecurityObject();
6837
6838     for ( i=0; i < thost->interface->numberOfInterfaces; i++)
6839     {
6840             if ( *addr == thost->interface->addr[i] ) {
6841                     break;
6842             }
6843     }
6844
6845     if ( *addr != thost->interface->addr[i] )
6846         goto Bad_CallBackRxConnAddr;
6847
6848     conn = rx_NewConnection (thost->interface->addr[i],
6849                              thost->port, 1, sc, 0);
6850     rx_SetConnDeadTime(conn, 2);
6851     rx_SetConnHardDeadTime(conn, AFS_HARDDEADTIME);
6852     H_UNLOCK;
6853     errorCode = RXAFSCB_Probe(conn);
6854     H_LOCK;
6855     if (!errorCode) {
6856         if ( thost->callback_rxcon )
6857             rx_DestroyConnection(thost->callback_rxcon);
6858         thost->callback_rxcon = conn;
6859         thost->host           = addr;
6860         rx_SetConnDeadTime(thost->callback_rxcon, 50);
6861         rx_SetConnHardDeadTime(thost->callback_rxcon, AFS_HARDDEADTIME);
6862         h_ReleaseClient_r(tclient);
6863         /* The hold on thost will be released by CallPostamble */
6864         H_UNLOCK;
6865         errorCode = CallPostamble(tcon, errorCode, tcallhost);
6866         return errorCode;
6867     } else {
6868         rx_DestroyConnection(conn);
6869     }
6870   Bad_CallBackRxConnAddr:
6871     h_ReleaseClient_r(tclient);
6872     /* The hold on thost will be released by CallPostamble */
6873     H_UNLOCK;
6874 #endif
6875
6876     errorCode = CallPostamble(tcon, errorCode, tcallhost);
6877  Bad_CallBackRxConnAddr1:
6878     return errorCode;          /* failure */
6879 }
6880
6881 afs_int32
6882 sys_error_to_et(afs_int32 in)
6883 {
6884     if (in == 0)
6885         return 0;
6886     if (in < 0 || in > 511)
6887         return in;
6888     if ((in >= VICE_SPECIAL_ERRORS && in <= VIO) || in == VRESTRICTED)
6889         return in;
6890     if (sys2et[in] != 0)
6891         return sys2et[in];
6892     return in;
6893 }