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