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