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