source: rtems/cpukit/libfs/src/nfsclient/src/nfs.c @ ea90df23

4.104.114.95
Last change on this file since ea90df23 was ea90df23, checked in by Chris Johns <chrisj@…>, on 04/03/08 at 03:13:24

2008-04-03 Chris Johns <chrisj@…>

  • libfs/src/nfsclient/src/librtemsNfs.h, libfs/src/nfsclient/src/nfs.c: Remove CEXP references. CEXP is external to RTEMS and even if in the cpukit it should not cross reference in this way.
  • libmisc/shell/shell_getchar.c: New. Taken from the monitor.
  • libmisc/Makefile.am: Add shell_getchar.c and clean up a little in the shell area.
  • libmisc/shell/shell.c, libmisc/shell/shell.h: Add line editting support.
  • Property mode set to 100644
File size: 80.0 KB
Line 
1/* $Id$ */
2
3/* NFS client implementation for RTEMS; hooks into the RTEMS filesystem */
4
5/* Author: Till Straumann <strauman@slac.stanford.edu> 2002 */
6
7/*
8 * Authorship
9 * ----------
10 * This software (NFS-2 client implementation for RTEMS) was created by
11 *     Till Straumann <strauman@slac.stanford.edu>, 2002-2007,
12 *         Stanford Linear Accelerator Center, Stanford University.
13 *
14 * Acknowledgement of sponsorship
15 * ------------------------------
16 * The NFS-2 client implementation for RTEMS was produced by
17 *     the Stanford Linear Accelerator Center, Stanford University,
18 *         under Contract DE-AC03-76SFO0515 with the Department of Energy.
19 *
20 * Government disclaimer of liability
21 * ----------------------------------
22 * Neither the United States nor the United States Department of Energy,
23 * nor any of their employees, makes any warranty, express or implied, or
24 * assumes any legal liability or responsibility for the accuracy,
25 * completeness, or usefulness of any data, apparatus, product, or process
26 * disclosed, or represents that its use would not infringe privately owned
27 * rights.
28 *
29 * Stanford disclaimer of liability
30 * --------------------------------
31 * Stanford University makes no representations or warranties, express or
32 * implied, nor assumes any liability for the use of this software.
33 *
34 * Stanford disclaimer of copyright
35 * --------------------------------
36 * Stanford University, owner of the copyright, hereby disclaims its
37 * copyright and all other rights in this software.  Hence, anyone may
38 * freely use it for any purpose without restriction. 
39 *
40 * Maintenance of notices
41 * ----------------------
42 * In the interest of clarity regarding the origin and status of this
43 * SLAC software, this and all the preceding Stanford University notices
44 * are to remain affixed to any copy or derivative of this software made
45 * or distributed by the recipient and are to be affixed to any copy of
46 * software made or distributed by the recipient that contains a copy or
47 * derivative of this software.
48 *
49 * ------------------ SLAC Software Notices, Set 4 OTT.002a, 2004 FEB 03
50 */
51
52#ifdef  HAVE_CONFIG_H
53#include <config.h>
54#endif
55
56#include <rtems.h>
57#include <rtems/libio.h>
58#include <rtems/libio_.h>
59#include <rtems/seterr.h>
60#include <string.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <assert.h>
64#include <sys/stat.h>
65#include <dirent.h>
66#include <netdb.h>
67#include <ctype.h>
68#include <netinet/in.h>
69#include <arpa/inet.h>
70
71#include <nfs_prot.h>
72#include <mount_prot.h>
73
74#include "rpcio.h"
75
76/* Configurable parameters */
77
78/* Estimated average length of a filename (including terminating 0).
79 * This was calculated by doing
80 *
81 *      find <some root> -print -exec basename '{}' \; > feil
82 *      wc feil
83 *
84 * AVG_NAMLEN = (num_chars + num_lines)/num_lines
85 */
86#define CONFIG_AVG_NAMLEN                               10
87
88#define CONFIG_NFS_SMALL_XACT_SIZE              800                     /* size of RPC arguments for non-write ops */
89/* lifetime of NFS attributes in a NfsNode;
90 * the time is in seconds and the lifetime is
91 * infinite if the symbol is #undef
92 */
93#define CONFIG_ATTR_LIFETIME                    10/*secs*/
94
95/*
96 * The 'st_blksize' (stat(2)) value this nfs
97 * client should report. If set to zero then the server's fattr data
98 * is passed throught which is not necessary optimal.
99 * Newlib's stdio uses 'st_blksize' (if built with HAVE_BLKSIZE defined)
100 * to size the default buffer.
101 * Due to the overhead of NFS it is probably better to use the maximum
102 * size of an NFS read request (8k) rather than the optimal block
103 * size on the server.
104 * This value can be overridden at run-time by setting the global
105 * variable 'nfsStBlksize'.
106 * Thanks to Steven Johnson <sjohnson@sakuraindustries.com> for helping
107 * working on this issue.
108 */   
109#define DEFAULT_NFS_ST_BLKSIZE                  NFS_MAXDATA
110
111/* dont change this without changing the maximal write size */
112#define CONFIG_NFS_BIG_XACT_SIZE                UDPMSGSIZE      /* dont change this */
113
114/* The real values for these are specified further down */
115#define NFSCALL_TIMEOUT                                 (&_nfscalltimeout)
116#define MNTCALL_TIMEOUT                                 (&_nfscalltimeout)
117static struct timeval _nfscalltimeout = { 10, 0 };      /* {secs, us } */
118
119/* More or less fixed constants; in particular, NFS3 is not supported */
120#define DELIM                                                   '/'
121#define HOSTDELIM                                               ':'
122#define UPDIR                                                   ".."
123#define UIDSEP                                                  '@'
124#define NFS_VERSION_2                                   NFS_VERSION
125
126/* we use a dynamically assigned major number */
127#define NFS_MAJOR                                               (nfsGlob.nfs_major)
128
129
130/* NOTE: RTEMS (ss-20020301) uses a 'short st_ino' type :-( but the
131 * NFS fileid is 32 bit. [Later versions of RTEMS have fixed this;
132 * nfsInit() issues a warning if you run a version with 'short st_ino'.]
133 *
134 * As a workarount, we merge the upper 16bits of the fileid into the
135 * minor device no. Hence, it is still possible to uniquely identify
136 * a file by looking at its device number (major = nfs, minor = part
137 * of the fileid + our 'nfs-id' identifier).
138 *
139 * This has an impact on performance, as e.g. getcwd() stats() all
140 * directory entries when it believes it has crossed a mount point
141 * (a.st_dev != b.st_dev).
142 *
143 * OTOH, it also might cause node comparison failure! E.g. 'getcwd()'
144 * assumes that two nodes residing in the same directory must be located
145 * on the same device and hence compares 'st_ino' only.
146 * If two files in the same directory have the same inode number
147 * modulo 2^16, they will be considered equal (although their device
148 * number doesn't match - getcwd doesn't look at it).
149 *
150 * Other software might or might not be affected.
151 *
152 * The only clean solution to this problem is bumping up the size of
153 * 'ino_t' at least to 'long'.
154 * Note that this requires _all_ software (libraries etc.) to be
155 * recompiled.
156 */
157
158#define NFS_MAKE_DEV_T_INO_HACK(node) \
159                rtems_filesystem_make_dev_t( NFS_MAJOR, \
160                        (((node)->nfs->id)<<16) | (SERP_ATTR((node)).fileid >> 16) )
161
162/* use our 'nfs id' and the server's fsid for the minor device number
163 * this should be fairly unique
164 */
165#define NFS_MAKE_DEV_T(node) \
166                rtems_filesystem_make_dev_t( NFS_MAJOR, \
167                        (((node)->nfs->id)<<16) | (SERP_ATTR((node)).fsid & ((1<<16)-1)) )
168
169#define  DIRENT_HEADER_SIZE ( sizeof(struct dirent) - \
170                        sizeof( ((struct dirent *)0)->d_name ) )
171
172
173/* debugging flags */
174#define DEBUG_COUNT_NODES       (1<<0)
175#define DEBUG_TRACK_NODES       (1<<1)
176#define DEBUG_EVALPATH          (1<<2)
177#define DEBUG_READDIR           (1<<3)
178#define DEBUG_SYSCALLS          (1<<4)
179
180/* #define DEBUG        ( DEBUG_SYSCALLS | DEBUG_COUNT_NODES ) */
181
182#ifdef DEBUG
183#define STATIC
184#else
185#define STATIC static
186#endif
187
188#define MUTEX_ATTRIBUTES    (RTEMS_LOCAL           |   \
189                            RTEMS_PRIORITY         |   \
190                            RTEMS_INHERIT_PRIORITY |   \
191                            RTEMS_BINARY_SEMAPHORE)
192
193#define LOCK(s)         do {                               \
194                                                rtems_semaphore_obtain((s),    \
195                                                                        RTEMS_WAIT,        \
196                                                                        RTEMS_NO_TIMEOUT); \
197                                        } while (0)
198
199#define UNLOCK(s)       do { rtems_semaphore_release((s)); \
200                                        } while (0)
201
202/*****************************************
203        Types with Associated XDR Routines
204 *****************************************/
205
206/* a string buffer with a maximal length.
207 * If the buffer pointer is NULL, it is updated
208 * with an appropriately allocated area.
209 */
210typedef struct strbuf {
211        char    *buf;
212        u_int   max;
213} strbuf;
214
215static bool_t
216xdr_strbuf(XDR *xdrs, strbuf *obj)
217{
218        return xdr_string(xdrs, &obj->buf, obj->max);
219}
220
221/* Read 'readlink' results into a 'strbuf'.
222 * This is convenient as it avoids 
223 * one extra step of copying / lenght
224 * checking.
225 */
226typedef struct readlinkres_strbuf {
227        nfsstat status;
228        strbuf  strbuf;
229} readlinkres_strbuf;
230
231static bool_t
232xdr_readlinkres_strbuf(XDR *xdrs, readlinkres_strbuf *objp)
233{
234        if ( !xdr_nfsstat(xdrs, &objp->status) )
235                return FALSE;
236
237        if ( NFS_OK == objp->status ) {
238                if ( !xdr_string(xdrs, &objp->strbuf.buf, objp->strbuf.max) )
239                        return FALSE;
240        }
241        return TRUE;
242}
243
244
245/* DirInfoRec is used instead of dirresargs
246 * to convert recursion into iteration. The
247 * 'rpcgen'erated xdr_dirresargs ends up
248 * doing nested calls when unpacking the
249 * 'next' pointers.
250 */
251
252typedef struct DirInfoRec_ {
253        readdirargs     readdirargs;
254        /* clone of the 'readdirres' fields;
255         * the cookie is put into the readdirargs above
256         */
257        nfsstat         status;
258        char            *buf, *ptr;
259        int                     len;
260        bool_t          eofreached;
261} DirInfoRec, *DirInfo;
262
263/* this deals with one entry / record */
264static bool_t
265xdr_dir_info_entry(XDR *xdrs, DirInfo di)
266{
267union   {
268        char                    nambuf[NFS_MAXNAMLEN+1];
269        nfscookie               cookie;
270}                               dummy;
271struct dirent   *pde = (struct dirent *)di->ptr;
272u_int                   fileid;
273char                    *name;
274register int    nlen = 0,len,naligned = 0;
275nfscookie               *pcookie;
276
277        len = di->len;
278
279        if ( !xdr_u_int(xdrs, &fileid) )
280                return FALSE;
281
282        /* we must pass the address of a char* */
283        name = (len > NFS_MAXNAMLEN) ? pde->d_name : dummy.nambuf;
284
285        if ( !xdr_filename(xdrs, &name) ) {
286                return FALSE;
287        }
288
289        if (len >= 0) {
290                nlen      = strlen(name);
291                naligned  = nlen + 1 /* string delimiter */ + 3 /* alignment */;
292                naligned &= ~3;
293                len      -= naligned;
294        }
295
296        /* if the cookie goes into the DirInfo, we hope this doesn't fail
297         * - the caller ends up with an invalid readdirargs cookie otherwise...
298         */
299        pcookie = (len >= 0) ? &di->readdirargs.cookie : &dummy.cookie;
300        if ( !xdr_nfscookie(xdrs, pcookie) ) {
301                return FALSE;
302        }
303
304        di->len = len;
305        /* adjust the buffer pointer */
306        if (len >= 0) {
307                pde->d_ino    = fileid;
308                pde->d_namlen = nlen;
309                pde->d_off        = di->ptr - di->buf;
310                if (name == dummy.nambuf) {
311                        memcpy(pde->d_name, dummy.nambuf, nlen + 1);
312                }
313                pde->d_reclen = DIRENT_HEADER_SIZE + naligned;
314                di->ptr      += pde->d_reclen;
315        }
316
317        return TRUE;
318}
319
320/* this routine loops over all entries */
321static bool_t
322xdr_dir_info(XDR *xdrs, DirInfo di)
323{
324DirInfo dip;
325
326        if ( !xdr_nfsstat(xdrs, &di->status) )
327                return FALSE;
328
329        if ( NFS_OK != di->status )
330                return TRUE;
331
332        dip = di;
333
334        while (dip) {
335                /* reserve space for the dirent 'header' - we assume it's word aligned! */
336#ifdef DEBUG
337                assert( DIRENT_HEADER_SIZE % 4 == 0 );
338#endif
339                dip->len -= DIRENT_HEADER_SIZE;
340
341                /* we pass a 0 size - size is unused since
342                 * we always pass a non-NULL pointer
343                 */
344                if ( !xdr_pointer(xdrs, (void*)&dip, 0 /* size */, (xdrproc_t)xdr_dir_info_entry) )
345                        return FALSE;
346        }
347
348        if ( ! xdr_bool(xdrs, &di->eofreached) )
349                return FALSE;
350
351        /* if everything fits into the XDR buffer but not the user's buffer,
352         * they must resume reading from where xdr_dir_info_entry() started
353         * skipping and 'eofreached' needs to be adjusted
354         */
355        if ( di->len < 0 && di->eofreached )
356                di->eofreached = FALSE;
357
358        return TRUE;
359}
360
361
362/* a type better suited for node operations
363 * than diropres.
364 * fattr and fhs are swapped so parts of this
365 * structure may be used as a diroparg which
366 * is practical when looking up paths.
367 */
368
369/* Macro for accessing serporid fields
370 */
371#define SERP_ARGS(node) ((node)->serporid.serporid_u.serporid.arg_u)
372#define SERP_ATTR(node) ((node)->serporid.serporid_u.serporid.attributes)
373#define SERP_FILE(node) ((node)->serporid.serporid_u.serporid.file)
374
375
376typedef struct serporidok {
377        fattr                                   attributes;
378        nfs_fh                                  file;
379        union   {
380                struct {
381                        filename        name;
382                }                                       diroparg;
383                struct {
384                        sattr           attributes;
385                }                                       sattrarg;
386                struct {
387                        u_int           offset;
388                        u_int           count;
389                        u_int           totalcount;
390                }                                       readarg;
391                struct {
392                        u_int           beginoffset;
393                        u_int           offset;
394                        u_int           totalcount;
395                        struct {
396                                u_int data_len;
397                                char* data_val;
398                        }                       data;
399                }                                       writearg;
400                struct {
401                        filename        name;
402                        sattr           attributes;
403                }                                       createarg;
404                struct {
405                        filename        name;
406                        diropargs       to;
407                }                                       renamearg;
408                struct {
409                        diropargs       to;
410                }                                       linkarg;
411                struct {
412                        filename        name;
413                        nfspath         to;
414                        sattr           attributes;
415                }                                       symlinkarg;
416                struct {
417                        nfscookie       cookie;
418                        u_int           count;
419                }                                       readdirarg;
420        }                                                       arg_u;
421} serporidok;
422
423typedef struct serporid {
424        nfsstat                 status;
425        union   {
426                serporidok      serporid;
427        }                               serporid_u;
428} serporid;
429
430/* an XDR routine to encode/decode the inverted diropres
431 * into an nfsnodestat;
432 *
433 * NOTE: this routine only acts on
434 *   - 'serporid.status'
435 *   - 'serporid.file'
436 *   - 'serporid.attributes'
437 * and leaves the 'arg_u' alone.
438 *
439 * The idea is that a 'diropres' is read into 'serporid'
440 * which can then be used as an argument to subsequent
441 * NFS-RPCs (after filling in the node's arg_u).
442 */
443static bool_t
444xdr_serporidok(XDR *xdrs, serporidok *objp)
445{
446     if (!xdr_nfs_fh (xdrs, &objp->file))
447         return FALSE;
448     if (!xdr_fattr (xdrs, &objp->attributes))
449         return FALSE;
450    return TRUE;
451}   
452
453static bool_t
454xdr_serporid(XDR *xdrs, serporid *objp)
455{
456     if (!xdr_nfsstat (xdrs, &objp->status))
457         return FALSE;
458    switch (objp->status) {
459    case NFS_OK:
460         if (!xdr_serporidok(xdrs, &objp->serporid_u.serporid))
461             return FALSE;
462        break;
463    default:
464        break;
465    }
466    return TRUE;
467}
468
469/*****************************************
470        Data Structures and Types
471 *****************************************/
472
473/* 'time()' hack with less overhead; */
474
475/* assume reading a long word is atomic */
476#define READ_LONG_IS_ATOMIC
477
478typedef uint32_t        TimeStamp;
479
480static inline TimeStamp
481nowSeconds(void)
482{
483register uint32_t       rval;
484#ifndef READ_LONG_IS_ATOMIC
485rtems_interrupt_level           l;
486
487        rtems_interrupt_disable(level);
488#endif
489
490        rval = _TOD_Seconds_since_epoch;
491
492#ifndef READ_LONG_IS_ATOMIC
493        rtems_interrupt_enable(level);
494#endif
495        return rval;
496}
497
498
499/* Per mounted FS structure */
500typedef struct NfsRec_ {
501                /* the NFS server we're talking to.
502                 */
503        RpcUdpServer                                             server;
504                /* statistics; how many NfsNodes are
505                 * currently alive.
506                 */
507        volatile int                                             nodesInUse;
508#if DEBUG & DEBUG_COUNT_NODES
509                /* statistics; how many 'NfsNode.str'
510                 * strings are currently allocated.
511                 */
512        volatile int                                             stringsInUse;
513#endif
514                /* A small number who uniquely
515                 * identifies a mounted NFS within
516                 * this driver (i.e. this NfsRec).
517                 * Each time a NFS is mounted, the
518                 * global ID counter is incremented
519                 * and its value is assigned to the
520                 * newly created NfsRec.
521                 */
522        u_short                                                          id;
523                /* Our RTEMS filesystem mt_entry
524                 */
525        rtems_filesystem_mount_table_entry_t *mt_entry;
526                /* Next NfsRec on a linked list who
527                 * is anchored at nfsGlob
528                 */
529        struct NfsRec_                                           *next;
530                /* Who we pretend we are
531                 */
532        u_long                                                           uid,gid;
533} NfsRec, *Nfs;
534
535typedef struct NfsNodeRec_ {
536                /* This holds this node's attributes
537                 * (stats) and its nfs filehandle.
538                 * It also contains room for nfs rpc
539                 * arguments.
540                 */
541        serporid        serporid;
542                /* The arguments we used when doing
543                 * the 'lookup' call for this node.
544                 * We need this information (especially
545                 * the directory FH) for performing
546                 * certain operations on this
547                 * node (in particular: for unlinking
548                 * it from a parent directory)
549                 */
550        diropargs               args;
551                /* FS this node belongs to
552                 */
553        Nfs                             nfs;
554                /* A buffer for the string the
555                 * args.name points to.
556                 * We need this because args.name might
557                 * temporarily point to strings on the
558                 * stack. Duplicates are allocated from
559                 * the heap and attached to 'str' so
560                 * they can be released as appropriate.
561                 */
562        char               *str;
563                /* A timestamp for the stats
564                 */
565        TimeStamp               age;
566} NfsNodeRec, *NfsNode;
567
568/*****************************************
569        Forward Declarations
570 *****************************************/
571
572static int nfs_readlink(
573        rtems_filesystem_location_info_t  *loc,         /* IN  */       
574        char                                                      *buf,                 /* OUT */
575        size_t                                                    len
576);
577
578static int updateAttr(NfsNode node, int force);
579
580/* Mask bits when setting attributes.
581 * Only the 'arg' fields with their
582 * corresponding bit set in the mask
583 * will be used. The others are left
584 * unchanged.
585 * The 'TOUCH' bits instruct nfs_sattr()
586 * to update the respective time
587 * fields to the current time
588 */
589#define SATTR_MODE              (1<<0)
590#define SATTR_UID               (1<<1)
591#define SATTR_GID               (1<<2)
592#define SATTR_SIZE              (1<<3)
593#define SATTR_ATIME             (1<<4)
594#define SATTR_TOUCHA    (1<<5)
595#define SATTR_MTIME             (1<<6)
596#define SATTR_TOUCHM    (1<<7)
597#define SATTR_TOUCH             (SATTR_TOUCHM | SATTR_TOUCHA)
598
599static int
600nfs_sattr(NfsNode node, sattr *arg, u_long mask);
601
602extern struct _rtems_filesystem_operations_table nfs_fs_ops;
603static struct _rtems_filesystem_file_handlers_r  nfs_file_file_handlers;
604static struct _rtems_filesystem_file_handlers_r  nfs_dir_file_handlers;
605static struct _rtems_filesystem_file_handlers_r  nfs_link_file_handlers;
606static             rtems_driver_address_table            drvNfs;
607
608int
609nfsMountsShow(FILE*);
610
611rtems_status_code
612rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc);
613
614
615/*****************************************
616        Inline Routines
617 *****************************************/
618
619
620/* * * * * * * * * * * * * * * * * *
621        Trivial Operations on a NfsNode
622 * * * * * * * * * * * * * * * * * */
623
624/* determine if a location 'l' is an NFS root node */
625static inline int
626locIsRoot(rtems_filesystem_location_info_t *l)
627{
628NfsNode me = (NfsNode) l->node_access;
629NfsNode r;
630        r = (NfsNode)l->mt_entry->mt_fs_root.node_access;
631        return SERP_ATTR(r).fileid == SERP_ATTR(me).fileid &&
632                   SERP_ATTR(r).fsid   == SERP_ATTR(me).fsid;
633}
634
635/* determine if a location 'l' is an NFS node */
636static inline int
637locIsNfs(rtems_filesystem_location_info_t *l)
638{
639        return l->ops == &nfs_fs_ops;
640}
641
642/* determine if two locations refer to the
643 * same entity. We know that 'nfsloc' is a
644 * location inside nfs. However, we needn't
645 * know anything about 'anyloc'.
646 */
647static inline int
648locAreEqual(
649        rtems_filesystem_location_info_t *nfsloc,
650        rtems_filesystem_location_info_t *anyloc
651)
652{
653NfsNode na = (NfsNode) nfsloc->node_access;
654NfsNode nb;
655
656        if (!locIsNfs(anyloc))
657                return 0;
658
659        nb = (NfsNode) anyloc->node_access;
660
661        if (na->nfs != nb->nfs)
662                return 0;
663
664        updateAttr(nb, 0);
665
666        return SERP_ATTR(na).fileid == SERP_ATTR(nb).fileid &&
667                   SERP_ATTR(na).fsid   == SERP_ATTR(nb).fsid;
668}
669
670
671
672/*****************************************
673        Global Variables
674 *****************************************/
675
676/* These are (except for MAXNAMLEN/MAXPATHLEN) copied from IMFS */
677
678static rtems_filesystem_limits_and_options_t
679nfs_limits_and_options = {
680   5,                           /* link_max */
681   6,                           /* max_canon */
682   7,                           /* max_input */
683   NFS_MAXNAMLEN,       /* name_max */
684   NFS_MAXPATHLEN,      /* path_max */
685   2,                           /* pipe_buf */
686   1,                           /* posix_async_io */
687   2,                           /* posix_chown_restrictions */
688   3,                           /* posix_no_trunc */
689   4,                           /* posix_prio_io */
690   5,                           /* posix_sync_io */
691   6                            /* posix_vdisable */
692};
693
694/* size of an encoded 'entry' object */
695static int dirres_entry_size;
696
697/* Global stuff and statistics */
698static struct nfsstats {
699                /* A lock for protecting the
700                 * linked ist of mounted NFS
701                 * and the num_mounted_fs field
702                 */
703        rtems_id                                        llock;
704                /* A lock for protecting misc
705                 * stuff  within the driver.
706                 * The lock must only be held
707                 * for short periods of time.
708                 */
709        rtems_id                                        lock;
710                /* Our major number as assigned
711                 * by RTEMS
712                 */
713        rtems_device_major_number       nfs_major;
714                /* The number of currently
715                 * mounted NFS
716                 */
717        int                                                     num_mounted_fs;
718                /* A list of the currently
719                 * mounted NFS
720                 */
721        struct NfsRec_                          *mounted_fs;
722                /* A counter for allocating
723                 * unique IDs to each mounted
724                 * NFS.
725                 * Assume we are not going to
726                 * do more than 16k mounts
727                 * during the system lifetime
728                 */
729        u_short                                         fs_ids;
730} nfsGlob = {0/* IMPORTANT */};
731
732/*
733 * Global variable to tune the 'st_blksize' (stat(2)) value this nfs
734 * client should report.
735 * size on the server.
736 */                   
737#ifndef DEFAULT_NFS_ST_BLKSIZE
738#define DEFAULT_NFS_ST_BLKSIZE  NFS_MAXDATA
739#endif
740int nfsStBlksize = DEFAULT_NFS_ST_BLKSIZE;
741
742/* Two pools of RPC transactions;
743 * One with small send buffers
744 * the other with a big one.
745 * The actual size of the small
746 * buffer is configurable (see top).
747 *
748 * Note: The RX buffers are always
749 * big
750 */
751static RpcUdpXactPool smallPool = 0;
752static RpcUdpXactPool bigPool   = 0;
753
754
755/*****************************************
756        Implementation
757 *****************************************/
758
759/* Create a Nfs object. This is
760 * per-mounted NFS information.
761 *
762 * ARGS:        The Nfs server handle.
763 *
764 * RETURNS:     Nfs on success,
765 *                      NULL on failure with
766 *                      errno set
767 *
768 * NOTE:        The submitted server
769 *                      object is 'owned' by
770 *                      this Nfs and will be
771 *                      destroyed by nfsDestroy()
772 */
773static Nfs
774nfsCreate(RpcUdpServer server)
775{
776Nfs rval = calloc(1,sizeof(*rval));
777
778        if (rval) {
779                rval->server     = server;
780                LOCK(nfsGlob.llock);
781                        rval->next                 = nfsGlob.mounted_fs;
782                        nfsGlob.mounted_fs = rval;
783                UNLOCK(nfsGlob.llock);
784        } else {
785                errno = ENOMEM;
786        }
787                return rval;
788}
789
790/* Destroy an Nfs object and
791 * its associated server
792 */
793static void
794nfsDestroy(Nfs nfs)
795{
796register Nfs prev;
797        if (!nfs)
798                return;
799
800        LOCK(nfsGlob.llock);
801                if (nfs == nfsGlob.mounted_fs)
802                        nfsGlob.mounted_fs = nfs->next;
803                else {
804                        for (prev = nfsGlob.mounted_fs;
805                                 prev && prev->next != nfs;
806                                 prev = prev->next)
807                                        /* nothing else to do */;
808                        assert( prev );
809                        prev->next = nfs->next;
810                }
811        UNLOCK(nfsGlob.llock);
812
813        nfs->next = 0; /* paranoia */
814        rpcUdpServerDestroy(nfs->server);
815        free(nfs);
816}
817
818/*
819 * Create a Node. The node will
820 * be associated with a particular
821 * mounted NFS identified by 'nfs'
822 * Optionally, a NFS file handle
823 * may be copied into this node.
824 *
825 * ARGS:        nfs of the NFS this node
826 *                      belongs to.
827 *                      NFS file handle identifying
828 *                      this node.
829 * RETURNS:     node on success,
830 *                      NULL on failure with errno
831 *                      set.
832 *
833 * NOTE:        The caller of this routine
834 *                      is responsible for copying
835 *                      a NFS file handle if she
836 *                      choses to pass a NULL fh.
837 *
838 *                      The driver code assumes the
839 *                      a node always has a valid
840 *                      NFS filehandle and file
841 *                      attributes (unless the latter
842 *                      are aged).
843 */
844static NfsNode
845nfsNodeCreate(Nfs nfs, fhandle *fh)
846{
847NfsNode rval = malloc(sizeof(*rval));
848unsigned long flags;
849
850#if DEBUG & DEBUG_TRACK_NODES
851        fprintf(stderr,"NFS: creating a node\n");
852#endif
853
854        if (rval) {
855                if (fh)
856                        memcpy( &SERP_FILE(rval), fh, sizeof(*fh) );
857                rtems_interrupt_disable(flags);
858                        nfs->nodesInUse++;
859                rtems_interrupt_enable(flags);
860                rval->nfs       = nfs;
861                rval->str               = 0;
862        } else {
863                errno = ENOMEM;
864        }
865
866        return rval;
867}
868
869/* destroy a node */
870static void
871nfsNodeDestroy(NfsNode node)
872{
873unsigned long flags;
874
875#if DEBUG & DEBUG_TRACK_NODES
876        fprintf(stderr,"NFS: destroying a node\n");
877#endif
878#if 0
879        if (!node)
880                return;
881        /* this probably does nothing... */
882        xdr_free(xdr_serporid, &node->serporid);
883#endif
884
885        rtems_interrupt_disable(flags);
886                node->nfs->nodesInUse--;
887#if DEBUG & DEBUG_COUNT_NODES
888                if (node->str)
889                        node->nfs->stringsInUse--;
890#endif
891        rtems_interrupt_enable(flags);
892
893        if (node->str)
894                free(node->str);
895
896        free(node);
897}
898
899/* Clone a given node (AKA copy constructor),
900 * i.e. create an exact copy.
901 *
902 * ARGS:        node to clone
903 * RETURNS:     new node on success
904 *                      NULL on failure with errno set.
905 *
906 * NOTE:        a string attached to 'str'
907 *                      is cloned as well. Outdated
908 *                      attributes (of the new copy
909 *                      only) will be refreshed
910 *                      (if unsuccessful, this could
911 *                      be a reason for failure to
912 *                      clone a node).
913 */
914static NfsNode
915nfsNodeClone(NfsNode node)
916{
917NfsNode rval = nfsNodeCreate(node->nfs, 0);
918
919        if (rval) {
920                *rval = *node;
921
922                /* must clone the string also */
923                if (node->str) {
924                        rval->args.name = rval->str = strdup(node->str);
925                        if (!rval->str) {
926                                nfsNodeDestroy(rval);
927                                return 0;
928                        }
929#if DEBUG & DEBUG_COUNT_NODES
930                        { unsigned long flags;
931                        rtems_interrupt_disable(flags);
932                                node->nfs->stringsInUse++;
933                        rtems_interrupt_enable(flags);
934                        }
935#endif
936                }
937
938                /* possibly update the stats */
939                if (updateAttr(rval, 0 /* only if necessary */)) {
940                        nfsNodeDestroy(rval);
941                        return 0;
942                }
943        }
944        return rval;
945}
946
947/* Initialize the driver.
948 *
949 * ARGS:        depth of the small and big
950 *                      transaction pools, i.e. how
951 *                      many transactions (buffers)
952 *                      should always be kept around.
953 *
954 *                      (If more transactions are needed,
955 *                      they are created and destroyed
956 *                      on the fly).
957 */
958void
959nfsInit(int smallPoolDepth, int bigPoolDepth)
960{
961static int initialised = 0;
962entry   dummy;
963
964        if (initialised)
965                return;
966
967        initialised = 1;
968
969        fprintf(stderr,
970          "RTEMS-NFS $Release$, "                       \
971          "Till Straumann, Stanford/SLAC/SSRL 2002, " \
972          "See LICENSE file for licensing info.\n");
973
974        /* Get a major number */
975
976        if (RTEMS_SUCCESSFUL != rtems_io_register_driver(0, &drvNfs, &nfsGlob.nfs_major)) {
977                fprintf(stderr,"Registering NFS driver failed - %s\n", strerror(errno));
978                return;
979        }
980
981        if (0==smallPoolDepth)
982                smallPoolDepth = 20;
983        if (0==bigPoolDepth)
984                bigPoolDepth   = 10;
985
986        /* it's crucial to zero out the 'next' pointer
987         * because it terminates the xdr_entry recursion
988         *
989         * we also must make the filename some non-zero
990         * char pointer!
991         */
992
993        memset(&dummy, 0, sizeof(dummy));
994
995        dummy.nextentry   = 0;
996        dummy.name        = "somename"; /* guess average length of a filename */
997        dirres_entry_size = xdr_sizeof((xdrproc_t)xdr_entry, &dummy);
998
999        assert( smallPool = rpcUdpXactPoolCreate(
1000                                                        NFS_PROGRAM,
1001                                                        NFS_VERSION_2,
1002                                                        CONFIG_NFS_SMALL_XACT_SIZE,
1003                                                        smallPoolDepth) );
1004
1005        assert( bigPool   = rpcUdpXactPoolCreate(
1006                                                        NFS_PROGRAM,
1007                                                        NFS_VERSION_2,
1008                                                        CONFIG_NFS_BIG_XACT_SIZE,
1009                                                        bigPoolDepth) );
1010
1011        assert( RTEMS_SUCCESSFUL == rtems_semaphore_create(
1012                                                        rtems_build_name('N','F','S','l'),
1013                                                        1,
1014                                                        MUTEX_ATTRIBUTES,
1015                                                        0,
1016                                                        &nfsGlob.llock) );
1017
1018        assert( RTEMS_SUCCESSFUL == rtems_semaphore_create(
1019                                                        rtems_build_name('N','F','S','m'),
1020                                                        1,
1021                                                        MUTEX_ATTRIBUTES,
1022                                                        0,
1023                                                        &nfsGlob.lock) );
1024
1025        if (sizeof(ino_t) < sizeof(u_int)) {
1026                fprintf(stderr,
1027                                "WARNING: Using 'short st_ino' hits performance and may fail to access/find correct files\n");
1028                fprintf(stderr,
1029                                "you should fix newlib's sys/stat.h - for now I'll enable a hack...\n");
1030
1031        }
1032}
1033
1034/* Driver cleanup code
1035 */
1036int
1037nfsCleanup(void)
1038{
1039rtems_id        l;
1040int                     refuse;
1041
1042        if (!nfsGlob.llock) {
1043                /* registering the driver failed - let them still cleanup */
1044                return 0;
1045        }
1046
1047        LOCK(nfsGlob.llock);
1048        if ( (refuse = nfsGlob.num_mounted_fs) ) {
1049                fprintf(stderr,"Refuse to unload NFS; %i filesystems still mounted.\n",
1050                                                refuse);
1051                nfsMountsShow(stderr);
1052                /* yes, printing is slow - but since you try to unload the driver,
1053                 * you assume nobody is using NFS, so what if they have to wait?
1054                 */
1055                UNLOCK(nfsGlob.llock);
1056                return -1;
1057        }
1058
1059        rtems_semaphore_delete(nfsGlob.lock);
1060        nfsGlob.lock = 0;
1061
1062        /* hold the lock while cleaning up... */
1063
1064        rpcUdpXactPoolDestroy(smallPool);
1065        rpcUdpXactPoolDestroy(bigPool);
1066        l = nfsGlob.llock;
1067        rtems_io_unregister_driver(nfsGlob.nfs_major);
1068
1069        rtems_semaphore_delete(l);
1070        nfsGlob.llock = 0;
1071        return 0;
1072}
1073
1074/* NFS RPC wrapper.
1075 *
1076 * ARGS:        srvr    the NFS server we want to call
1077 *                      proc    the NFSPROC_xx we want to invoke
1078 *                      xargs   xdr routine to wrap the arguments
1079 *                      pargs   pointer to the argument object
1080 *                      xres    xdr routine to unwrap the results
1081 *                      pres    pointer to the result object
1082 *
1083 * RETURNS:     0 on success, -1 on error with errno set.
1084 *
1085 * NOTE:        the caller assumes that errno is set to
1086 *                      a nonzero value if this routine returns
1087 *                      an error (nonzero return value).
1088 *
1089 *                      This routine prints RPC error messages to
1090 *                      stderr.
1091 */
1092STATIC int
1093nfscall(
1094        RpcUdpServer    srvr,
1095        int                             proc,
1096        xdrproc_t               xargs,
1097        void *                  pargs,
1098        xdrproc_t               xres,
1099        void *                  pres)
1100{
1101RpcUdpXact              xact;
1102enum clnt_stat  stat;
1103RpcUdpXactPool  pool;
1104int                             rval = -1;
1105
1106
1107        switch (proc) {
1108                case NFSPROC_SYMLINK:
1109                case NFSPROC_WRITE:
1110                                        pool = bigPool;         break;
1111                default:        pool = smallPool;       break;
1112        }
1113
1114        xact = rpcUdpXactPoolGet(pool, XactGetCreate);
1115
1116        if ( !xact ) {
1117                errno = ENOMEM;
1118                return -1;
1119        }
1120
1121        if ( RPC_SUCCESS != (stat=rpcUdpSend(
1122                                                                xact,
1123                                                                srvr,
1124                                                                NFSCALL_TIMEOUT,
1125                                                                proc,
1126                                                                xres,
1127                                                                pres,
1128                                                                xargs,
1129                                                                pargs,
1130                                                                0)) ||
1131             RPC_SUCCESS != (stat=rpcUdpRcv(xact)) ) {
1132
1133                fprintf(stderr,
1134                                "NFS (proc %i) - %s\n",
1135                                proc,
1136                                clnt_sperrno(stat));
1137
1138                switch (stat) {
1139                        /* TODO: this is probably not complete and/or fully accurate */
1140                        case RPC_CANTENCODEARGS : errno = EINVAL;       break;
1141                        case RPC_AUTHERROR      : errno = EPERM;        break;
1142
1143                        case RPC_CANTSEND               :
1144                        case RPC_CANTRECV               : /* hope they have errno set */
1145                        case RPC_SYSTEMERROR    : break;
1146
1147                        default                 : errno = EIO;          break;
1148                }
1149        } else {
1150                rval = 0;
1151        }
1152
1153        /* release the transaction back into the pool */
1154        rpcUdpXactPoolPut(xact);
1155
1156        if (rval && !errno)
1157                errno = EIO;
1158
1159        return rval;
1160}
1161
1162/* Check the 'age' of a node's stats
1163 * and read the attributes from the server
1164 * if necessary.
1165 *
1166 * ARGS:        node    node to update
1167 *                      force   enforce updating ignoring
1168 *                                      the timestamp/age
1169 *
1170 * RETURNS:     0 on success,
1171 *                      -1 on failure with errno set
1172 */
1173
1174static int
1175updateAttr(NfsNode node, int force)
1176{
1177
1178        if (force
1179#ifdef CONFIG_ATTR_LIFETIME
1180                || (nowSeconds() - node->age > CONFIG_ATTR_LIFETIME)
1181#endif
1182                ) {
1183                if ( nfscall(node->nfs->server,
1184                                          NFSPROC_GETATTR,
1185                                          (xdrproc_t)xdr_nfs_fh,        &SERP_FILE(node),
1186                                          (xdrproc_t)xdr_attrstat, &node->serporid) )
1187                return -1;
1188
1189                if ( NFS_OK != node->serporid.status ) {
1190                        errno = node->serporid.status;
1191                        return -1;
1192                }
1193
1194                node->age = nowSeconds();
1195        }
1196       
1197        return 0;
1198}
1199
1200/*
1201 * IP address helper. Note that we avoid
1202 * gethostbyname() since it's not reentrant.
1203 *
1204 * initialize a sockaddr_in from a
1205 * [<uid>'.'<gid>'@']<host>':'<path>" string and let
1206 * pPath point to the <path> part; retrieve the optional
1207 * uid/gids
1208 *
1209 * ARGS:        see description above
1210 *
1211 * RETURNS:     0 on success,
1212 *                      -1 on failure with errno set
1213 */
1214static int
1215buildIpAddr(u_long *puid, u_long *pgid,
1216                        char **pHost, struct sockaddr_in *psa,
1217                        char **pPath)
1218{
1219char    host[30];
1220char    *chpt = *pPath;
1221char    *path;
1222int             len;
1223
1224        if ( !chpt ) {
1225                errno = EINVAL;
1226                return -1;
1227        }
1228
1229        /* look for the optional uid/gid */
1230        if ( (chpt = strchr(chpt, UIDSEP)) ) {
1231                if ( 2 != sscanf(*pPath,"%li.%li",puid,pgid) ) {
1232                        errno = EINVAL;
1233                        return -1;
1234                }
1235                chpt++;
1236        } else {
1237                *puid = RPCIOD_DEFAULT_ID;
1238                *pgid = RPCIOD_DEFAULT_ID;
1239                chpt  = *pPath;
1240        }
1241        if ( pHost )
1242                *pHost = chpt;
1243
1244        /* split the device name which is in the form
1245         *
1246         * <host_ip> ':' <path>
1247         *
1248         * into its components using a local buffer
1249         */
1250
1251        if ( !(path = strchr(chpt, HOSTDELIM)) ||
1252              (len  = path - chpt) >= sizeof(host) - 1 ) {
1253                errno = EINVAL;
1254                return -1;
1255        }
1256        /* point to path beyond ':' */
1257        path++;
1258
1259        strncpy(host, chpt, len);
1260        host[len]=0;
1261
1262        if ( ! inet_pton(AF_INET, host, &psa->sin_addr) ) {
1263                errno = ENXIO;
1264                return -1;
1265        }
1266
1267        psa->sin_family = AF_INET;
1268        psa->sin_port   = 0;
1269        *pPath          = path;
1270        return 0;
1271}
1272
1273/* wrapper similar to nfscall.
1274 * However, since it is not used
1275 * very often, the simpler and less
1276 * efficient rpcUdpCallRp API is used.
1277 *
1278 * ARGS:        see 'nfscall()' above
1279 *
1280 * RETURNS:     RPC status
1281 */
1282static enum clnt_stat
1283mntcall(
1284        struct sockaddr_in      *psrvr,
1285        int                                     proc,
1286        xdrproc_t                       xargs,
1287        void *                          pargs,
1288        xdrproc_t                       xres,
1289        void *                          pres,
1290        u_long                          uid,
1291        u_long                          gid)
1292{
1293#ifdef MOUNT_V1_PORT
1294int                                     retry;
1295#endif
1296enum clnt_stat          stat = RPC_FAILED;
1297
1298#ifdef MOUNT_V1_PORT
1299        /* if the portmapper fails, retry a fixed port */
1300        for (retry = 1, psrvr->sin_port = 0, stat = RPC_FAILED;
1301                 retry >= 0 && stat;
1302                 stat && (psrvr->sin_port = htons(MOUNT_V1_PORT)), retry-- )
1303#endif
1304                stat  = rpcUdpCallRp(
1305                                                psrvr,
1306                                                MOUNTPROG,
1307                                                MOUNTVERS,
1308                                                proc,
1309                                                xargs,
1310                                                pargs,
1311                                                xres,
1312                                                pres,
1313                                                uid,
1314                                                gid,
1315                                                MNTCALL_TIMEOUT
1316                                );
1317        return stat;
1318}
1319
1320/*****************************************
1321        RTEMS File System Operations for NFS
1322 *****************************************/
1323
1324#if 0 /* for reference */
1325
1326struct rtems_filesystem_location_info_tt
1327{
1328   void                                 *node_access;
1329   rtems_filesystem_file_handlers_r     *handlers;
1330   rtems_filesystem_operations_table    *ops;
1331   rtems_filesystem_mount_table_entry_t *mt_entry;
1332};
1333
1334#endif
1335
1336/*
1337 * Evaluate a path letting 'pathloc' travel along.
1338 *
1339 * The important semantics of this operation are:
1340 *
1341 * If this routine returns -1, the caller assumes
1342 * pathloc to be _invalid_ and hence it will not
1343 * invoke rtems_filesystem_freenode() on it.
1344 *
1345 * OTOH, if evalpath returns 0,
1346 * rtems_filesystem_freenode() will eventually be
1347 * called which results in our freeing the associated
1348 * NfsNode attached to node_access.
1349 *
1350 * Therefore, this routine will _always_ allocate
1351 * a NfsNode and pass it out to *pathloc (provided
1352 * that the evaluation succeeds).
1353 *
1354 * However, if the evaluation finds that it has to
1355 * step across FS boundaries (mount point or a symlink
1356 * pointing outside), the NfsNode is destroyed
1357 * before passing control to the new FS' evalpath_h()
1358 *
1359 */
1360       
1361STATIC int nfs_do_evalpath(
1362        const char                        *pathname,      /* IN     */
1363        void                              *arg,
1364        rtems_filesystem_location_info_t  *pathloc,       /* IN/OUT */
1365        int                                                               forMake
1366)
1367{
1368char                    *del = 0, *part;
1369int                             e = 0;
1370NfsNode                 node   = pathloc->node_access;
1371char                    *p     = malloc(MAXPATHLEN+1);
1372Nfs                             nfs    = (Nfs)pathloc->mt_entry->fs_info;
1373RpcUdpServer    server = nfs->server;
1374unsigned long   flags;
1375#if DEBUG & DEBUG_COUNT_NODES
1376unsigned long   niu,siu;
1377#endif
1378
1379        if ( !p ) {
1380                e = ENOMEM;
1381                goto cleanup;
1382        }
1383        strcpy(p, pathname);
1384
1385        LOCK(nfsGlob.lock);
1386        node = nfsNodeClone(node);
1387        UNLOCK(nfsGlob.lock);
1388
1389        /* from here on, the NFS is protected from being unmounted
1390         * since the node refcount is > 1
1391         */
1392       
1393        /* clone the node */
1394        if ( !node ) {
1395                /* nodeClone sets errno */
1396                goto cleanup;
1397        }
1398
1399        pathloc->node_access = node;
1400
1401        /* Special case: the RTEMS filesystem code
1402         * may emit '..' on a regular file node to
1403         * find the parent directory :-(.
1404         * (eval.c: rtems_filesystem_evaluate_parent())
1405         * Try to catch this case here:
1406         */
1407        if ( NFDIR != SERP_ATTR(node).type && '.'==*p && '.'==*(p+1) ) {
1408                for ( part = p+2; '/'==*part; part++ )
1409                        /* skip trailing '/' */;
1410                if ( !*part ) {
1411                        /* this is it; back out dir and let them look up the dir itself... */
1412                        memcpy( &SERP_FILE(node),
1413                                        &node->args.dir,
1414                                        sizeof(node->args.dir));
1415                        *(p+1)=0;
1416                }
1417        }
1418
1419        for (part=p; part && *part; part=del) {
1420
1421                if ( NFLNK == SERP_ATTR(node).type ) {
1422                        /* follow midpath link */
1423                        char *b = malloc(NFS_MAXPATHLEN+1);
1424                        int       l;
1425
1426                        if (!b) {
1427                                e = ENOMEM;
1428                                goto cleanup;
1429                        }
1430                        if (nfs_readlink(pathloc, b, NFS_MAXPATHLEN+1)) {
1431                                free(b);
1432                                e = errno;
1433                                goto cleanup;
1434                        }
1435
1436                        /* prepend the link value to the rest of the path */
1437                        if ( (l=strlen(b)) + strlen(part) + 1 > NFS_MAXPATHLEN ) {
1438                                free(b);
1439                                e = EINVAL;
1440                                goto cleanup;
1441                        }
1442                        /* swap string buffers and reset delimiter */
1443                        b[l++] = DELIM;
1444                        strcpy(b+l,part);
1445                        part = b;
1446                        b    = p;
1447                        p    = del = part;
1448
1449                        free(b);
1450
1451                        /* back up the directory filehandle (only necessary
1452                         * if we don't back out to the root
1453                         */
1454                        if (! (DELIM == *part) ) {
1455                                memcpy( &SERP_FILE(node),
1456                                                &node->args.dir,
1457                                                sizeof(node->args.dir));
1458
1459                                if (updateAttr(node, 1 /* force */)) {
1460                                        e = errno;
1461                                        goto cleanup;
1462                                }
1463                        }
1464                }
1465
1466                /* find delimiter and eat /// sequences
1467                 * (only if we don't restart at the root)
1468                 */
1469                if ( DELIM != *part && (del = strchr(part, DELIM))) {
1470                        do {
1471                                *del++=0;
1472                        } while (DELIM==*del);
1473                }
1474
1475                /* refuse to backup over the root */
1476                if ( 0==strcmp(part,UPDIR)
1477                         && locAreEqual(pathloc, &rtems_filesystem_root) ) {
1478                        part++;
1479                }
1480
1481                /* cross mountpoint upwards */
1482                if ( (0==strcmp(part,UPDIR) && locIsRoot(pathloc)) /* cross mountpoint up */
1483                        || DELIM == *part                              /* link starts at root */
1484                        ) {
1485                        int                                                                     rval;
1486
1487#if DEBUG & DEBUG_EVALPATH
1488                        fprintf(stderr,
1489                                        "Crossing mountpoint upwards\n");
1490#endif
1491
1492                        if (DELIM == *part) {
1493                                *pathloc = rtems_filesystem_root;
1494                        } else {
1495                                *pathloc = pathloc->mt_entry->mt_point_node;
1496                                /* re-append the rest of the path */
1497                                if (del)
1498                                        while ( 0 == *--del )
1499                                                *del = DELIM;
1500                        }
1501
1502                        nfsNodeDestroy(node);
1503
1504#if DEBUG & DEBUG_EVALPATH
1505                        fprintf(stderr,
1506                                        "Re-evaluating '%s'\n",
1507                                        part);
1508#endif
1509
1510                        if (forMake)
1511                                rval = pathloc->ops->evalformake_h(part, pathloc, (const char**)arg);
1512                        else
1513                                rval = pathloc->ops->evalpath_h(part, (int)arg, pathloc);
1514
1515                        free(p);
1516                        return rval;
1517                }
1518
1519                /* lookup one element */
1520                SERP_ARGS(node).diroparg.name = part;
1521
1522                /* remember args / directory fh */
1523                memcpy( &node->args, &SERP_FILE(node), sizeof(node->args));
1524
1525                /* don't lookup the item we want to create */
1526                if ( forMake && (!del || !*del) )
1527                                break;
1528
1529#if DEBUG & DEBUG_EVALPATH
1530                fprintf(stderr,"Looking up '%s'\n",part);
1531#endif
1532
1533                if ( nfscall(server,
1534                                                 NFSPROC_LOOKUP,
1535                                                 (xdrproc_t)xdr_diropargs, &SERP_FILE(node),
1536                                                 (xdrproc_t)xdr_serporid,  &node->serporid) ||
1537                        NFS_OK != (errno=node->serporid.status) ) {
1538                        e = errno;
1539                        goto cleanup;
1540                }
1541                node->age = nowSeconds();
1542
1543#if DEBUG & DEBUG_EVALPATH
1544                if (NFLNK == SERP_ATTR(node).type && del) {
1545                        fprintf(stderr,
1546                                        "Following midpath link '%s'\n",
1547                                        part);
1548                }
1549#endif
1550
1551        }
1552
1553        if (forMake) {
1554                /* remember the name - do this _before_ copying
1555                 * the name to local storage; the caller expects a
1556                 * pointer into pathloc
1557                 */
1558                assert( node->args.name );
1559
1560                *(const char**)arg = pathname + (node->args.name - p);
1561
1562#if 0
1563                /* restore the directory node */
1564
1565                memcpy( &SERP_FILE(node),
1566                                &node->args.dir,
1567                                sizeof(node->args.dir));
1568
1569                if ( (nfscall(nfs->server,
1570                                                NFSPROC_GETATTR,
1571                                                (xdrproc_t)xdr_nfs_fh,   &SERP_FILE(node),
1572                                                (xdrproc_t)xdr_attrstat, &node->serporid) && !errno && (errno = EIO)) ||
1573                     (NFS_OK != (errno=node->serporid.status) ) ) {
1574                        goto cleanup;
1575                }
1576#endif
1577        }
1578
1579        if (locIsRoot(pathloc)) {
1580
1581                /* stupid filesystem code has no 'op' for comparing nodes
1582                 * but just compares the 'node_access' pointers.
1583                 * Luckily, this is only done for comparing the root nodes.
1584                 * Hence, we never give them a copy of the root but always
1585                 * the root itself.
1586                 */
1587                pathloc->node_access = pathloc->mt_entry->mt_fs_root.node_access;
1588                /* increment the 'in use' counter since we return one more
1589                 * reference to the root node
1590                 */
1591                rtems_interrupt_disable(flags);
1592                        nfs->nodesInUse++;
1593                rtems_interrupt_enable(flags);
1594                nfsNodeDestroy(node);
1595
1596
1597        } else {
1598                switch (SERP_ATTR(node).type) {
1599                        case NFDIR:     pathloc->handlers = &nfs_dir_file_handlers;  break;
1600                        case NFREG:     pathloc->handlers = &nfs_file_file_handlers; break;
1601                        case NFLNK: pathloc->handlers = &nfs_link_file_handlers; break;
1602                        default:        pathloc->handlers = &rtems_filesystem_null_handlers; break;
1603                }
1604                pathloc->node_access = node;
1605
1606                /* remember the name of this directory entry */
1607
1608                if (node->args.name) {
1609                        if (node->str) {
1610#if DEBUG & DEBUG_COUNT_NODES
1611                                rtems_interrupt_disable(flags);
1612                                        nfs->stringsInUse--;
1613                                rtems_interrupt_enable(flags);
1614#endif
1615                                free(node->str);
1616                        }
1617                        node->args.name = node->str = strdup(node->args.name);
1618                        if (!node->str) {
1619                                e = ENOMEM;
1620                                goto cleanup;
1621                        }
1622
1623#if DEBUG & DEBUG_COUNT_NODES
1624                        rtems_interrupt_disable(flags);
1625                                nfs->stringsInUse++;
1626                        rtems_interrupt_enable(flags);
1627#endif
1628                }
1629
1630        }
1631        node = 0;
1632
1633        e = 0;
1634
1635cleanup:
1636        free(p);
1637#if DEBUG & DEBUG_COUNT_NODES
1638        /* cache counters; nfs may be unmounted by other thread after the last
1639         * node is destroyed
1640         */
1641        niu = nfs->nodesInUse;
1642        siu = nfs->stringsInUse;
1643#endif
1644        if (node) {
1645                nfsNodeDestroy(node);
1646                pathloc->node_access = 0;
1647        }
1648#if DEBUG & DEBUG_COUNT_NODES
1649        fprintf(stderr,
1650                        "leaving evalpath, in use count is %i nodes, %i strings\n",
1651                        niu,siu);
1652#endif
1653        if (e) {
1654#if DEBUG & DEBUG_EVALPATH
1655                perror("Evalpath");
1656#endif
1657                rtems_set_errno_and_return_minus_one(e);
1658        } else {
1659                return 0;
1660        }
1661}
1662
1663/* MANDATORY; may set errno=ENOSYS and return -1 */
1664static int nfs_evalformake(
1665        const char                       *path,       /* IN */
1666        rtems_filesystem_location_info_t *pathloc,    /* IN/OUT */
1667        const char                      **pname       /* OUT    */
1668)
1669{
1670        return nfs_do_evalpath(path, (void*)pname, pathloc, 1 /*forMake*/);
1671}
1672
1673static int nfs_evalpath(
1674        const char                                               *path,           /* IN */
1675        int                                                              flags,           /* IN */
1676        rtems_filesystem_location_info_t *pathloc    /* IN/OUT */
1677)
1678{
1679        return nfs_do_evalpath(path, (void*)flags, pathloc, 0 /*not forMake*/);
1680}
1681
1682
1683/* create a hard link */
1684
1685static int nfs_link(
1686        rtems_filesystem_location_info_t  *to_loc,      /* IN */
1687        rtems_filesystem_location_info_t  *parent_loc,  /* IN */
1688        const char                        *name         /* IN */
1689)
1690{
1691NfsNode pNode;
1692nfsstat status;
1693NfsNode tNode = to_loc->node_access;
1694
1695#if DEBUG & DEBUG_SYSCALLS
1696        fprintf(stderr,"Creating link '%s'\n",name);
1697#endif
1698
1699        if ( !locIsNfs(parent_loc) ) {
1700                errno = EXDEV;
1701                return -1;
1702        }
1703
1704        pNode = parent_loc->node_access;
1705        if ( tNode->nfs != pNode->nfs ) {
1706                errno = EXDEV;
1707                return -1;
1708        }
1709        memcpy(&SERP_ARGS(tNode).linkarg.to.dir,
1710                   &SERP_FILE(pNode),
1711                   sizeof(SERP_FILE(pNode)));
1712
1713        SERP_ARGS(tNode).linkarg.to.name = (filename)name;
1714
1715        if ( nfscall(tNode->nfs->server,
1716                                          NFSPROC_LINK,
1717                                          (xdrproc_t)xdr_linkargs,      &SERP_FILE(tNode),
1718                                          (xdrproc_t)xdr_nfsstat,       &status)
1719             || (NFS_OK != (errno = status))
1720           ) {
1721#if DEBUG & DEBUG_SYSCALLS
1722                perror("nfs_link");
1723#endif
1724                return -1;
1725        }
1726
1727        return 0;
1728
1729}
1730
1731static int nfs_do_unlink(
1732        rtems_filesystem_location_info_t  *loc,       /* IN */
1733        int                                                               proc
1734)
1735{
1736nfsstat                 status;
1737NfsNode                 node  = loc->node_access;
1738Nfs                             nfs   = node->nfs;
1739#if DEBUG & DEBUG_SYSCALLS
1740char                    *name = NFSPROC_REMOVE == proc ?
1741                                                        "nfs_unlink" : "nfs_rmdir";
1742#endif
1743
1744        /* The FS generics have determined that pathloc is _not_
1745         * a directory. Hence we may assume that the parent
1746         * is in our NFS.
1747         */
1748
1749#if DEBUG & DEBUG_SYSCALLS
1750        assert( node->args.name == node->str && node->str );
1751
1752        fprintf(stderr,"%s '%s'\n", name, node->args.name);
1753#endif
1754
1755        if ( nfscall(nfs->server,
1756                                 proc,
1757                                 (xdrproc_t)xdr_diropargs,      &node->args,
1758                                 (xdrproc_t)xdr_nfsstat,        &status)
1759             || (NFS_OK != (errno = status))
1760            ) {
1761#if DEBUG & DEBUG_SYSCALLS
1762                perror(name);
1763#endif
1764                return -1;
1765        }
1766
1767        return 0;
1768}
1769
1770static int nfs_unlink(
1771        rtems_filesystem_location_info_t  *loc       /* IN */
1772)
1773{
1774        return nfs_do_unlink(loc, NFSPROC_REMOVE);
1775}
1776
1777static int nfs_chown(
1778        rtems_filesystem_location_info_t  *pathloc,       /* IN */
1779        uid_t                              owner,         /* IN */
1780        gid_t                              group          /* IN */
1781)
1782{
1783sattr   arg;
1784
1785        arg.uid = owner;
1786        arg.gid = group;
1787
1788        return nfs_sattr(pathloc->node_access, &arg, SATTR_UID | SATTR_GID);
1789       
1790}
1791
1792/* Cleanup the FS private info attached to pathloc->node_access */
1793static int nfs_freenode(
1794        rtems_filesystem_location_info_t      *pathloc       /* IN */
1795)
1796{
1797Nfs     nfs    = ((NfsNode)pathloc->node_access)->nfs;
1798
1799#if DEBUG & DEBUG_COUNT_NODES
1800        /* print counts at entry where they are > 0 so 'nfs' is safe from being destroyed
1801         * and there's no race condition
1802         */
1803        fprintf(stderr,
1804                        "entering freenode, in use count is %i nodes, %i strings\n",
1805                        nfs->nodesInUse,
1806                        nfs->stringsInUse);
1807#endif
1808
1809        /* never destroy the root node; it is released by the unmount
1810         * code
1811         */
1812        if (locIsRoot(pathloc)) {
1813                unsigned long flags;
1814                /* just adjust the references to the root node but
1815                 * don't really release it
1816                 */
1817                rtems_interrupt_disable(flags);
1818                        nfs->nodesInUse--;
1819                rtems_interrupt_enable(flags);
1820        } else {
1821                nfsNodeDestroy(pathloc->node_access);
1822                pathloc->node_access = 0;
1823        }
1824        return 0;
1825}
1826
1827/* NOTE/TODO: mounting on top of NFS is not currently supported
1828 *
1829 * Challenge: stateless protocol. It would be possible to
1830 * delete mount points on the server. We would need some sort
1831 * of a 'garbage collector' looking for dead/unreachable
1832 * mount points and unmounting them.
1833 * Also, the path evaluation routine would have to check
1834 * for crossing mount points. Crossing over from one NFS
1835 * into another NFS could probably handled iteratively
1836 * rather than by recursion.
1837 */
1838
1839#ifdef DECLARE_BODY
1840/* This routine is called when they try to mount something
1841 * on top of THIS filesystem, i.e. if one of our directories
1842 * is used as a mount point
1843 */
1844static int nfs_mount(
1845        rtems_filesystem_mount_table_entry_t *mt_entry     /* in */
1846)DECLARE_BODY
1847#else
1848#define nfs_mount 0
1849#endif
1850
1851#ifdef DECLARE_BODY
1852/* This op is called when they try to unmount a FS
1853 * from a mountpoint managed by THIS FS.
1854 */
1855static int nfs_unmount(
1856        rtems_filesystem_mount_table_entry_t *mt_entry     /* in */
1857)DECLARE_BODY
1858#else
1859#define nfs_unmount 0
1860#endif
1861
1862#if 0
1863
1864/* for reference (libio.h) */
1865
1866struct rtems_filesystem_mount_table_entry_tt {
1867  Chain_Node                             Node;
1868  rtems_filesystem_location_info_t       mt_point_node;
1869  rtems_filesystem_location_info_t       mt_fs_root;
1870  int                                    options;
1871  void                                  *fs_info;
1872
1873  rtems_filesystem_limits_and_options_t  pathconf_limits_and_options;
1874
1875  /*
1876   *  When someone adds a mounted filesystem on a real device,
1877   *  this will need to be used.
1878   *
1879   *  The best option long term for this is probably an open file descriptor.
1880   */
1881  char                                  *dev;
1882};
1883#endif
1884
1885
1886/* This op is called as the last step of mounting this FS */
1887STATIC int nfs_fsmount_me(
1888        rtems_filesystem_mount_table_entry_t *mt_entry
1889)
1890{
1891char                            *host;
1892struct sockaddr_in      saddr;
1893enum clnt_stat          stat;
1894fhstatus                        fhstat;
1895u_long                          uid,gid;
1896#ifdef NFS_V2_PORT
1897int                                     retry;
1898#endif
1899Nfs                                     nfs       = 0;
1900NfsNode                         rootNode  = 0;
1901RpcUdpServer            nfsServer = 0;
1902int                                     e         = -1;
1903char                            *path     = mt_entry->dev;
1904
1905
1906        if ( buildIpAddr(&uid, &gid, &host, &saddr, &path) )
1907                return -1;
1908
1909
1910#ifdef NFS_V2_PORT
1911        /* if the portmapper fails, retry a fixed port */
1912        for (retry = 1, saddr.sin_port = 0, stat = RPC_FAILED;
1913                 retry >= 0 && stat;
1914                 stat && (saddr.sin_port = htons(NFS_V2_PORT)), retry-- )
1915#endif
1916                stat = rpcUdpServerCreate(
1917                                        &saddr,
1918                                        NFS_PROGRAM,
1919                                        NFS_VERSION_2,
1920                                        uid,
1921                                        gid,
1922                                        &nfsServer
1923                                        );
1924
1925        if ( RPC_SUCCESS != stat ) {
1926                fprintf(stderr,
1927                                "Unable to contact NFS server - invalid port? (%s)\n",
1928                                clnt_sperrno(stat));
1929                e = EPROTONOSUPPORT;
1930                goto cleanup;
1931        }
1932
1933
1934        /* first, try to ping the NFS server by
1935         * calling the NULL proc.
1936         */
1937        if ( nfscall(nfsServer,
1938                                         NFSPROC_NULL,
1939                                         (xdrproc_t)xdr_void, 0,
1940                                         (xdrproc_t)xdr_void, 0) ) {
1941
1942                fputs("NFS Ping ",stderr);
1943                fwrite(host, 1, path-host-1, stderr);
1944                fprintf(stderr," failed: %s\n", strerror(errno));
1945
1946                e = errno ? errno : EIO;
1947                goto cleanup;
1948        }
1949
1950        /* that seemed to work - we now try the
1951         * actual mount
1952         */
1953
1954        /* reuse server address but let the mntcall()
1955         * search for the mountd's port
1956         */
1957        saddr.sin_port = 0;
1958
1959        stat = mntcall( &saddr,
1960                                        MOUNTPROC_MNT,
1961                                        (xdrproc_t)xdr_dirpath,
1962                                        &path,
1963                                        (xdrproc_t)xdr_fhstatus,
1964                                        &fhstat,
1965                                        uid,
1966                                        gid );
1967
1968        if (stat) {
1969                fprintf(stderr,"MOUNT -- %s\n",clnt_sperrno(stat));
1970                if ( e<=0 )
1971                        e = EIO;
1972                goto cleanup;
1973        } else if (NFS_OK != (e=fhstat.fhs_status)) {
1974                fprintf(stderr,"MOUNT: %s\n",strerror(e));
1975                goto cleanup;
1976        }
1977
1978        assert( nfs = nfsCreate(nfsServer) );
1979        nfsServer = 0;
1980
1981        nfs->uid  = uid;
1982        nfs->gid  = gid;
1983
1984        /* that seemed to work - we now create the root node
1985         * and we also must obtain the root node attributes
1986         */
1987        assert( rootNode = nfsNodeCreate(nfs, &fhstat.fhstatus_u.fhs_fhandle) );
1988
1989        if ( updateAttr(rootNode, 1 /* force */) ) {
1990                e = errno;
1991                goto cleanup;
1992        }
1993
1994        /* looks good so far */
1995
1996        mt_entry->mt_fs_root.node_access = rootNode;
1997
1998        rootNode = 0;
1999
2000        mt_entry->mt_fs_root.ops                 = &nfs_fs_ops;
2001        mt_entry->mt_fs_root.handlers    = &nfs_dir_file_handlers;
2002        mt_entry->pathconf_limits_and_options = nfs_limits_and_options;
2003
2004        LOCK(nfsGlob.llock);
2005                nfsGlob.num_mounted_fs++;
2006                /* allocate a new ID for this FS */
2007                nfs->id = nfsGlob.fs_ids++;
2008        UNLOCK(nfsGlob.llock);
2009
2010        mt_entry->fs_info                                = nfs;
2011        nfs->mt_entry                                    = mt_entry;
2012        nfs = 0;
2013
2014        e = 0;
2015
2016cleanup:
2017        if (nfs)
2018                nfsDestroy(nfs);
2019        if (nfsServer)
2020                rpcUdpServerDestroy(nfsServer);
2021        if (rootNode)
2022                nfsNodeDestroy(rootNode);
2023        if (e)
2024                rtems_set_errno_and_return_minus_one(e);
2025        else
2026                return 0;
2027}
2028
2029/* This op is called when they try to unmount THIS fs */
2030STATIC int nfs_fsunmount_me(
2031        rtems_filesystem_mount_table_entry_t *mt_entry    /* in */
2032)
2033{
2034enum clnt_stat          stat;
2035struct sockaddr_in      saddr;
2036char                            *path = mt_entry->dev;
2037int                                     nodesInUse;
2038u_long                          uid,gid;
2039
2040LOCK(nfsGlob.llock);
2041        nodesInUse = ((Nfs)mt_entry->fs_info)->nodesInUse;
2042
2043        if (nodesInUse > 1 /* one ref to the root node used by us */) {
2044                UNLOCK(nfsGlob.llock);
2045                fprintf(stderr,
2046                                "Refuse to unmount; there are still %i nodes in use (1 used by us)\n",
2047                                nodesInUse);
2048                rtems_set_errno_and_return_minus_one(EBUSY);
2049        }
2050
2051        assert( 0 == buildIpAddr(&uid, &gid, 0, &saddr, &path) );
2052       
2053        stat = mntcall( &saddr,
2054                                        MOUNTPROC_UMNT,
2055                                        (xdrproc_t)xdr_dirpath, &path,
2056                                        (xdrproc_t)xdr_void,     0,
2057                                    uid,
2058                                    gid
2059                                  );
2060
2061        if (stat) {
2062                UNLOCK(nfsGlob.llock);
2063                fprintf(stderr,"NFS UMOUNT -- %s\n", clnt_sperrno(stat));
2064                errno = EIO;
2065                return -1;
2066        }
2067
2068        nfsNodeDestroy(mt_entry->mt_fs_root.node_access);
2069        mt_entry->mt_fs_root.node_access = 0;
2070       
2071        nfsDestroy(mt_entry->fs_info);
2072        mt_entry->fs_info = 0;
2073
2074        nfsGlob.num_mounted_fs--;
2075UNLOCK(nfsGlob.llock);
2076
2077        return 0;
2078}
2079
2080/* OPTIONAL; may be NULL - BUT: CAUTION; mount() doesn't check
2081 * for this handler to be present - a fs bug
2082 * //NOTE: (10/25/2002) patch submitted and probably applied
2083 */
2084static rtems_filesystem_node_types_t nfs_node_type(
2085        rtems_filesystem_location_info_t    *pathloc      /* in */
2086)
2087{
2088NfsNode node = pathloc->node_access;
2089
2090        if (updateAttr(node, 0 /* only if old */))
2091                return -1;
2092
2093        switch( SERP_ATTR(node).type ) {
2094                default:
2095                        /* rtems has no value for 'unknown';
2096                         */
2097                case NFNON:
2098                case NFSOCK:
2099                case NFBAD:
2100                case NFFIFO:
2101                                break;
2102
2103
2104                case NFREG: return RTEMS_FILESYSTEM_MEMORY_FILE;
2105                case NFDIR:     return RTEMS_FILESYSTEM_DIRECTORY;
2106
2107                case NFBLK:
2108                case NFCHR:     return RTEMS_FILESYSTEM_DEVICE;
2109
2110                case NFLNK: return RTEMS_FILESYSTEM_SYM_LINK;
2111        }
2112        return -1;
2113}
2114
2115static int nfs_mknod(
2116        const char                        *path,       /* IN */
2117        mode_t                             mode,       /* IN */
2118        dev_t                              dev,        /* IN */
2119        rtems_filesystem_location_info_t  *pathloc     /* IN/OUT */
2120)
2121{
2122rtems_clock_time_value  now;
2123diropres                                res;
2124NfsNode                                 node = pathloc->node_access;
2125mode_t                                  type = S_IFMT & mode;
2126
2127        if (type != S_IFDIR && type != S_IFREG)
2128                rtems_set_errno_and_return_minus_one(ENOTSUP);
2129
2130#if DEBUG & DEBUG_SYSCALLS
2131        fprintf(stderr,"nfs_mknod: creating %s\n", path);
2132#endif
2133
2134        rtems_clock_get(RTEMS_CLOCK_GET_TIME_VALUE, &now);
2135
2136        SERP_ARGS(node).createarg.name                  = (filename)path;
2137        SERP_ARGS(node).createarg.attributes.mode       = mode;
2138        /* TODO: either use our uid or use the Nfs credentials */
2139        SERP_ARGS(node).createarg.attributes.uid        = 0;
2140        SERP_ARGS(node).createarg.attributes.gid        = 0;
2141        SERP_ARGS(node).createarg.attributes.size       = 0;
2142        SERP_ARGS(node).createarg.attributes.atime.seconds      = now.seconds;
2143        SERP_ARGS(node).createarg.attributes.atime.useconds     = now.microseconds;
2144        SERP_ARGS(node).createarg.attributes.mtime.seconds      = now.seconds;
2145        SERP_ARGS(node).createarg.attributes.mtime.useconds     = now.microseconds;
2146
2147        if ( nfscall( node->nfs->server,
2148                                                NFSPROC_CREATE,
2149                                                (xdrproc_t)xdr_createargs,      &SERP_FILE(node),
2150                                                (xdrproc_t)xdr_diropres,        &res)
2151                || (NFS_OK != (errno = res.status)) ) {
2152#if DEBUG & DEBUG_SYSCALLS
2153                perror("nfs_mknod");
2154#endif
2155                return -1;
2156        }
2157
2158        return 0;
2159}
2160
2161static int nfs_utime(
2162        rtems_filesystem_location_info_t  *pathloc,       /* IN */
2163        time_t                             actime,        /* IN */
2164        time_t                             modtime        /* IN */
2165)
2166{
2167sattr   arg;
2168
2169        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2170        arg.atime.seconds  = actime;
2171        arg.atime.useconds = 0;
2172        arg.mtime.seconds  = modtime;
2173        arg.mtime.useconds = 0;
2174
2175        return nfs_sattr(pathloc->node_access, &arg, SATTR_ATIME | SATTR_MTIME);
2176}
2177
2178static int nfs_symlink(
2179        rtems_filesystem_location_info_t  *loc,         /* IN */
2180        const char                        *link_name,   /* IN */
2181        const char                        *node_name
2182)
2183{
2184rtems_clock_time_value  now;
2185nfsstat                                 status;
2186NfsNode                                 node = loc->node_access;
2187
2188
2189#if DEBUG & DEBUG_SYSCALLS
2190        fprintf(stderr,"nfs_symlink: creating %s -> %s\n", link_name, node_name);
2191#endif
2192
2193        rtems_clock_get(RTEMS_CLOCK_GET_TIME_VALUE, &now);
2194
2195        SERP_ARGS(node).symlinkarg.name                 = (filename)link_name;
2196        SERP_ARGS(node).symlinkarg.to                           = (nfspath) node_name;
2197
2198        SERP_ARGS(node).symlinkarg.attributes.mode      = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
2199        /* TODO */
2200        SERP_ARGS(node).symlinkarg.attributes.uid       = 0;
2201        SERP_ARGS(node).symlinkarg.attributes.gid       = 0;
2202        SERP_ARGS(node).symlinkarg.attributes.size      = 0;
2203        SERP_ARGS(node).symlinkarg.attributes.atime.seconds      = now.seconds;
2204        SERP_ARGS(node).symlinkarg.attributes.atime.useconds = now.microseconds;
2205        SERP_ARGS(node).symlinkarg.attributes.mtime.seconds      = now.seconds;
2206        SERP_ARGS(node).symlinkarg.attributes.mtime.useconds = now.microseconds;
2207
2208        if ( nfscall( node->nfs->server,
2209                                                NFSPROC_SYMLINK,
2210                                                (xdrproc_t)xdr_symlinkargs,     &SERP_FILE(node),
2211                                                (xdrproc_t)xdr_nfsstat,         &status)
2212                || (NFS_OK != (errno = status)) ) {
2213#if DEBUG & DEBUG_SYSCALLS
2214                perror("nfs_symlink");
2215#endif
2216                return -1;
2217        }
2218
2219        return 0;
2220}
2221
2222static int nfs_do_readlink(
2223        rtems_filesystem_location_info_t  *loc,         /* IN  */       
2224        strbuf                                                    *psbuf                /* IN/OUT */
2225)
2226{
2227NfsNode                         node = loc->node_access;
2228Nfs                                     nfs  = node->nfs;
2229readlinkres_strbuf      rr;
2230int                                     wasAlloced;
2231int                                     rval;
2232
2233        rr.strbuf  = *psbuf;
2234
2235        wasAlloced = (0 == psbuf->buf);
2236
2237        if ( (rval = nfscall(nfs->server,
2238                                                        NFSPROC_READLINK,
2239                                                        (xdrproc_t)xdr_nfs_fh,                  &SERP_FILE(node),
2240                                                        (xdrproc_t)xdr_readlinkres_strbuf, &rr)) ) {
2241                if (wasAlloced)
2242                        xdr_free( (xdrproc_t)xdr_strbuf, (caddr_t)&rr.strbuf );
2243        }
2244
2245
2246        if (NFS_OK != rr.status) {
2247                if (wasAlloced)
2248                        xdr_free( (xdrproc_t)xdr_strbuf, (caddr_t)&rr.strbuf );
2249                rtems_set_errno_and_return_minus_one(rr.status);
2250        }
2251
2252        *psbuf = rr.strbuf;
2253
2254        return 0;
2255}
2256
2257static int nfs_readlink(
2258        rtems_filesystem_location_info_t  *loc,         /* IN  */       
2259        char                                                      *buf,                 /* OUT */
2260        size_t                                                    len
2261)
2262{
2263strbuf sbuf;
2264        sbuf.buf = buf;
2265        sbuf.max = len;
2266
2267        return nfs_do_readlink(loc, &sbuf);
2268}
2269
2270/* The semantics of this routine are:
2271 *
2272 * The caller submits a valid pathloc, i.e. it has
2273 * an NfsNode attached to node_access.
2274 * On return, pathloc points to the target node which
2275 * may or may not be an NFS node.
2276 * Hence, the original NFS node is released in either
2277 * case:
2278 *   - link evaluation fails; pathloc points to no valid node
2279 *   - link evaluation success; pathloc points to a new valid
2280 *     node. If it's an NFS node, a new NfsNode will be attached
2281 *     to node_access...
2282 */
2283
2284#define LINKVAL_BUFLEN                          (MAXPATHLEN+1)
2285#define RVAL_ERR_BUT_DONT_FREENODE      (-1)
2286#define RVAL_ERR_AND_DO_FREENODE        ( 1)
2287#define RVAL_OK                                         ( 0)
2288
2289static int nfs_eval_link(
2290        rtems_filesystem_location_info_t *pathloc,     /* IN/OUT */
2291        int                              flags         /* IN     */
2292)
2293{
2294rtems_filesystem_node_types_t   type;
2295char                                                    *buf = malloc(LINKVAL_BUFLEN);
2296int                                                             rval = RVAL_ERR_AND_DO_FREENODE;
2297
2298        if (!buf) {
2299                errno = ENOMEM;
2300                goto cleanup;
2301        }
2302
2303        /* in this loop, we must not use NFS specific ops as we might
2304         * step out of our FS during the process...
2305         * This algorithm should actually be performed by the
2306         * generic's evaluate_path routine :-(
2307         *
2308         * Unfortunately, there is no way of finding the
2309         * directory node who contains 'pathloc', however :-(
2310         */
2311        do {
2312                /* assume the generics have verified 'pathloc' to be
2313                 * a link...
2314                 */
2315                if ( !pathloc->ops->readlink_h ) {
2316                        errno = ENOTSUP;
2317                        goto cleanup;
2318                }
2319
2320                if ( pathloc->ops->readlink_h(pathloc, buf, LINKVAL_BUFLEN) ) {
2321                        goto cleanup;
2322                }
2323
2324#if DEBUG & DEBUG_EVALPATH
2325                fprintf(stderr, "link value is '%s'\n", buf);
2326#endif
2327
2328                /* is the link value an absolute path ? */
2329                if ( DELIM != *buf ) {
2330                        /* NO; a relative path */
2331
2332                        /* we must backup to the link's directory - we
2333                         * know only how to do that for NFS, however.
2334                         * In this special case, we can avoid recursion.
2335                         * Otherwise (i.e. if the link is on another FS),
2336                         * we must step into its eval_link_h().
2337                         */
2338                        if (locIsNfs(pathloc)) {
2339                                NfsNode node = pathloc->node_access;
2340                                int             err;
2341
2342                                memcpy( &SERP_FILE(node),
2343                                                &node->args.dir,
2344                                                sizeof(node->args.dir) );
2345
2346                                if (updateAttr(node, 1 /* force */))
2347                                        goto cleanup;
2348
2349                                if (SERP_ATTR(node).type != NFDIR) {
2350                                        errno = ENOTDIR;
2351                                        goto cleanup;
2352                                }
2353
2354                                pathloc->handlers = &nfs_dir_file_handlers;
2355
2356                                err = nfs_evalpath(buf, flags, pathloc);
2357
2358                                /* according to its semantics,
2359                                 * nfs_evalpath cloned the node attached
2360                                 * to pathloc. Hence we have to
2361                                 * release the old one (referring to
2362                                 * the link; the new clone has been
2363                                 * updated and refers to the link _value_).
2364                                 */
2365                                nfsNodeDestroy(node);
2366
2367                                if (err) {
2368                                        /* nfs_evalpath has set errno;
2369                                         * pathloc->node_access has no
2370                                         * valid node attached in this case
2371                                         */
2372                                        rval = RVAL_ERR_BUT_DONT_FREENODE;
2373                                        goto cleanup;
2374                                }
2375
2376                        } else {
2377                                if ( ! pathloc->ops->eval_link_h ) {
2378                                        errno = ENOTSUP;
2379                                        goto cleanup;
2380                                }
2381                                if (!pathloc->ops->eval_link_h(pathloc, flags)) {
2382                                        /* FS is responsible for freeing its pathloc->node_access
2383                                         * if necessary
2384                                         */
2385                                        rval = RVAL_ERR_BUT_DONT_FREENODE;
2386                                        goto cleanup;
2387                                }
2388                        }
2389                } else {
2390                        /* link points to an absolute path '/xxx' */
2391                               
2392                        /* release this node; filesystem_evaluate_path() will
2393                         * lookup a new one.
2394                         */
2395                        rtems_filesystem_freenode(pathloc);
2396
2397                        if (rtems_filesystem_evaluate_path(buf, flags, pathloc, 1)) {
2398                                goto cleanup;
2399                        }
2400                }
2401
2402                if ( !pathloc->ops->node_type_h ) {
2403                        errno = ENOTSUP;
2404                        goto cleanup;
2405                }
2406
2407                type = pathloc->ops->node_type_h(pathloc);
2408
2409
2410                /* I dont know what to do about hard links */
2411        } while ( RTEMS_FILESYSTEM_SYM_LINK == type );
2412
2413        rval = RVAL_OK;
2414
2415cleanup:
2416
2417        free(buf);
2418
2419        if (RVAL_ERR_AND_DO_FREENODE == rval) {
2420                rtems_filesystem_freenode(pathloc);
2421                return -1;
2422        }
2423
2424        return rval;
2425}
2426
2427
2428struct _rtems_filesystem_operations_table nfs_fs_ops = {
2429                nfs_evalpath,           /* MANDATORY */
2430                nfs_evalformake,        /* MANDATORY; may set errno=ENOSYS and return -1 */
2431                nfs_link,                       /* OPTIONAL; may be NULL */
2432                nfs_unlink,                     /* OPTIONAL; may be NULL */
2433                nfs_node_type,          /* OPTIONAL; may be NULL; BUG in mount - no test!! */
2434                nfs_mknod,                      /* OPTIONAL; may be NULL */
2435                nfs_chown,                      /* OPTIONAL; may be NULL */
2436                nfs_freenode,           /* OPTIONAL; may be NULL; (release node_access) */
2437                nfs_mount,                      /* OPTIONAL; may be NULL */
2438                nfs_fsmount_me,         /* OPTIONAL; may be NULL -- but this makes NO SENSE */
2439                nfs_unmount,            /* OPTIONAL; may be NULL */
2440                nfs_fsunmount_me,       /* OPTIONAL; may be NULL */
2441                nfs_utime,                      /* OPTIONAL; may be NULL */
2442                nfs_eval_link,          /* OPTIONAL; may be NULL */
2443                nfs_symlink,            /* OPTIONAL; may be NULL */
2444                nfs_readlink,           /* OPTIONAL; may be NULL */
2445};
2446
2447/*****************************************
2448        File Handlers
2449
2450        NOTE: the FS generics expect a FS'
2451              evalpath_h() to switch the
2452                  pathloc->handlers according
2453                  to the pathloc/node's file
2454                  type.
2455                  We currently have 'file' and
2456                  'directory' handlers and very
2457                  few 'symlink' handlers.
2458
2459                  The handlers for each type are
2460                  implemented or #defined ZERO
2461                  in a 'nfs_file_xxx',
2462                  'nfs_dir_xxx', 'nfs_link_xxx'
2463                  sequence below this point.
2464
2465                  In some cases, a common handler,
2466                  can be used for all file types.
2467                  It is then simply called
2468                  'nfs_xxx'.
2469 *****************************************/
2470
2471
2472#if 0
2473/* from rtems/libio.h for convenience */
2474struct rtems_libio_tt {
2475                rtems_driver_name_t              *driver;
2476                off_t                             size;      /* size of file */
2477                off_t                             offset;    /* current offset into file */
2478                uint32_t                          flags;
2479                rtems_filesystem_location_info_t  pathinfo;
2480                Objects_Id                        sem;
2481                uint32_t                          data0;     /* private to "driver" */
2482                void                             *data1;     /* ... */
2483                void                             *file_info; /* used by file handlers */
2484                rtems_filesystem_file_handlers_r *handlers;  /* type specific handlers */
2485};
2486#endif
2487
2488/* stateless NFS protocol makes this trivial */
2489static int nfs_file_open(
2490        rtems_libio_t *iop,
2491        const char    *pathname,
2492        uint32_t      flag,
2493        uint32_t      mode
2494)
2495{
2496        iop->file_info = 0;
2497        return 0;
2498}
2499
2500/* reading directories is not stateless; we must
2501 * remember the last 'read' position, i.e.
2502 * the server 'cookie'. We do manage this information
2503 * attached to the iop->file_info.
2504 */
2505static int nfs_dir_open(
2506        rtems_libio_t *iop,
2507        const char    *pathname,
2508        uint32_t      flag,
2509        uint32_t      mode
2510)
2511{
2512NfsNode         node = iop->pathinfo.node_access;
2513DirInfo         di;
2514
2515        /* create a readdirargs object and copy the file handle;
2516         * attach to the file_info.
2517         */
2518
2519        di = (DirInfo) malloc(sizeof(*di));
2520        iop->file_info = di;
2521
2522        if ( !di  ) {
2523                errno = ENOMEM;
2524                return -1;
2525        }
2526
2527        memcpy( &di->readdirargs.dir,
2528                        &SERP_FILE(node),
2529                        sizeof(di->readdirargs.dir) );
2530
2531        /* rewind cookie */
2532        memset( &di->readdirargs.cookie,
2533                0,
2534                sizeof(di->readdirargs.cookie) );
2535
2536        di->eofreached = FALSE;
2537
2538        return 0;
2539}
2540
2541#define nfs_link_open 0
2542
2543static int nfs_file_close(
2544        rtems_libio_t *iop
2545)
2546{
2547        return 0;
2548}
2549
2550static int nfs_dir_close(
2551        rtems_libio_t *iop
2552)
2553{
2554        free(iop->file_info);
2555        iop->file_info = 0;
2556        return 0;
2557}
2558
2559#define nfs_link_close 0
2560
2561static ssize_t nfs_file_read(
2562        rtems_libio_t *iop,
2563        void          *buffer,
2564        size_t        count
2565)
2566{
2567readres rr;
2568NfsNode node = iop->pathinfo.node_access;
2569Nfs             nfs  = node->nfs;
2570
2571        if (count > NFS_MAXDATA)
2572                count = NFS_MAXDATA;
2573
2574        SERP_ARGS(node).readarg.offset          = iop->offset;
2575        SERP_ARGS(node).readarg.count           = count;
2576        SERP_ARGS(node).readarg.totalcount      = 0xdeadbeef;
2577
2578        rr.readres_u.reply.data.data_val        = buffer;
2579
2580        if ( nfscall(   nfs->server,
2581                                                NFSPROC_READ,
2582                                                (xdrproc_t)xdr_readargs,        &SERP_FILE(node),
2583                                                (xdrproc_t)xdr_readres, &rr) ) {
2584                return -1;
2585        }
2586
2587
2588        if (NFS_OK != rr.status) {
2589                rtems_set_errno_and_return_minus_one(rr.status);
2590        }
2591
2592#if DEBUG & DEBUG_SYSCALLS
2593        fprintf(stderr,
2594                        "Read %i (asked for %i) bytes from offset %i to 0x%08x\n",
2595                        rr.readres_u.reply.data.data_len,
2596                        count,
2597                        iop->offset,
2598                        rr.readres_u.reply.data.data_val);
2599#endif
2600
2601
2602        return rr.readres_u.reply.data.data_len;
2603}
2604
2605/* this is called by readdir() / getdents() */
2606static ssize_t nfs_dir_read(
2607        rtems_libio_t *iop,
2608        void          *buffer,
2609        size_t        count
2610)
2611{
2612DirInfo                 di     = iop->file_info;
2613RpcUdpServer    server = ((Nfs)iop->pathinfo.mt_entry->fs_info)->server;
2614
2615        if ( di->eofreached )
2616                return 0;
2617
2618        di->ptr = di->buf = buffer;
2619
2620        /* align + round down the buffer */
2621        count &= ~ (DIRENT_HEADER_SIZE - 1);
2622        di->len = count;
2623
2624#if 0
2625        /* now estimate the number of entries we should ask for */
2626        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2627
2628        /* estimate the encoded size that might take up */
2629        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2630#else
2631        /* integer arithmetics are better done the other way round */
2632        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2633        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2634#endif
2635
2636        if (count > NFS_MAXDATA)
2637                count = NFS_MAXDATA;
2638
2639        di->readdirargs.count = count;
2640
2641#if DEBUG & DEBUG_READDIR
2642        fprintf(stderr,
2643                        "Readdir: asking for %i XDR bytes, buffer is %i\n",
2644                        count, di->len);
2645#endif
2646
2647        if ( nfscall(
2648                                        server,
2649                                        NFSPROC_READDIR,
2650                                        (xdrproc_t)xdr_readdirargs, &di->readdirargs,
2651                                        (xdrproc_t)xdr_dir_info,    di) ) {
2652                return -1;
2653        }
2654
2655
2656        if (NFS_OK != di->status) {
2657                rtems_set_errno_and_return_minus_one(di->status);
2658        }
2659
2660        return (char*)di->ptr - (char*)buffer;
2661}
2662
2663#define nfs_link_read 0
2664
2665static ssize_t nfs_file_write(
2666        rtems_libio_t *iop,
2667        const void    *buffer,
2668        size_t        count
2669)
2670{
2671NfsNode         node = iop->pathinfo.node_access;
2672Nfs                     nfs  = node->nfs;
2673int                     e;
2674
2675        if (count > NFS_MAXDATA)
2676                count = NFS_MAXDATA;
2677
2678
2679        SERP_ARGS(node).writearg.beginoffset   = 0xdeadbeef;
2680        if ( LIBIO_FLAGS_APPEND & iop->flags ) {
2681                if ( updateAttr(node, 0) ) {
2682                        return -1;
2683                }
2684                SERP_ARGS(node).writearg.offset            = SERP_ATTR(node).size;
2685        } else {
2686                SERP_ARGS(node).writearg.offset            = iop->offset;
2687        }
2688        SERP_ARGS(node).writearg.totalcount        = 0xdeadbeef;
2689        SERP_ARGS(node).writearg.data.data_len = count;
2690        SERP_ARGS(node).writearg.data.data_val = (void*)buffer;
2691
2692        /* write XDR buffer size will be chosen by nfscall based
2693         * on the PROC specifier
2694         */
2695
2696        if ( nfscall(   nfs->server,
2697                                                NFSPROC_WRITE,
2698                                                (xdrproc_t)xdr_writeargs,       &SERP_FILE(node),
2699                                                (xdrproc_t)xdr_attrstat,        &node->serporid) ) {
2700                return -1;
2701        }
2702
2703
2704        if (NFS_OK != (e=node->serporid.status) ) {
2705                /* try at least to recover the current attributes */
2706                updateAttr(node, 1 /* force */);
2707                rtems_set_errno_and_return_minus_one(e);
2708        }
2709
2710        node->age = nowSeconds();
2711
2712        return count;
2713}
2714
2715#define nfs_dir_write  0
2716#define nfs_link_write 0
2717
2718/* IOCTL is unneeded/unsupported */
2719#ifdef DECLARE_BODY
2720static int nfs_file_ioctl(
2721        rtems_libio_t *iop,
2722        uint32_t      command,
2723        void          *buffer
2724)DECLARE_BODY
2725#else
2726#define nfs_file_ioctl 0
2727#define nfs_dir_ioctl 0
2728#define nfs_link_ioctl 0
2729#endif
2730
2731static int nfs_file_lseek(
2732        rtems_libio_t *iop,
2733        off_t          length,
2734        int            whence
2735)
2736{
2737#if DEBUG & DEBUG_SYSCALLS
2738        fprintf(stderr,
2739                        "lseek to %i (length %i, whence %i)\n",
2740                        iop->offset,
2741                        length,
2742                        whence);
2743#endif
2744        if ( SEEK_END == whence ) {
2745                /* rtems (4.6.2) libcsupport code 'lseek' uses iop->size to
2746                 * compute the offset. We don't want to track the file size
2747                 * by updating 'iop->size' constantly.
2748                 * Since lseek is the only place using iop->size, we work
2749                 * around this by tweaking the offset here...
2750                 */
2751                NfsNode node = iop->pathinfo.node_access;
2752                fattr   *fa  = &SERP_ATTR(node);
2753
2754                if (updateAttr(node, 0 /* only if old */)) {
2755                        return -1;
2756                }
2757                iop->offset = fa->size;
2758        }
2759
2760        /* this is particularly easy :-) */
2761        return iop->offset;
2762}
2763
2764static int nfs_dir_lseek(
2765        rtems_libio_t *iop,
2766        off_t          length,
2767        int            whence
2768)
2769{
2770DirInfo di = iop->file_info;
2771
2772        /* we don't support anything other than
2773         * rewinding
2774         */
2775        if (SEEK_SET != whence || 0 != length) {
2776                errno = ENOTSUP;
2777                return -1;
2778        }
2779
2780        /* rewind cookie */
2781        memset( &di->readdirargs.cookie,
2782                0,
2783                sizeof(di->readdirargs.cookie) );
2784
2785        di->eofreached = FALSE;
2786
2787        return iop->offset;
2788}
2789
2790#define nfs_link_lseek 0
2791
2792#if 0   /* structure types for reference */
2793struct fattr {
2794                ftype type;
2795                u_int mode;
2796                u_int nlink;
2797                u_int uid;
2798                u_int gid;
2799                u_int size;
2800                u_int blocksize;
2801                u_int rdev;
2802                u_int blocks;
2803                u_int fsid;
2804                u_int fileid;
2805                nfstime atime;
2806                nfstime mtime;
2807                nfstime ctime;
2808};
2809
2810struct  stat
2811{
2812                dev_t     st_dev;
2813                ino_t     st_ino;
2814                mode_t    st_mode;
2815                nlink_t   st_nlink;
2816                uid_t     st_uid;
2817                gid_t     st_gid;
2818                dev_t     st_rdev;
2819                off_t     st_size;
2820                /* SysV/sco doesn't have the rest... But Solaris, eabi does.  */
2821#if defined(__svr4__) && !defined(__PPC__) && !defined(__sun__)
2822                time_t    st_atime;
2823                time_t    st_mtime;
2824                time_t    st_ctime;
2825#else
2826                time_t    st_atime;
2827                long      st_spare1;
2828                time_t    st_mtime;
2829                long      st_spare2;
2830                time_t    st_ctime;
2831                long      st_spare3;
2832                long      st_blksize;
2833                long      st_blocks;
2834                long  st_spare4[2];
2835#endif
2836};
2837#endif
2838
2839/* common for file/dir/link */
2840static int nfs_fstat(
2841        rtems_filesystem_location_info_t *loc,
2842        struct stat                      *buf
2843)
2844{
2845NfsNode node = loc->node_access;
2846fattr   *fa  = &SERP_ATTR(node);
2847
2848        if (updateAttr(node, 0 /* only if old */)) {
2849                return -1;
2850        }
2851
2852/* done by caller
2853        memset(buf, 0, sizeof(*buf));
2854 */
2855
2856        /* translate */
2857
2858        /* one of the branches hopefully is optimized away */
2859        if (sizeof(ino_t) < sizeof(u_int)) {
2860        buf->st_dev             = NFS_MAKE_DEV_T_INO_HACK((NfsNode)loc->node_access);
2861        } else {
2862        buf->st_dev             = NFS_MAKE_DEV_T((NfsNode)loc->node_access);
2863        }
2864        buf->st_mode    = fa->mode;
2865        buf->st_nlink   = fa->nlink;
2866        buf->st_uid             = fa->uid;
2867        buf->st_gid             = fa->gid;
2868        buf->st_size    = fa->size;
2869        /* Set to "preferred size" of this NFS client implementation */
2870        buf->st_blksize = nfsStBlksize ? nfsStBlksize : fa->blocksize;
2871        buf->st_rdev    = fa->rdev;
2872        buf->st_blocks  = fa->blocks;
2873        buf->st_ino     = fa->fileid;
2874        buf->st_atime   = fa->atime.seconds;
2875        buf->st_mtime   = fa->mtime.seconds;
2876        buf->st_ctime   = fa->ctime.seconds;
2877
2878#if 0 /* NFS should return the modes */
2879        switch(fa->type) {
2880                default:
2881                case NFNON:
2882                case NFBAD:
2883                                break;
2884
2885                case NFSOCK: buf->st_mode |= S_IFSOCK; break;
2886                case NFFIFO: buf->st_mode |= S_IFIFO;  break;
2887                case NFREG : buf->st_mode |= S_IFREG;  break;
2888                case NFDIR : buf->st_mode |= S_IFDIR;  break;
2889                case NFBLK : buf->st_mode |= S_IFBLK;  break;
2890                case NFCHR : buf->st_mode |= S_IFCHR;  break;
2891                case NFLNK : buf->st_mode |= S_IFLNK;  break;
2892        }
2893#endif
2894
2895        return 0;
2896}
2897
2898/* a helper which does the real work for
2899 * a couple of handlers (such as chmod,
2900 * ftruncate or utime)
2901 */
2902static int
2903nfs_sattr(NfsNode node, sattr *arg, u_long mask)
2904{
2905
2906rtems_clock_time_value  now;
2907nfstime                                 nfsnow, t;
2908int                                             e;
2909u_int                                   mode;
2910
2911        if (updateAttr(node, 0 /* only if old */))
2912                return -1;
2913
2914        rtems_clock_get(RTEMS_CLOCK_GET_TIME_VALUE, &now);
2915
2916        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2917        nfsnow.seconds  = now.seconds;
2918        nfsnow.useconds = now.microseconds;
2919
2920        /* merge permission bits into existing type bits */
2921        mode = SERP_ATTR(node).mode;
2922        if (mask & SATTR_MODE) {
2923                mode &= S_IFMT;
2924                mode |= arg->mode & ~S_IFMT;
2925        } else {
2926                mode = -1;
2927        }
2928        SERP_ARGS(node).sattrarg.attributes.mode  = mode;
2929
2930        SERP_ARGS(node).sattrarg.attributes.uid   =
2931                (mask & SATTR_UID)  ? arg->uid : -1;
2932
2933        SERP_ARGS(node).sattrarg.attributes.gid   =
2934                (mask & SATTR_GID)  ? arg->gid : -1;
2935
2936        SERP_ARGS(node).sattrarg.attributes.size  =
2937                (mask & SATTR_SIZE) ? arg->size : -1;
2938
2939        if (mask & SATTR_ATIME)
2940                t = arg->atime;
2941        else if (mask & SATTR_TOUCHA)
2942                t = nfsnow;
2943        else
2944                t.seconds = t.useconds = -1;
2945        SERP_ARGS(node).sattrarg.attributes.atime = t;
2946
2947        if (mask & SATTR_ATIME)
2948                t = arg->mtime;
2949        else if (mask & SATTR_TOUCHA)
2950                t = nfsnow;
2951        else
2952                t.seconds = t.useconds = -1;
2953        SERP_ARGS(node).sattrarg.attributes.mtime = t;
2954
2955        node->serporid.status = NFS_OK;
2956
2957        if ( nfscall( node->nfs->server,
2958                                                NFSPROC_SETATTR,
2959                                                (xdrproc_t)xdr_sattrargs,       &SERP_FILE(node),
2960                                                (xdrproc_t)xdr_attrstat,        &node->serporid) ) {
2961#if DEBUG & DEBUG_SYSCALLS
2962                fprintf(stderr,
2963                                "nfs_sattr (mask 0x%08x): %s",
2964                                mask,
2965                                strerror(errno));
2966#endif
2967                return -1;
2968        }
2969
2970        if (NFS_OK != (e=node->serporid.status) ) {
2971#if DEBUG & DEBUG_SYSCALLS
2972                fprintf(stderr,"nfs_sattr: %s\n",strerror(e));
2973#endif
2974                /* try at least to recover the current attributes */
2975                updateAttr(node, 1 /* force */);
2976                rtems_set_errno_and_return_minus_one(e);
2977        }
2978
2979        node->age = nowSeconds();
2980
2981        return 0;
2982}
2983
2984
2985/* common for file/dir/link */
2986static int nfs_fchmod(
2987        rtems_filesystem_location_info_t *loc,
2988        mode_t                            mode
2989)
2990{
2991sattr   arg;
2992
2993        arg.mode = mode;
2994        return nfs_sattr(loc->node_access, &arg, SATTR_MODE);
2995       
2996}
2997
2998/* just set the size attribute to 'length'
2999 * the server will take care of the rest :-)
3000 */
3001static int nfs_file_ftruncate(
3002        rtems_libio_t *iop,
3003        off_t          length
3004)
3005{
3006sattr                                   arg;
3007
3008        arg.size = length;
3009        /* must not modify any other attribute; if we are not the owner
3010         * of the file or directory but only have write access changing
3011         * any attribute besides 'size' will fail...
3012         */
3013        return nfs_sattr(iop->pathinfo.node_access,
3014                                         &arg,
3015                                         SATTR_SIZE);
3016}
3017
3018#define nfs_dir_ftruncate 0
3019#define nfs_link_ftruncate 0
3020
3021/* not implemented */
3022#ifdef DECLARE_BODY
3023static int nfs_file_fpathconf(
3024        rtems_libio_t *iop,
3025        int name
3026)DECLARE_BODY
3027#else
3028#define nfs_file_fpathconf 0
3029#define nfs_dir_fpathconf 0
3030#define nfs_link_fpathconf 0
3031#endif
3032
3033/* unused */
3034#ifdef DECLARE_BODY
3035static int nfs_file_fsync(
3036        rtems_libio_t *iop
3037)DECLARE_BODY
3038#else
3039#define nfs_file_fsync 0
3040#define nfs_dir_fsync 0
3041#define nfs_link_fsync 0
3042#endif
3043
3044/* unused */
3045#ifdef DECLARE_BODY
3046static int nfs_file_fdatasync(
3047        rtems_libio_t *iop
3048)DECLARE_BODY
3049#else
3050#define nfs_file_fdatasync 0
3051#define nfs_dir_fdatasync 0
3052#define nfs_link_fdatasync 0
3053#endif
3054
3055/* unused */
3056#ifdef DECLARE_BODY
3057static int nfs_file_fcntl(
3058        int            cmd,
3059        rtems_libio_t *iop
3060)DECLARE_BODY
3061#else
3062#define nfs_file_fcntl 0
3063#define nfs_dir_fcntl 0
3064#define nfs_link_fcntl 0
3065#endif
3066
3067/* files and symlinks are removed
3068 * by the common nfs_unlink() routine.
3069 * NFS has a different NFSPROC_RMDIR
3070 * call, though...
3071 */
3072static int nfs_dir_rmnod(
3073        rtems_filesystem_location_info_t      *pathloc       /* IN */
3074)
3075{
3076        return nfs_do_unlink(pathloc, NFSPROC_RMDIR);
3077}
3078
3079/* the file handlers table */
3080static
3081struct _rtems_filesystem_file_handlers_r nfs_file_file_handlers = {
3082                nfs_file_open,                  /* OPTIONAL; may be NULL */
3083                nfs_file_close,                 /* OPTIONAL; may be NULL */
3084                nfs_file_read,                  /* OPTIONAL; may be NULL */
3085                nfs_file_write,                 /* OPTIONAL; may be NULL */
3086                nfs_file_ioctl,                 /* OPTIONAL; may be NULL */
3087                nfs_file_lseek,                 /* OPTIONAL; may be NULL */
3088                nfs_fstat,                              /* OPTIONAL; may be NULL */
3089                nfs_fchmod,                             /* OPTIONAL; may be NULL */
3090                nfs_file_ftruncate,             /* OPTIONAL; may be NULL */
3091                nfs_file_fpathconf,             /* OPTIONAL; may be NULL - UNUSED */
3092                nfs_file_fsync,                 /* OPTIONAL; may be NULL */
3093                nfs_file_fdatasync,             /* OPTIONAL; may be NULL */
3094                nfs_file_fcntl,                 /* OPTIONAL; may be NULL */
3095                nfs_unlink,                             /* OPTIONAL; may be NULL */
3096};
3097
3098/* the directory handlers table */
3099static
3100struct _rtems_filesystem_file_handlers_r nfs_dir_file_handlers = {
3101                nfs_dir_open,                   /* OPTIONAL; may be NULL */
3102                nfs_dir_close,                  /* OPTIONAL; may be NULL */
3103                nfs_dir_read,                   /* OPTIONAL; may be NULL */
3104                nfs_dir_write,                  /* OPTIONAL; may be NULL */
3105                nfs_dir_ioctl,                  /* OPTIONAL; may be NULL */
3106                nfs_dir_lseek,                  /* OPTIONAL; may be NULL */
3107                nfs_fstat,                              /* OPTIONAL; may be NULL */
3108                nfs_fchmod,                             /* OPTIONAL; may be NULL */
3109                nfs_dir_ftruncate,              /* OPTIONAL; may be NULL */
3110                nfs_dir_fpathconf,              /* OPTIONAL; may be NULL - UNUSED */
3111                nfs_dir_fsync,                  /* OPTIONAL; may be NULL */
3112                nfs_dir_fdatasync,              /* OPTIONAL; may be NULL */
3113                nfs_dir_fcntl,                  /* OPTIONAL; may be NULL */
3114                nfs_dir_rmnod,                          /* OPTIONAL; may be NULL */
3115};
3116
3117/* the link handlers table */
3118static
3119struct _rtems_filesystem_file_handlers_r nfs_link_file_handlers = {
3120                nfs_link_open,                  /* OPTIONAL; may be NULL */
3121                nfs_link_close,                 /* OPTIONAL; may be NULL */
3122                nfs_link_read,                  /* OPTIONAL; may be NULL */
3123                nfs_link_write,                 /* OPTIONAL; may be NULL */
3124                nfs_link_ioctl,                 /* OPTIONAL; may be NULL */
3125                nfs_link_lseek,                 /* OPTIONAL; may be NULL */
3126                nfs_fstat,                              /* OPTIONAL; may be NULL */
3127                nfs_fchmod,                             /* OPTIONAL; may be NULL */
3128                nfs_link_ftruncate,             /* OPTIONAL; may be NULL */
3129                nfs_link_fpathconf,             /* OPTIONAL; may be NULL - UNUSED */
3130                nfs_link_fsync,                 /* OPTIONAL; may be NULL */
3131                nfs_link_fdatasync,             /* OPTIONAL; may be NULL */
3132                nfs_link_fcntl,                 /* OPTIONAL; may be NULL */
3133                nfs_unlink,                             /* OPTIONAL; may be NULL */
3134};
3135
3136/* we need a dummy driver entry table to get a
3137 * major number from the system
3138 */
3139static
3140rtems_device_driver nfs_initialize(
3141                rtems_device_major_number       major,
3142                rtems_device_minor_number       minor,
3143                void                                            *arg
3144)
3145{
3146        /* we don't really use this routine because
3147     * we cannot supply an argument (contrary
3148     * to what the 'arg' parameter suggests - it
3149     * is always set to 0 by the generics :-()
3150     * and because we don't want the user to
3151     * have to deal with the major number (which
3152     * OTOH is something WE are interested in. The
3153     * only reason for using this API was getting
3154     * a major number, after all).
3155     *
3156         * Something must be present, however, to
3157         * reserve a slot in the driver table.
3158         */
3159        return RTEMS_SUCCESSFUL;
3160}
3161
3162static rtems_driver_address_table       drvNfs = {
3163                nfs_initialize,
3164                0,                                      /* open    */
3165                0,                                      /* close   */
3166                0,                                      /* read    */
3167                0,                                      /* write   */
3168                0                                       /* control */
3169};
3170
3171/* Dump a list of the currently mounted NFS to a  file */
3172int
3173nfsMountsShow(FILE *f)
3174{
3175char    *mntpt = 0;
3176Nfs             nfs;
3177
3178        if (!f)
3179                f = stdout;
3180
3181        if ( !(mntpt=malloc(MAXPATHLEN)) ) {
3182                fprintf(stderr,"nfsMountsShow(): no memory\n");
3183                return -1;
3184        }
3185       
3186        fprintf(f,"Currently Mounted NFS:\n");
3187
3188        LOCK(nfsGlob.llock);
3189
3190        for (nfs = nfsGlob.mounted_fs; nfs; nfs=nfs->next) {
3191                fprintf(f,"%s on ", nfs->mt_entry->dev);
3192                if (rtems_filesystem_resolve_location(mntpt, MAXPATHLEN, &nfs->mt_entry->mt_fs_root))
3193                        fprintf(f,"<UNABLE TO LOOKUP MOUNTPOINT>\n");
3194                else
3195                        fprintf(f,"%s\n",mntpt);
3196        }
3197
3198        UNLOCK(nfsGlob.llock);
3199
3200        free(mntpt);
3201        return 0;
3202}
3203
3204/* convenience wrapper
3205 *
3206 * NOTE: this routine calls NON-REENTRANT
3207 *       gethostbyname() if the host is
3208 *       not in 'dot' notation.
3209 */
3210int
3211nfsMount(char *uidhost, char *path, char *mntpoint)
3212{
3213rtems_filesystem_mount_table_entry_t    *mtab;
3214struct stat                                                             st;
3215int                                                                             devl;
3216char                                                                    *host;
3217int                                                                             rval = -1;
3218char                                                                    *dev =  0;
3219
3220        if (!uidhost || !path || !mntpoint) {
3221                fprintf(stderr,"usage: nfsMount(""[uid.gid@]host"",""path"",""mountpoint"")\n");
3222                nfsMountsShow(stderr);
3223                return -1;
3224        }
3225
3226        if ( !(dev = malloc((devl=strlen(uidhost) + 20 + strlen(path)+1))) ) {
3227                fprintf(stderr,"nfsMount: out of memory\n");
3228                return -1;
3229        }
3230
3231        /* Try to create the mount point if nonexistent */
3232        if (stat(mntpoint, &st)) {
3233                if (ENOENT != errno) {
3234                        perror("nfsMount trying to create mount point - stat failed");
3235                        goto cleanup;
3236                } else if (mkdir(mntpoint,0777)) {
3237                        perror("nfsMount trying to create mount point");
3238                        goto cleanup;
3239                }
3240        }
3241
3242        if ( !(host=strchr(uidhost,UIDSEP)) ) {
3243                host = uidhost;
3244        } else {
3245                host++;
3246        }
3247
3248        if (isdigit(*host)) {
3249                /* avoid using gethostbyname */
3250                sprintf(dev,"%s:%s",uidhost,path);
3251        } else {
3252                struct hostent *h;
3253
3254                /* copy the uid part (hostname will be
3255                 * overwritten)
3256                 */
3257                strcpy(dev, uidhost);
3258
3259                /* NOTE NOTE NOTE: gethostbyname is NOT
3260                 * thread safe. This is UGLY
3261                 */
3262
3263/* BEGIN OF NON-THREAD SAFE REGION */
3264
3265                h = gethostbyname(host);
3266
3267                if ( !h ||
3268                         !inet_ntop( AF_INET,
3269                                             (struct in_addr*)h->h_addr_list[0],
3270                                                 dev  + (host - uidhost),
3271                                                 devl - (host - uidhost) )
3272                        ) {
3273                        fprintf(stderr,"nfsMount: host '%s' not found\n",host);
3274                        goto cleanup;
3275                }
3276
3277/* END OF NON-THREAD SAFE REGION */
3278
3279                /* append ':<path>' */
3280                strcat(dev,":");
3281                strcat(dev,path);
3282        }
3283
3284        printf("Trying to mount %s on %s\n",dev,mntpoint);
3285
3286        if (mount(&mtab,
3287                          &nfs_fs_ops,
3288                          RTEMS_FILESYSTEM_READ_WRITE,
3289                          dev,
3290                          mntpoint)) {
3291                perror("nfsMount - mount");
3292                goto cleanup;
3293        }
3294
3295        rval = 0;
3296
3297cleanup:
3298        free(dev);
3299        return rval;
3300}
3301
3302/* HERE COMES A REALLY UGLY HACK */
3303
3304/* This is stupid; it is _very_ hard to find the path
3305 * leading to a rtems_filesystem_location_info_t node :-(
3306 * The only easy way is making the location the current
3307 * directory and issue a getcwd().
3308 * However, since we don't want to tamper with the
3309 * current directory, we must create a separate
3310 * task to do the job for us - sigh.
3311 */
3312
3313typedef struct ResolvePathArgRec_ {
3314        rtems_filesystem_location_info_t        *loc;   /* IN: location to resolve      */
3315        char                                                            *buf;   /* IN/OUT: buffer where to put the path */
3316        int                                                                     len;    /* IN: buffer length            */
3317        rtems_id                                                        sync;   /* IN: synchronization          */
3318        rtems_status_code                                       status; /* OUT: result                          */
3319} ResolvePathArgRec, *ResolvePathArg;
3320
3321static void
3322resolve_path(rtems_task_argument arg)
3323{
3324ResolvePathArg                                          rpa = (ResolvePathArg)arg;
3325rtems_filesystem_location_info_t        old;
3326
3327        /* IMPORTANT: let the helper task have its own libio environment (i.e. cwd) */
3328        if (RTEMS_SUCCESSFUL == (rpa->status = rtems_libio_set_private_env())) {
3329
3330                old = rtems_filesystem_current;
3331
3332                rtems_filesystem_current = *(rpa->loc);
3333
3334                if ( !getcwd(rpa->buf, rpa->len) )
3335                        rpa->status = RTEMS_UNSATISFIED;
3336
3337                /* must restore the cwd because 'freenode' will be called on it */
3338                rtems_filesystem_current = old;
3339        }
3340        rtems_semaphore_release(rpa->sync);
3341        rtems_task_delete(RTEMS_SELF);
3342}
3343
3344
3345/* a utility routine to find the path leading to a
3346 * rtems_filesystem_location_info_t node
3347 *
3348 * INPUT: 'loc' and a buffer 'buf' (length 'len') to hold the
3349 *        path.
3350 * OUTPUT: path copied into 'buf'
3351 *
3352 * RETURNS: 0 on success, RTEMS error code on error.
3353 */
3354rtems_status_code
3355rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc)
3356{
3357ResolvePathArgRec       arg;
3358rtems_id                        tid = 0;
3359rtems_task_priority     pri;
3360rtems_status_code       status;
3361
3362        arg.loc  = loc;
3363        arg.buf  = buf;
3364        arg.len  = len;
3365        arg.sync = 0;
3366
3367        status = rtems_semaphore_create(
3368                                        rtems_build_name('r','e','s','s'),
3369                                        0,
3370                                        RTEMS_SIMPLE_BINARY_SEMAPHORE,
3371                                        0,
3372                                        &arg.sync);
3373
3374        if (RTEMS_SUCCESSFUL != status)
3375                goto cleanup;
3376
3377        rtems_task_set_priority(RTEMS_SELF, RTEMS_CURRENT_PRIORITY, &pri);
3378
3379        status = rtems_task_create(
3380                                        rtems_build_name('r','e','s','s'),
3381                                        pri,
3382                                        RTEMS_MINIMUM_STACK_SIZE + 50000,
3383                                        RTEMS_DEFAULT_MODES,
3384                                        RTEMS_DEFAULT_ATTRIBUTES,
3385                                        &tid);
3386
3387        if (RTEMS_SUCCESSFUL != status)
3388                goto cleanup;
3389
3390        status = rtems_task_start(tid, resolve_path, (rtems_task_argument)&arg);
3391
3392        if (RTEMS_SUCCESSFUL != status) {
3393                rtems_task_delete(tid);
3394                goto cleanup;
3395        }
3396
3397
3398        /* synchronize with the helper task */
3399        rtems_semaphore_obtain(arg.sync, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
3400
3401        status = arg.status;
3402
3403cleanup:
3404        if (arg.sync)
3405                rtems_semaphore_delete(arg.sync);
3406
3407        return status;
3408}
3409
3410int
3411nfsSetTimeout(uint32_t timeout_ms)
3412{
3413rtems_interrupt_level k;
3414uint32_t                  s,us;
3415
3416        if ( timeout_ms > 100000 ) {
3417                /* out of range */
3418                return -1;
3419        }
3420
3421        s  = timeout_ms/1000;
3422        us = (timeout_ms % 1000) * 1000;
3423
3424        rtems_interrupt_disable(k);
3425        _nfscalltimeout.tv_sec  = s;
3426        _nfscalltimeout.tv_usec = us;
3427        rtems_interrupt_enable(k);
3428
3429        return 0;
3430}
3431
3432uint32_t
3433nfsGetTimeout()
3434{
3435rtems_interrupt_level k;
3436uint32_t              s,us;
3437        rtems_interrupt_disable(k);
3438        s  = _nfscalltimeout.tv_sec;
3439        us = _nfscalltimeout.tv_usec;
3440        rtems_interrupt_enable(k);
3441        return s*1000 + us/1000;
3442}
Note: See TracBrowser for help on using the repository browser.