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