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

4.104.115
Last change on this file since 07d6fd5 was 07d6fd5, checked in by Chris Johns <chrisj@…>, on 04/29/09 at 08:31:27

2009-04-29 Chris Johns <chrisj@…>

  • libcsupport/include/rtems/libio.h: Add rtems_off64_t for internal use. Update the internal off_t to the 64bit offset.
  • libnetworking/lib/ftpfs.c, libnetworking/lib/tftpDriver.c, libfs/src/nfsclient/src/nfs.c, libfs/src/imfs/imfs_fifo.c, libfs/src/imfs/memfile.c, libfs/src/imfs/imfs_directory.c, libfs/src/imfs/imfs.h, libfs/src/imfs/deviceio.c: Change off_t to rtems_off64_t.
  • libmisc/shell/main_msdosfmt.c: Add an info level so the format code can tell the user what is happening. Add more options to control the format configuration.
  • libfs/src/dosfs/msdos_format.c: Add a print function to display the format progress and print statements. Select a better default cluster size depending on the size of the disk. This lowers the size of the FAT on large disks. Read and maintain the MRB partition information.
  • libfs/src/dosfs/dosfs.h, libfs/src/dosfs/fat.h, libfs/src/dosfs/fat_file.c, libfs/src/dosfs/fat_file.h, libfs/src/dosfs/msdos.h, libfs/src/dosfs/msdos_conv.c, libfs/src/dosfs/msdos_create.c, libfs/src/dosfs/msdos_file.c, libfs/src/dosfs/msdos_handlers_dir.c, libfs/src/dosfs/msdos_handlers_file.c, libfs/src/dosfs/msdos_init.c, libfs/src/dosfs/msdos_initsupp.c, libfs/src/dosfs/msdos_misc.c, libfs/src/dosfs/msdos_mknod.c: Add long file name support. Change off_t to rtems_off64_t.
  • Property mode set to 100644
File size: 80.3 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{
483  rtems_interval rval;
484  rtems_clock_get_seconds_since_epoch( &rval );
485  return rval;
486}
487
488
489/* Per mounted FS structure */
490typedef struct NfsRec_ {
491                /* the NFS server we're talking to.
492                 */
493        RpcUdpServer                                             server;
494                /* statistics; how many NfsNodes are
495                 * currently alive.
496                 */
497        volatile int                                             nodesInUse;
498#if DEBUG & DEBUG_COUNT_NODES
499                /* statistics; how many 'NfsNode.str'
500                 * strings are currently allocated.
501                 */
502        volatile int                                             stringsInUse;
503#endif
504                /* A small number who uniquely
505                 * identifies a mounted NFS within
506                 * this driver (i.e. this NfsRec).
507                 * Each time a NFS is mounted, the
508                 * global ID counter is incremented
509                 * and its value is assigned to the
510                 * newly created NfsRec.
511                 */
512        u_short                                                          id;
513                /* Our RTEMS filesystem mt_entry
514                 */
515        rtems_filesystem_mount_table_entry_t *mt_entry;
516                /* Next NfsRec on a linked list who
517                 * is anchored at nfsGlob
518                 */
519        struct NfsRec_                                           *next;
520                /* Who we pretend we are
521                 */
522        u_long                                                           uid,gid;
523} NfsRec, *Nfs;
524
525typedef struct NfsNodeRec_ {
526                /* This holds this node's attributes
527                 * (stats) and its nfs filehandle.
528                 * It also contains room for nfs rpc
529                 * arguments.
530                 */
531        serporid        serporid;
532                /* The arguments we used when doing
533                 * the 'lookup' call for this node.
534                 * We need this information (especially
535                 * the directory FH) for performing
536                 * certain operations on this
537                 * node (in particular: for unlinking
538                 * it from a parent directory)
539                 */
540        diropargs               args;
541                /* FS this node belongs to
542                 */
543        Nfs                             nfs;
544                /* A buffer for the string the
545                 * args.name points to.
546                 * We need this because args.name might
547                 * temporarily point to strings on the
548                 * stack. Duplicates are allocated from
549                 * the heap and attached to 'str' so
550                 * they can be released as appropriate.
551                 */
552        char               *str;
553                /* A timestamp for the stats
554                 */
555        TimeStamp               age;
556} NfsNodeRec, *NfsNode;
557
558/*****************************************
559        Forward Declarations
560 *****************************************/
561
562static int nfs_readlink(
563        rtems_filesystem_location_info_t  *loc,         /* IN  */       
564        char                                                      *buf,                 /* OUT */
565        size_t                                                    len
566);
567
568static int updateAttr(NfsNode node, int force);
569
570/* Mask bits when setting attributes.
571 * Only the 'arg' fields with their
572 * corresponding bit set in the mask
573 * will be used. The others are left
574 * unchanged.
575 * The 'TOUCH' bits instruct nfs_sattr()
576 * to update the respective time
577 * fields to the current time
578 */
579#define SATTR_MODE              (1<<0)
580#define SATTR_UID               (1<<1)
581#define SATTR_GID               (1<<2)
582#define SATTR_SIZE              (1<<3)
583#define SATTR_ATIME             (1<<4)
584#define SATTR_TOUCHA    (1<<5)
585#define SATTR_MTIME             (1<<6)
586#define SATTR_TOUCHM    (1<<7)
587#define SATTR_TOUCH             (SATTR_TOUCHM | SATTR_TOUCHA)
588
589static int
590nfs_sattr(NfsNode node, sattr *arg, u_long mask);
591
592extern struct _rtems_filesystem_operations_table nfs_fs_ops;
593static struct _rtems_filesystem_file_handlers_r  nfs_file_file_handlers;
594static struct _rtems_filesystem_file_handlers_r  nfs_dir_file_handlers;
595static struct _rtems_filesystem_file_handlers_r  nfs_link_file_handlers;
596static             rtems_driver_address_table            drvNfs;
597
598int
599nfsMountsShow(FILE*);
600
601rtems_status_code
602rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc);
603
604
605/*****************************************
606        Inline Routines
607 *****************************************/
608
609
610/* * * * * * * * * * * * * * * * * *
611        Trivial Operations on a NfsNode
612 * * * * * * * * * * * * * * * * * */
613
614/* determine if a location 'l' is an NFS root node */
615static inline int
616locIsRoot(rtems_filesystem_location_info_t *l)
617{
618NfsNode me = (NfsNode) l->node_access;
619NfsNode r;
620        r = (NfsNode)l->mt_entry->mt_fs_root.node_access;
621        return SERP_ATTR(r).fileid == SERP_ATTR(me).fileid &&
622                   SERP_ATTR(r).fsid   == SERP_ATTR(me).fsid;
623}
624
625/* determine if a location 'l' is an NFS node */
626static inline int
627locIsNfs(rtems_filesystem_location_info_t *l)
628{
629        return l->ops == &nfs_fs_ops;
630}
631
632/* determine if two locations refer to the
633 * same entity. We know that 'nfsloc' is a
634 * location inside nfs. However, we needn't
635 * know anything about 'anyloc'.
636 */
637static inline int
638locAreEqual(
639        rtems_filesystem_location_info_t *nfsloc,
640        rtems_filesystem_location_info_t *anyloc
641)
642{
643NfsNode na = (NfsNode) nfsloc->node_access;
644NfsNode nb;
645
646        if (!locIsNfs(anyloc))
647                return 0;
648
649        nb = (NfsNode) anyloc->node_access;
650
651        if (na->nfs != nb->nfs)
652                return 0;
653
654        updateAttr(nb, 0);
655
656        return SERP_ATTR(na).fileid == SERP_ATTR(nb).fileid &&
657                   SERP_ATTR(na).fsid   == SERP_ATTR(nb).fsid;
658}
659
660
661
662/*****************************************
663        Global Variables
664 *****************************************/
665
666/* These are (except for MAXNAMLEN/MAXPATHLEN) copied from IMFS */
667
668static rtems_filesystem_limits_and_options_t
669nfs_limits_and_options = {
670   5,                           /* link_max */
671   6,                           /* max_canon */
672   7,                           /* max_input */
673   NFS_MAXNAMLEN,       /* name_max */
674   NFS_MAXPATHLEN,      /* path_max */
675   2,                           /* pipe_buf */
676   1,                           /* posix_async_io */
677   2,                           /* posix_chown_restrictions */
678   3,                           /* posix_no_trunc */
679   4,                           /* posix_prio_io */
680   5,                           /* posix_sync_io */
681   6                            /* posix_vdisable */
682};
683
684/* size of an encoded 'entry' object */
685static int dirres_entry_size;
686
687/* Global stuff and statistics */
688static struct nfsstats {
689                /* A lock for protecting the
690                 * linked ist of mounted NFS
691                 * and the num_mounted_fs field
692                 */
693        rtems_id                                        llock;
694                /* A lock for protecting misc
695                 * stuff  within the driver.
696                 * The lock must only be held
697                 * for short periods of time.
698                 */
699        rtems_id                                        lock;
700                /* Our major number as assigned
701                 * by RTEMS
702                 */
703        rtems_device_major_number       nfs_major;
704                /* The number of currently
705                 * mounted NFS
706                 */
707        int                                                     num_mounted_fs;
708                /* A list of the currently
709                 * mounted NFS
710                 */
711        struct NfsRec_                          *mounted_fs;
712                /* A counter for allocating
713                 * unique IDs to each mounted
714                 * NFS.
715                 * Assume we are not going to
716                 * do more than 16k mounts
717                 * during the system lifetime
718                 */
719        u_short                                         fs_ids;
720} nfsGlob = {0, 0,  0, 0, 0, 0};
721
722/*
723 * Global variable to tune the 'st_blksize' (stat(2)) value this nfs
724 * client should report.
725 * size on the server.
726 */                   
727#ifndef DEFAULT_NFS_ST_BLKSIZE
728#define DEFAULT_NFS_ST_BLKSIZE  NFS_MAXDATA
729#endif
730int nfsStBlksize = DEFAULT_NFS_ST_BLKSIZE;
731
732/* Two pools of RPC transactions;
733 * One with small send buffers
734 * the other with a big one.
735 * The actual size of the small
736 * buffer is configurable (see top).
737 *
738 * Note: The RX buffers are always
739 * big
740 */
741static RpcUdpXactPool smallPool = 0;
742static RpcUdpXactPool bigPool   = 0;
743
744
745/*****************************************
746        Implementation
747 *****************************************/
748
749/* Create a Nfs object. This is
750 * per-mounted NFS information.
751 *
752 * ARGS:        The Nfs server handle.
753 *
754 * RETURNS:     Nfs on success,
755 *                      NULL on failure with
756 *                      errno set
757 *
758 * NOTE:        The submitted server
759 *                      object is 'owned' by
760 *                      this Nfs and will be
761 *                      destroyed by nfsDestroy()
762 */
763static Nfs
764nfsCreate(RpcUdpServer server)
765{
766Nfs rval = calloc(1,sizeof(*rval));
767
768        if (rval) {
769                rval->server     = server;
770                LOCK(nfsGlob.llock);
771                        rval->next                 = nfsGlob.mounted_fs;
772                        nfsGlob.mounted_fs = rval;
773                UNLOCK(nfsGlob.llock);
774        } else {
775                errno = ENOMEM;
776        }
777                return rval;
778}
779
780/* Destroy an Nfs object and
781 * its associated server
782 */
783static void
784nfsDestroy(Nfs nfs)
785{
786register Nfs prev;
787        if (!nfs)
788                return;
789
790        LOCK(nfsGlob.llock);
791                if (nfs == nfsGlob.mounted_fs)
792                        nfsGlob.mounted_fs = nfs->next;
793                else {
794                        for (prev = nfsGlob.mounted_fs;
795                                 prev && prev->next != nfs;
796                                 prev = prev->next)
797                                        /* nothing else to do */;
798                        assert( prev );
799                        prev->next = nfs->next;
800                }
801        UNLOCK(nfsGlob.llock);
802
803        nfs->next = 0; /* paranoia */
804        rpcUdpServerDestroy(nfs->server);
805        free(nfs);
806}
807
808/*
809 * Create a Node. The node will
810 * be associated with a particular
811 * mounted NFS identified by 'nfs'
812 * Optionally, a NFS file handle
813 * may be copied into this node.
814 *
815 * ARGS:        nfs of the NFS this node
816 *                      belongs to.
817 *                      NFS file handle identifying
818 *                      this node.
819 * RETURNS:     node on success,
820 *                      NULL on failure with errno
821 *                      set.
822 *
823 * NOTE:        The caller of this routine
824 *                      is responsible for copying
825 *                      a NFS file handle if she
826 *                      choses to pass a NULL fh.
827 *
828 *                      The driver code assumes the
829 *                      a node always has a valid
830 *                      NFS filehandle and file
831 *                      attributes (unless the latter
832 *                      are aged).
833 */
834static NfsNode
835nfsNodeCreate(Nfs nfs, fhandle *fh)
836{
837NfsNode rval = malloc(sizeof(*rval));
838unsigned long flags;
839
840#if DEBUG & DEBUG_TRACK_NODES
841        fprintf(stderr,"NFS: creating a node\n");
842#endif
843
844        if (rval) {
845                if (fh)
846                        memcpy( &SERP_FILE(rval), fh, sizeof(*fh) );
847                rtems_interrupt_disable(flags);
848                        nfs->nodesInUse++;
849                rtems_interrupt_enable(flags);
850                rval->nfs       = nfs;
851                rval->str               = 0;
852        } else {
853                errno = ENOMEM;
854        }
855
856        return rval;
857}
858
859/* destroy a node */
860static void
861nfsNodeDestroy(NfsNode node)
862{
863unsigned long flags;
864
865#if DEBUG & DEBUG_TRACK_NODES
866        fprintf(stderr,"NFS: destroying a node\n");
867#endif
868#if 0
869        if (!node)
870                return;
871        /* this probably does nothing... */
872        xdr_free(xdr_serporid, &node->serporid);
873#endif
874
875        rtems_interrupt_disable(flags);
876                node->nfs->nodesInUse--;
877#if DEBUG & DEBUG_COUNT_NODES
878                if (node->str)
879                        node->nfs->stringsInUse--;
880#endif
881        rtems_interrupt_enable(flags);
882
883        if (node->str)
884                free(node->str);
885
886        free(node);
887}
888
889/* Clone a given node (AKA copy constructor),
890 * i.e. create an exact copy.
891 *
892 * ARGS:        node to clone
893 * RETURNS:     new node on success
894 *                      NULL on failure with errno set.
895 *
896 * NOTE:        a string attached to 'str'
897 *                      is cloned as well. Outdated
898 *                      attributes (of the new copy
899 *                      only) will be refreshed
900 *                      (if unsuccessful, this could
901 *                      be a reason for failure to
902 *                      clone a node).
903 */
904static NfsNode
905nfsNodeClone(NfsNode node)
906{
907NfsNode rval = nfsNodeCreate(node->nfs, 0);
908
909        if (rval) {
910                *rval = *node;
911
912                /* must clone the string also */
913                if (node->str) {
914                        rval->args.name = rval->str = strdup(node->str);
915                        if (!rval->str) {
916                                errno = ENOMEM;
917                                nfsNodeDestroy(rval);
918                                return 0;
919                        }
920#if DEBUG & DEBUG_COUNT_NODES
921                        { unsigned long flags;
922                        rtems_interrupt_disable(flags);
923                                node->nfs->stringsInUse++;
924                        rtems_interrupt_enable(flags);
925                        }
926#endif
927                }
928
929                /* possibly update the stats */
930                if (updateAttr(rval, 0 /* only if necessary */)) {
931                        nfsNodeDestroy(rval);
932                        return 0;
933                }
934        }
935        return rval;
936}
937
938/* Initialize the driver.
939 *
940 * ARGS:        depth of the small and big
941 *                      transaction pools, i.e. how
942 *                      many transactions (buffers)
943 *                      should always be kept around.
944 *
945 *                      (If more transactions are needed,
946 *                      they are created and destroyed
947 *                      on the fly).
948 */
949void
950nfsInit(int smallPoolDepth, int bigPoolDepth)
951{
952static int initialised = 0;
953entry   dummy;
954rtems_status_code status;
955
956        if (initialised)
957                return;
958
959        initialised = 1;
960
961        fprintf(stderr,
962          "RTEMS-NFS $Release$, "                       \
963          "Till Straumann, Stanford/SLAC/SSRL 2002, " \
964          "See LICENSE file for licensing info.\n");
965
966        /* Get a major number */
967
968        if (RTEMS_SUCCESSFUL != rtems_io_register_driver(0, &drvNfs, &nfsGlob.nfs_major)) {
969                fprintf(stderr,"Registering NFS driver failed - %s\n", strerror(errno));
970                return;
971        }
972
973        if (0==smallPoolDepth)
974                smallPoolDepth = 20;
975        if (0==bigPoolDepth)
976                bigPoolDepth   = 10;
977
978        /* it's crucial to zero out the 'next' pointer
979         * because it terminates the xdr_entry recursion
980         *
981         * we also must make the filename some non-zero
982         * char pointer!
983         */
984
985        memset(&dummy, 0, sizeof(dummy));
986
987        dummy.nextentry   = 0;
988        dummy.name        = "somename"; /* guess average length of a filename */
989        dirres_entry_size = xdr_sizeof((xdrproc_t)xdr_entry, &dummy);
990
991        smallPool = rpcUdpXactPoolCreate(
992                NFS_PROGRAM,
993                NFS_VERSION_2,
994                CONFIG_NFS_SMALL_XACT_SIZE,
995                smallPoolDepth);
996        assert( smallPool );
997
998        bigPool = rpcUdpXactPoolCreate(
999                NFS_PROGRAM,
1000                NFS_VERSION_2,
1001                CONFIG_NFS_BIG_XACT_SIZE,
1002                bigPoolDepth);
1003        assert( bigPool );
1004
1005        status = rtems_semaphore_create(
1006                rtems_build_name('N','F','S','l'),
1007                1,
1008                MUTEX_ATTRIBUTES,
1009                0,
1010                &nfsGlob.llock);
1011        assert( status == RTEMS_SUCCESSFUL );
1012        status = rtems_semaphore_create(
1013                rtems_build_name('N','F','S','m'),
1014                1,
1015                MUTEX_ATTRIBUTES,
1016                0,
1017                &nfsGlob.lock);
1018        assert( status == RTEMS_SUCCESSFUL );
1019
1020        if (sizeof(ino_t) < sizeof(u_int)) {
1021                fprintf(stderr,
1022                        "WARNING: Using 'short st_ino' hits performance and may fail to access/find correct files\n");
1023                fprintf(stderr,
1024                        "you should fix newlib's sys/stat.h - for now I'll enable a hack...\n");
1025
1026        }
1027}
1028
1029/* Driver cleanup code
1030 */
1031int
1032nfsCleanup(void)
1033{
1034rtems_id        l;
1035int                     refuse;
1036
1037        if (!nfsGlob.llock) {
1038                /* registering the driver failed - let them still cleanup */
1039                return 0;
1040        }
1041
1042        LOCK(nfsGlob.llock);
1043        if ( (refuse = nfsGlob.num_mounted_fs) ) {
1044                fprintf(stderr,"Refuse to unload NFS; %i filesystems still mounted.\n",
1045                                                refuse);
1046                nfsMountsShow(stderr);
1047                /* yes, printing is slow - but since you try to unload the driver,
1048                 * you assume nobody is using NFS, so what if they have to wait?
1049                 */
1050                UNLOCK(nfsGlob.llock);
1051                return -1;
1052        }
1053
1054        rtems_semaphore_delete(nfsGlob.lock);
1055        nfsGlob.lock = 0;
1056
1057        /* hold the lock while cleaning up... */
1058
1059        rpcUdpXactPoolDestroy(smallPool);
1060        rpcUdpXactPoolDestroy(bigPool);
1061        l = nfsGlob.llock;
1062        rtems_io_unregister_driver(nfsGlob.nfs_major);
1063
1064        rtems_semaphore_delete(l);
1065        nfsGlob.llock = 0;
1066        return 0;
1067}
1068
1069/* NFS RPC wrapper.
1070 *
1071 * ARGS:        srvr    the NFS server we want to call
1072 *                      proc    the NFSPROC_xx we want to invoke
1073 *                      xargs   xdr routine to wrap the arguments
1074 *                      pargs   pointer to the argument object
1075 *                      xres    xdr routine to unwrap the results
1076 *                      pres    pointer to the result object
1077 *
1078 * RETURNS:     0 on success, -1 on error with errno set.
1079 *
1080 * NOTE:        the caller assumes that errno is set to
1081 *                      a nonzero value if this routine returns
1082 *                      an error (nonzero return value).
1083 *
1084 *                      This routine prints RPC error messages to
1085 *                      stderr.
1086 */
1087STATIC int
1088nfscall(
1089        RpcUdpServer    srvr,
1090        int                             proc,
1091        xdrproc_t               xargs,
1092        void *                  pargs,
1093        xdrproc_t               xres,
1094        void *                  pres)
1095{
1096RpcUdpXact              xact;
1097enum clnt_stat  stat;
1098RpcUdpXactPool  pool;
1099int                             rval = -1;
1100
1101
1102        switch (proc) {
1103                case NFSPROC_SYMLINK:
1104                case NFSPROC_WRITE:
1105                                        pool = bigPool;         break;
1106                default:        pool = smallPool;       break;
1107        }
1108
1109        xact = rpcUdpXactPoolGet(pool, XactGetCreate);
1110
1111        if ( !xact ) {
1112                errno = ENOMEM;
1113                return -1;
1114        }
1115
1116        if ( RPC_SUCCESS != (stat=rpcUdpSend(
1117                                                                xact,
1118                                                                srvr,
1119                                                                NFSCALL_TIMEOUT,
1120                                                                proc,
1121                                                                xres,
1122                                                                pres,
1123                                                                xargs,
1124                                                                pargs,
1125                                                                0)) ||
1126             RPC_SUCCESS != (stat=rpcUdpRcv(xact)) ) {
1127
1128                fprintf(stderr,
1129                                "NFS (proc %i) - %s\n",
1130                                proc,
1131                                clnt_sperrno(stat));
1132
1133                switch (stat) {
1134                        /* TODO: this is probably not complete and/or fully accurate */
1135                        case RPC_CANTENCODEARGS : errno = EINVAL;       break;
1136                        case RPC_AUTHERROR      : errno = EPERM;        break;
1137
1138                        case RPC_CANTSEND               :
1139                        case RPC_CANTRECV               : /* hope they have errno set */
1140                        case RPC_SYSTEMERROR    : break;
1141
1142                        default                 : errno = EIO;          break;
1143                }
1144        } else {
1145                rval = 0;
1146        }
1147
1148        /* release the transaction back into the pool */
1149        rpcUdpXactPoolPut(xact);
1150
1151        if (rval && !errno)
1152                errno = EIO;
1153
1154        return rval;
1155}
1156
1157/* Check the 'age' of a node's stats
1158 * and read the attributes from the server
1159 * if necessary.
1160 *
1161 * ARGS:        node    node to update
1162 *                      force   enforce updating ignoring
1163 *                                      the timestamp/age
1164 *
1165 * RETURNS:     0 on success,
1166 *                      -1 on failure with errno set
1167 */
1168
1169static int
1170updateAttr(NfsNode node, int force)
1171{
1172
1173        if (force
1174#ifdef CONFIG_ATTR_LIFETIME
1175                || (nowSeconds() - node->age > CONFIG_ATTR_LIFETIME)
1176#endif
1177                ) {
1178                if ( nfscall(node->nfs->server,
1179                                          NFSPROC_GETATTR,
1180                                          (xdrproc_t)xdr_nfs_fh,        &SERP_FILE(node),
1181                                          (xdrproc_t)xdr_attrstat, &node->serporid) )
1182                return -1;
1183
1184                if ( NFS_OK != node->serporid.status ) {
1185                        errno = node->serporid.status;
1186                        return -1;
1187                }
1188
1189                node->age = nowSeconds();
1190        }
1191       
1192        return 0;
1193}
1194
1195/*
1196 * IP address helper. Note that we avoid
1197 * gethostbyname() since it's not reentrant.
1198 *
1199 * initialize a sockaddr_in from a
1200 * [<uid>'.'<gid>'@']<host>':'<path>" string and let
1201 * pPath point to the <path> part; retrieve the optional
1202 * uid/gids
1203 *
1204 * ARGS:        see description above
1205 *
1206 * RETURNS:     0 on success,
1207 *                      -1 on failure with errno set
1208 */
1209static int
1210buildIpAddr(u_long *puid, u_long *pgid,
1211                        char **pHost, struct sockaddr_in *psa,
1212                        char **pPath)
1213{
1214char    host[30];
1215char    *chpt = *pPath;
1216char    *path;
1217int             len;
1218
1219        if ( !chpt ) {
1220                errno = EINVAL;
1221                return -1;
1222        }
1223
1224        /* look for the optional uid/gid */
1225        if ( (chpt = strchr(chpt, UIDSEP)) ) {
1226                if ( 2 != sscanf(*pPath,"%li.%li",puid,pgid) ) {
1227                        errno = EINVAL;
1228                        return -1;
1229                }
1230                chpt++;
1231        } else {
1232                *puid = RPCIOD_DEFAULT_ID;
1233                *pgid = RPCIOD_DEFAULT_ID;
1234                chpt  = *pPath;
1235        }
1236        if ( pHost )
1237                *pHost = chpt;
1238
1239        /* split the device name which is in the form
1240         *
1241         * <host_ip> ':' <path>
1242         *
1243         * into its components using a local buffer
1244         */
1245
1246        if ( !(path = strchr(chpt, HOSTDELIM)) ||
1247              (len  = path - chpt) >= sizeof(host) - 1 ) {
1248                errno = EINVAL;
1249                return -1;
1250        }
1251        /* point to path beyond ':' */
1252        path++;
1253
1254        strncpy(host, chpt, len);
1255        host[len]=0;
1256
1257        if ( ! inet_pton(AF_INET, host, &psa->sin_addr) ) {
1258                errno = ENXIO;
1259                return -1;
1260        }
1261
1262        psa->sin_family = AF_INET;
1263        psa->sin_port   = 0;
1264        *pPath          = path;
1265        return 0;
1266}
1267
1268/* wrapper similar to nfscall.
1269 * However, since it is not used
1270 * very often, the simpler and less
1271 * efficient rpcUdpCallRp API is used.
1272 *
1273 * ARGS:        see 'nfscall()' above
1274 *
1275 * RETURNS:     RPC status
1276 */
1277static enum clnt_stat
1278mntcall(
1279        struct sockaddr_in      *psrvr,
1280        int                                     proc,
1281        xdrproc_t                       xargs,
1282        void *                          pargs,
1283        xdrproc_t                       xres,
1284        void *                          pres,
1285        u_long                          uid,
1286        u_long                          gid)
1287{
1288#ifdef MOUNT_V1_PORT
1289int                                     retry;
1290#endif
1291enum clnt_stat          stat = RPC_FAILED;
1292
1293#ifdef MOUNT_V1_PORT
1294        /* if the portmapper fails, retry a fixed port */
1295        for (retry = 1, psrvr->sin_port = 0, stat = RPC_FAILED;
1296                 retry >= 0 && stat;
1297                 stat && (psrvr->sin_port = htons(MOUNT_V1_PORT)), retry-- )
1298#endif
1299                stat  = rpcUdpCallRp(
1300                                                psrvr,
1301                                                MOUNTPROG,
1302                                                MOUNTVERS,
1303                                                proc,
1304                                                xargs,
1305                                                pargs,
1306                                                xres,
1307                                                pres,
1308                                                uid,
1309                                                gid,
1310                                                MNTCALL_TIMEOUT
1311                                );
1312        return stat;
1313}
1314
1315/*****************************************
1316        RTEMS File System Operations for NFS
1317 *****************************************/
1318
1319#if 0 /* for reference */
1320
1321struct rtems_filesystem_location_info_tt
1322{
1323   void                                 *node_access;
1324   rtems_filesystem_file_handlers_r     *handlers;
1325   rtems_filesystem_operations_table    *ops;
1326   rtems_filesystem_mount_table_entry_t *mt_entry;
1327};
1328
1329#endif
1330
1331/*
1332 * Evaluate a path letting 'pathloc' travel along.
1333 *
1334 * The important semantics of this operation are:
1335 *
1336 * If this routine returns -1, the caller assumes
1337 * pathloc to be _invalid_ and hence it will not
1338 * invoke rtems_filesystem_freenode() on it.
1339 *
1340 * OTOH, if evalpath returns 0,
1341 * rtems_filesystem_freenode() will eventually be
1342 * called which results in our freeing the associated
1343 * NfsNode attached to node_access.
1344 *
1345 * Therefore, this routine will _always_ allocate
1346 * a NfsNode and pass it out to *pathloc (provided
1347 * that the evaluation succeeds).
1348 *
1349 * However, if the evaluation finds that it has to
1350 * step across FS boundaries (mount point or a symlink
1351 * pointing outside), the NfsNode is destroyed
1352 * before passing control to the new FS' evalpath_h()
1353 *
1354 */
1355       
1356STATIC int nfs_do_evalpath(
1357        const char                        *pathname,      /* IN     */
1358        void                              *arg,
1359        rtems_filesystem_location_info_t  *pathloc,       /* IN/OUT */
1360        int                                                               forMake
1361)
1362{
1363char                    *del = 0, *part;
1364int                             e = 0;
1365NfsNode                 node   = pathloc->node_access;
1366char                    *p     = malloc(MAXPATHLEN+1);
1367Nfs                             nfs    = (Nfs)pathloc->mt_entry->fs_info;
1368RpcUdpServer    server = nfs->server;
1369unsigned long   flags;
1370#if DEBUG & DEBUG_COUNT_NODES
1371unsigned long   niu,siu;
1372#endif
1373
1374        if ( !p ) {
1375                e = ENOMEM;
1376                goto cleanup;
1377        }
1378        strcpy(p, pathname);
1379
1380        LOCK(nfsGlob.lock);
1381        node = nfsNodeClone(node);
1382        UNLOCK(nfsGlob.lock);
1383
1384        /* from here on, the NFS is protected from being unmounted
1385         * since the node refcount is > 1
1386         */
1387       
1388        /* clone the node */
1389        if ( !node ) {
1390                /* nodeClone sets errno */
1391                pathloc->node_access = 0;
1392                if ( ! (e = errno) ) {
1393                        /* if we have no node, e must not be zero! */
1394                        e = ENOMEM;
1395                }
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  rtems_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        nfs = nfsCreate(nfsServer);
1979        assert( nfs );
1980        nfsServer = 0;
1981
1982        nfs->uid  = uid;
1983        nfs->gid  = gid;
1984
1985        /* that seemed to work - we now create the root node
1986         * and we also must obtain the root node attributes
1987         */
1988        rootNode = nfsNodeCreate(nfs, &fhstat.fhstatus_u.fhs_fhandle);
1989        assert( rootNode );
1990
1991        if ( updateAttr(rootNode, 1 /* force */) ) {
1992                e = errno;
1993                goto cleanup;
1994        }
1995
1996        /* looks good so far */
1997
1998        mt_entry->mt_fs_root.node_access = rootNode;
1999
2000        rootNode = 0;
2001
2002        mt_entry->mt_fs_root.ops                 = &nfs_fs_ops;
2003        mt_entry->mt_fs_root.handlers    = &nfs_dir_file_handlers;
2004        mt_entry->pathconf_limits_and_options = nfs_limits_and_options;
2005
2006        LOCK(nfsGlob.llock);
2007                nfsGlob.num_mounted_fs++;
2008                /* allocate a new ID for this FS */
2009                nfs->id = nfsGlob.fs_ids++;
2010        UNLOCK(nfsGlob.llock);
2011
2012        mt_entry->fs_info                                = nfs;
2013        nfs->mt_entry                                    = mt_entry;
2014        nfs = 0;
2015
2016        e = 0;
2017
2018cleanup:
2019        if (nfs)
2020                nfsDestroy(nfs);
2021        if (nfsServer)
2022                rpcUdpServerDestroy(nfsServer);
2023        if (rootNode)
2024                nfsNodeDestroy(rootNode);
2025        if (e)
2026                rtems_set_errno_and_return_minus_one(e);
2027        else
2028                return 0;
2029}
2030
2031/* This op is called when they try to unmount THIS fs */
2032STATIC int nfs_fsunmount_me(
2033        rtems_filesystem_mount_table_entry_t *mt_entry    /* in */
2034)
2035{
2036enum clnt_stat          stat;
2037struct sockaddr_in      saddr;
2038char                    *path = mt_entry->dev;
2039int                     nodesInUse;
2040u_long                  uid,gid;
2041int                     status;
2042
2043LOCK(nfsGlob.llock);
2044        nodesInUse = ((Nfs)mt_entry->fs_info)->nodesInUse;
2045
2046        if (nodesInUse > 1 /* one ref to the root node used by us */) {
2047                UNLOCK(nfsGlob.llock);
2048                fprintf(stderr,
2049                                "Refuse to unmount; there are still %i nodes in use (1 used by us)\n",
2050                                nodesInUse);
2051                rtems_set_errno_and_return_minus_one(EBUSY);
2052        }
2053
2054        status = buildIpAddr(&uid, &gid, 0, &saddr, &path);
2055        assert( !status );
2056       
2057        stat = mntcall( &saddr,
2058                                        MOUNTPROC_UMNT,
2059                                        (xdrproc_t)xdr_dirpath, &path,
2060                                        (xdrproc_t)xdr_void,     0,
2061                                    uid,
2062                                    gid
2063                                  );
2064
2065        if (stat) {
2066                UNLOCK(nfsGlob.llock);
2067                fprintf(stderr,"NFS UMOUNT -- %s\n", clnt_sperrno(stat));
2068                errno = EIO;
2069                return -1;
2070        }
2071
2072        nfsNodeDestroy(mt_entry->mt_fs_root.node_access);
2073        mt_entry->mt_fs_root.node_access = 0;
2074       
2075        nfsDestroy(mt_entry->fs_info);
2076        mt_entry->fs_info = 0;
2077
2078        nfsGlob.num_mounted_fs--;
2079UNLOCK(nfsGlob.llock);
2080
2081        return 0;
2082}
2083
2084/* OPTIONAL; may be NULL - BUT: CAUTION; mount() doesn't check
2085 * for this handler to be present - a fs bug
2086 * //NOTE: (10/25/2002) patch submitted and probably applied
2087 */
2088static rtems_filesystem_node_types_t nfs_node_type(
2089        rtems_filesystem_location_info_t    *pathloc      /* in */
2090)
2091{
2092NfsNode node = pathloc->node_access;
2093
2094        if (updateAttr(node, 0 /* only if old */))
2095                return -1;
2096
2097        switch( SERP_ATTR(node).type ) {
2098                default:
2099                        /* rtems has no value for 'unknown';
2100                         */
2101                case NFNON:
2102                case NFSOCK:
2103                case NFBAD:
2104                case NFFIFO:
2105                                break;
2106
2107
2108                case NFREG: return RTEMS_FILESYSTEM_MEMORY_FILE;
2109                case NFDIR:     return RTEMS_FILESYSTEM_DIRECTORY;
2110
2111                case NFBLK:
2112                case NFCHR:     return RTEMS_FILESYSTEM_DEVICE;
2113
2114                case NFLNK: return RTEMS_FILESYSTEM_SYM_LINK;
2115        }
2116        return -1;
2117}
2118
2119static int nfs_mknod(
2120        const char                        *path,       /* IN */
2121        mode_t                             mode,       /* IN */
2122        dev_t                              dev,        /* IN */
2123        rtems_filesystem_location_info_t  *pathloc     /* IN/OUT */
2124)
2125{
2126rtems_clock_time_value  now;
2127diropres                                res;
2128NfsNode                                 node = pathloc->node_access;
2129mode_t                                  type = S_IFMT & mode;
2130
2131        if (type != S_IFDIR && type != S_IFREG)
2132                rtems_set_errno_and_return_minus_one(ENOTSUP);
2133
2134#if DEBUG & DEBUG_SYSCALLS
2135        fprintf(stderr,"nfs_mknod: creating %s\n", path);
2136#endif
2137
2138        rtems_clock_get(RTEMS_CLOCK_GET_TIME_VALUE, &now);
2139
2140        SERP_ARGS(node).createarg.name                  = (filename)path;
2141        SERP_ARGS(node).createarg.attributes.mode       = mode;
2142        /* TODO: either use our uid or use the Nfs credentials */
2143        SERP_ARGS(node).createarg.attributes.uid        = 0;
2144        SERP_ARGS(node).createarg.attributes.gid        = 0;
2145        SERP_ARGS(node).createarg.attributes.size       = 0;
2146        SERP_ARGS(node).createarg.attributes.atime.seconds      = now.seconds;
2147        SERP_ARGS(node).createarg.attributes.atime.useconds     = now.microseconds;
2148        SERP_ARGS(node).createarg.attributes.mtime.seconds      = now.seconds;
2149        SERP_ARGS(node).createarg.attributes.mtime.useconds     = now.microseconds;
2150
2151        if ( nfscall( node->nfs->server,
2152                                                NFSPROC_CREATE,
2153                                                (xdrproc_t)xdr_createargs,      &SERP_FILE(node),
2154                                                (xdrproc_t)xdr_diropres,        &res)
2155                || (NFS_OK != (errno = res.status)) ) {
2156#if DEBUG & DEBUG_SYSCALLS
2157                perror("nfs_mknod");
2158#endif
2159                return -1;
2160        }
2161
2162        return 0;
2163}
2164
2165static int nfs_utime(
2166        rtems_filesystem_location_info_t  *pathloc,       /* IN */
2167        time_t                             actime,        /* IN */
2168        time_t                             modtime        /* IN */
2169)
2170{
2171sattr   arg;
2172
2173        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2174        arg.atime.seconds  = actime;
2175        arg.atime.useconds = 0;
2176        arg.mtime.seconds  = modtime;
2177        arg.mtime.useconds = 0;
2178
2179        return nfs_sattr(pathloc->node_access, &arg, SATTR_ATIME | SATTR_MTIME);
2180}
2181
2182static int nfs_symlink(
2183        rtems_filesystem_location_info_t  *loc,         /* IN */
2184        const char                        *link_name,   /* IN */
2185        const char                        *node_name
2186)
2187{
2188rtems_clock_time_value  now;
2189nfsstat                                 status;
2190NfsNode                                 node = loc->node_access;
2191
2192
2193#if DEBUG & DEBUG_SYSCALLS
2194        fprintf(stderr,"nfs_symlink: creating %s -> %s\n", link_name, node_name);
2195#endif
2196
2197        rtems_clock_get(RTEMS_CLOCK_GET_TIME_VALUE, &now);
2198
2199        SERP_ARGS(node).symlinkarg.name                 = (filename)link_name;
2200        SERP_ARGS(node).symlinkarg.to                           = (nfspath) node_name;
2201
2202        SERP_ARGS(node).symlinkarg.attributes.mode      = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
2203        /* TODO */
2204        SERP_ARGS(node).symlinkarg.attributes.uid       = 0;
2205        SERP_ARGS(node).symlinkarg.attributes.gid       = 0;
2206        SERP_ARGS(node).symlinkarg.attributes.size      = 0;
2207        SERP_ARGS(node).symlinkarg.attributes.atime.seconds      = now.seconds;
2208        SERP_ARGS(node).symlinkarg.attributes.atime.useconds = now.microseconds;
2209        SERP_ARGS(node).symlinkarg.attributes.mtime.seconds      = now.seconds;
2210        SERP_ARGS(node).symlinkarg.attributes.mtime.useconds = now.microseconds;
2211
2212        if ( nfscall( node->nfs->server,
2213                                                NFSPROC_SYMLINK,
2214                                                (xdrproc_t)xdr_symlinkargs,     &SERP_FILE(node),
2215                                                (xdrproc_t)xdr_nfsstat,         &status)
2216                || (NFS_OK != (errno = status)) ) {
2217#if DEBUG & DEBUG_SYSCALLS
2218                perror("nfs_symlink");
2219#endif
2220                return -1;
2221        }
2222
2223        return 0;
2224}
2225
2226static int nfs_do_readlink(
2227        rtems_filesystem_location_info_t  *loc,         /* IN  */       
2228        strbuf                                                    *psbuf                /* IN/OUT */
2229)
2230{
2231NfsNode                         node = loc->node_access;
2232Nfs                                     nfs  = node->nfs;
2233readlinkres_strbuf      rr;
2234int                                     wasAlloced;
2235int                                     rval;
2236
2237        rr.strbuf  = *psbuf;
2238
2239        wasAlloced = (0 == psbuf->buf);
2240
2241        if ( (rval = nfscall(nfs->server,
2242                                                        NFSPROC_READLINK,
2243                                                        (xdrproc_t)xdr_nfs_fh,                  &SERP_FILE(node),
2244                                                        (xdrproc_t)xdr_readlinkres_strbuf, &rr)) ) {
2245                if (wasAlloced)
2246                        xdr_free( (xdrproc_t)xdr_strbuf, (caddr_t)&rr.strbuf );
2247        }
2248
2249
2250        if (NFS_OK != rr.status) {
2251                if (wasAlloced)
2252                        xdr_free( (xdrproc_t)xdr_strbuf, (caddr_t)&rr.strbuf );
2253                rtems_set_errno_and_return_minus_one(rr.status);
2254        }
2255
2256        *psbuf = rr.strbuf;
2257
2258        return 0;
2259}
2260
2261static int nfs_readlink(
2262        rtems_filesystem_location_info_t  *loc,         /* IN  */       
2263        char                                                      *buf,                 /* OUT */
2264        size_t                                                    len
2265)
2266{
2267strbuf sbuf;
2268        sbuf.buf = buf;
2269        sbuf.max = len;
2270
2271        return nfs_do_readlink(loc, &sbuf);
2272}
2273
2274/* The semantics of this routine are:
2275 *
2276 * The caller submits a valid pathloc, i.e. it has
2277 * an NfsNode attached to node_access.
2278 * On return, pathloc points to the target node which
2279 * may or may not be an NFS node.
2280 * Hence, the original NFS node is released in either
2281 * case:
2282 *   - link evaluation fails; pathloc points to no valid node
2283 *   - link evaluation success; pathloc points to a new valid
2284 *     node. If it's an NFS node, a new NfsNode will be attached
2285 *     to node_access...
2286 */
2287
2288#define LINKVAL_BUFLEN                          (MAXPATHLEN+1)
2289#define RVAL_ERR_BUT_DONT_FREENODE      (-1)
2290#define RVAL_ERR_AND_DO_FREENODE        ( 1)
2291#define RVAL_OK                                         ( 0)
2292
2293static int nfs_eval_link(
2294        rtems_filesystem_location_info_t *pathloc,     /* IN/OUT */
2295        int                              flags         /* IN     */
2296)
2297{
2298rtems_filesystem_node_types_t   type;
2299char                                                    *buf = malloc(LINKVAL_BUFLEN);
2300int                                                             rval = RVAL_ERR_AND_DO_FREENODE;
2301
2302        if (!buf) {
2303                errno = ENOMEM;
2304                goto cleanup;
2305        }
2306
2307        /* in this loop, we must not use NFS specific ops as we might
2308         * step out of our FS during the process...
2309         * This algorithm should actually be performed by the
2310         * generic's evaluate_path routine :-(
2311         *
2312         * Unfortunately, there is no way of finding the
2313         * directory node who contains 'pathloc', however :-(
2314         */
2315        do {
2316                /* assume the generics have verified 'pathloc' to be
2317                 * a link...
2318                 */
2319                if ( !pathloc->ops->readlink_h ) {
2320                        errno = ENOTSUP;
2321                        goto cleanup;
2322                }
2323
2324                if ( pathloc->ops->readlink_h(pathloc, buf, LINKVAL_BUFLEN) ) {
2325                        goto cleanup;
2326                }
2327
2328#if DEBUG & DEBUG_EVALPATH
2329                fprintf(stderr, "link value is '%s'\n", buf);
2330#endif
2331
2332                /* is the link value an absolute path ? */
2333                if ( DELIM != *buf ) {
2334                        /* NO; a relative path */
2335
2336                        /* we must backup to the link's directory - we
2337                         * know only how to do that for NFS, however.
2338                         * In this special case, we can avoid recursion.
2339                         * Otherwise (i.e. if the link is on another FS),
2340                         * we must step into its eval_link_h().
2341                         */
2342                        if (locIsNfs(pathloc)) {
2343                                NfsNode node = pathloc->node_access;
2344                                int             err;
2345
2346                                memcpy( &SERP_FILE(node),
2347                                                &node->args.dir,
2348                                                sizeof(node->args.dir) );
2349
2350                                if (updateAttr(node, 1 /* force */))
2351                                        goto cleanup;
2352
2353                                if (SERP_ATTR(node).type != NFDIR) {
2354                                        errno = ENOTDIR;
2355                                        goto cleanup;
2356                                }
2357
2358                                pathloc->handlers = &nfs_dir_file_handlers;
2359
2360                                err = nfs_evalpath(buf, flags, pathloc);
2361
2362                                /* according to its semantics,
2363                                 * nfs_evalpath cloned the node attached
2364                                 * to pathloc. Hence we have to
2365                                 * release the old one (referring to
2366                                 * the link; the new clone has been
2367                                 * updated and refers to the link _value_).
2368                                 */
2369                                nfsNodeDestroy(node);
2370
2371                                if (err) {
2372                                        /* nfs_evalpath has set errno;
2373                                         * pathloc->node_access has no
2374                                         * valid node attached in this case
2375                                         */
2376                                        rval = RVAL_ERR_BUT_DONT_FREENODE;
2377                                        goto cleanup;
2378                                }
2379
2380                        } else {
2381                                if ( ! pathloc->ops->eval_link_h ) {
2382                                        errno = ENOTSUP;
2383                                        goto cleanup;
2384                                }
2385                                if (!pathloc->ops->eval_link_h(pathloc, flags)) {
2386                                        /* FS is responsible for freeing its pathloc->node_access
2387                                         * if necessary
2388                                         */
2389                                        rval = RVAL_ERR_BUT_DONT_FREENODE;
2390                                        goto cleanup;
2391                                }
2392                        }
2393                } else {
2394                        /* link points to an absolute path '/xxx' */
2395                               
2396                        /* release this node; filesystem_evaluate_path() will
2397                         * lookup a new one.
2398                         */
2399                        rtems_filesystem_freenode(pathloc);
2400
2401                        if (rtems_filesystem_evaluate_path(buf, flags, pathloc, 1)) {
2402                                /* If evalpath fails then there is no valid node
2403                                 * attached to pathloc; hence we must not attempt
2404                                 * to free the node
2405                                 */
2406                                rval = RVAL_ERR_BUT_DONT_FREENODE;
2407                                goto cleanup;
2408                        }
2409                }
2410
2411                if ( !pathloc->ops->node_type_h ) {
2412                        errno = ENOTSUP;
2413                        goto cleanup;
2414                }
2415
2416                type = pathloc->ops->node_type_h(pathloc);
2417
2418
2419                /* I dont know what to do about hard links */
2420        } while ( RTEMS_FILESYSTEM_SYM_LINK == type );
2421
2422        rval = RVAL_OK;
2423
2424cleanup:
2425
2426        free(buf);
2427
2428        if (RVAL_ERR_AND_DO_FREENODE == rval) {
2429                rtems_filesystem_freenode(pathloc);
2430                return -1;
2431        }
2432
2433        return rval;
2434}
2435
2436
2437struct _rtems_filesystem_operations_table nfs_fs_ops = {
2438                nfs_evalpath,           /* MANDATORY */
2439                nfs_evalformake,        /* MANDATORY; may set errno=ENOSYS and return -1 */
2440                nfs_link,                       /* OPTIONAL; may be NULL */
2441                nfs_unlink,                     /* OPTIONAL; may be NULL */
2442                nfs_node_type,          /* OPTIONAL; may be NULL; BUG in mount - no test!! */
2443                nfs_mknod,                      /* OPTIONAL; may be NULL */
2444                nfs_chown,                      /* OPTIONAL; may be NULL */
2445                nfs_freenode,           /* OPTIONAL; may be NULL; (release node_access) */
2446                nfs_mount,                      /* OPTIONAL; may be NULL */
2447                nfs_fsmount_me,         /* OPTIONAL; may be NULL -- but this makes NO SENSE */
2448                nfs_unmount,            /* OPTIONAL; may be NULL */
2449                nfs_fsunmount_me,       /* OPTIONAL; may be NULL */
2450                nfs_utime,                      /* OPTIONAL; may be NULL */
2451                nfs_eval_link,          /* OPTIONAL; may be NULL */
2452                nfs_symlink,            /* OPTIONAL; may be NULL */
2453                nfs_readlink,           /* OPTIONAL; may be NULL */
2454};
2455
2456/*****************************************
2457        File Handlers
2458
2459        NOTE: the FS generics expect a FS'
2460              evalpath_h() to switch the
2461                  pathloc->handlers according
2462                  to the pathloc/node's file
2463                  type.
2464                  We currently have 'file' and
2465                  'directory' handlers and very
2466                  few 'symlink' handlers.
2467
2468                  The handlers for each type are
2469                  implemented or #defined ZERO
2470                  in a 'nfs_file_xxx',
2471                  'nfs_dir_xxx', 'nfs_link_xxx'
2472                  sequence below this point.
2473
2474                  In some cases, a common handler,
2475                  can be used for all file types.
2476                  It is then simply called
2477                  'nfs_xxx'.
2478 *****************************************/
2479
2480
2481#if 0
2482/* from rtems/libio.h for convenience */
2483struct rtems_libio_tt {
2484                rtems_driver_name_t              *driver;
2485                off_t                             size;      /* size of file */
2486                off_t                             offset;    /* current offset into file */
2487                uint32_t                          flags;
2488                rtems_filesystem_location_info_t  pathinfo;
2489                Objects_Id                        sem;
2490                uint32_t                          data0;     /* private to "driver" */
2491                void                             *data1;     /* ... */
2492                void                             *file_info; /* used by file handlers */
2493                rtems_filesystem_file_handlers_r *handlers;  /* type specific handlers */
2494};
2495#endif
2496
2497/* stateless NFS protocol makes this trivial */
2498static int nfs_file_open(
2499        rtems_libio_t *iop,
2500        const char    *pathname,
2501        uint32_t      flag,
2502        uint32_t      mode
2503)
2504{
2505        iop->file_info = 0;
2506        return 0;
2507}
2508
2509/* reading directories is not stateless; we must
2510 * remember the last 'read' position, i.e.
2511 * the server 'cookie'. We do manage this information
2512 * attached to the iop->file_info.
2513 */
2514static int nfs_dir_open(
2515        rtems_libio_t *iop,
2516        const char    *pathname,
2517        uint32_t      flag,
2518        uint32_t      mode
2519)
2520{
2521NfsNode         node = iop->pathinfo.node_access;
2522DirInfo         di;
2523
2524        /* create a readdirargs object and copy the file handle;
2525         * attach to the file_info.
2526         */
2527
2528        di = (DirInfo) malloc(sizeof(*di));
2529        iop->file_info = di;
2530
2531        if ( !di  ) {
2532                errno = ENOMEM;
2533                return -1;
2534        }
2535
2536        memcpy( &di->readdirargs.dir,
2537                        &SERP_FILE(node),
2538                        sizeof(di->readdirargs.dir) );
2539
2540        /* rewind cookie */
2541        memset( &di->readdirargs.cookie,
2542                0,
2543                sizeof(di->readdirargs.cookie) );
2544
2545        di->eofreached = FALSE;
2546
2547        return 0;
2548}
2549
2550#define nfs_link_open 0
2551
2552static int nfs_file_close(
2553        rtems_libio_t *iop
2554)
2555{
2556        return 0;
2557}
2558
2559static int nfs_dir_close(
2560        rtems_libio_t *iop
2561)
2562{
2563        free(iop->file_info);
2564        iop->file_info = 0;
2565        return 0;
2566}
2567
2568#define nfs_link_close 0
2569
2570static ssize_t nfs_file_read(
2571        rtems_libio_t *iop,
2572        void          *buffer,
2573        size_t        count
2574)
2575{
2576readres rr;
2577NfsNode node = iop->pathinfo.node_access;
2578Nfs             nfs  = node->nfs;
2579
2580        if (count > NFS_MAXDATA)
2581                count = NFS_MAXDATA;
2582
2583        SERP_ARGS(node).readarg.offset          = iop->offset;
2584        SERP_ARGS(node).readarg.count           = count;
2585        SERP_ARGS(node).readarg.totalcount      = 0xdeadbeef;
2586
2587        rr.readres_u.reply.data.data_val        = buffer;
2588
2589        if ( nfscall(   nfs->server,
2590                                                NFSPROC_READ,
2591                                                (xdrproc_t)xdr_readargs,        &SERP_FILE(node),
2592                                                (xdrproc_t)xdr_readres, &rr) ) {
2593                return -1;
2594        }
2595
2596
2597        if (NFS_OK != rr.status) {
2598                rtems_set_errno_and_return_minus_one(rr.status);
2599        }
2600
2601#if DEBUG & DEBUG_SYSCALLS
2602        fprintf(stderr,
2603                        "Read %i (asked for %i) bytes from offset %i to 0x%08x\n",
2604                        rr.readres_u.reply.data.data_len,
2605                        count,
2606                        iop->offset,
2607                        rr.readres_u.reply.data.data_val);
2608#endif
2609
2610
2611        return rr.readres_u.reply.data.data_len;
2612}
2613
2614/* this is called by readdir() / getdents() */
2615static ssize_t nfs_dir_read(
2616        rtems_libio_t *iop,
2617        void          *buffer,
2618        size_t        count
2619)
2620{
2621DirInfo                 di     = iop->file_info;
2622RpcUdpServer    server = ((Nfs)iop->pathinfo.mt_entry->fs_info)->server;
2623
2624        if ( di->eofreached )
2625                return 0;
2626
2627        di->ptr = di->buf = buffer;
2628
2629        /* align + round down the buffer */
2630        count &= ~ (DIRENT_HEADER_SIZE - 1);
2631        di->len = count;
2632
2633#if 0
2634        /* now estimate the number of entries we should ask for */
2635        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2636
2637        /* estimate the encoded size that might take up */
2638        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2639#else
2640        /* integer arithmetics are better done the other way round */
2641        count *= dirres_entry_size + CONFIG_AVG_NAMLEN;
2642        count /= DIRENT_HEADER_SIZE + CONFIG_AVG_NAMLEN;
2643#endif
2644
2645        if (count > NFS_MAXDATA)
2646                count = NFS_MAXDATA;
2647
2648        di->readdirargs.count = count;
2649
2650#if DEBUG & DEBUG_READDIR
2651        fprintf(stderr,
2652                        "Readdir: asking for %i XDR bytes, buffer is %i\n",
2653                        count, di->len);
2654#endif
2655
2656        if ( nfscall(
2657                                        server,
2658                                        NFSPROC_READDIR,
2659                                        (xdrproc_t)xdr_readdirargs, &di->readdirargs,
2660                                        (xdrproc_t)xdr_dir_info,    di) ) {
2661                return -1;
2662        }
2663
2664
2665        if (NFS_OK != di->status) {
2666                rtems_set_errno_and_return_minus_one(di->status);
2667        }
2668
2669        return (char*)di->ptr - (char*)buffer;
2670}
2671
2672#define nfs_link_read 0
2673
2674static ssize_t nfs_file_write(
2675        rtems_libio_t *iop,
2676        const void    *buffer,
2677        size_t        count
2678)
2679{
2680NfsNode         node = iop->pathinfo.node_access;
2681Nfs                     nfs  = node->nfs;
2682int                     e;
2683
2684        if (count > NFS_MAXDATA)
2685                count = NFS_MAXDATA;
2686
2687
2688        SERP_ARGS(node).writearg.beginoffset   = 0xdeadbeef;
2689        if ( LIBIO_FLAGS_APPEND & iop->flags ) {
2690                if ( updateAttr(node, 0) ) {
2691                        return -1;
2692                }
2693                SERP_ARGS(node).writearg.offset            = SERP_ATTR(node).size;
2694        } else {
2695                SERP_ARGS(node).writearg.offset            = iop->offset;
2696        }
2697        SERP_ARGS(node).writearg.totalcount        = 0xdeadbeef;
2698        SERP_ARGS(node).writearg.data.data_len = count;
2699        SERP_ARGS(node).writearg.data.data_val = (void*)buffer;
2700
2701        /* write XDR buffer size will be chosen by nfscall based
2702         * on the PROC specifier
2703         */
2704
2705        if ( nfscall(   nfs->server,
2706                                                NFSPROC_WRITE,
2707                                                (xdrproc_t)xdr_writeargs,       &SERP_FILE(node),
2708                                                (xdrproc_t)xdr_attrstat,        &node->serporid) ) {
2709                return -1;
2710        }
2711
2712
2713        if (NFS_OK != (e=node->serporid.status) ) {
2714                /* try at least to recover the current attributes */
2715                updateAttr(node, 1 /* force */);
2716                rtems_set_errno_and_return_minus_one(e);
2717        }
2718
2719        node->age = nowSeconds();
2720
2721        return count;
2722}
2723
2724#define nfs_dir_write  0
2725#define nfs_link_write 0
2726
2727/* IOCTL is unneeded/unsupported */
2728#ifdef DECLARE_BODY
2729static int nfs_file_ioctl(
2730        rtems_libio_t *iop,
2731        uint32_t      command,
2732        void          *buffer
2733)DECLARE_BODY
2734#else
2735#define nfs_file_ioctl 0
2736#define nfs_dir_ioctl 0
2737#define nfs_link_ioctl 0
2738#endif
2739
2740static rtems_off64_t nfs_file_lseek(
2741        rtems_libio_t *iop,
2742        rtems_off64_t  length,
2743        int            whence
2744)
2745{
2746#if DEBUG & DEBUG_SYSCALLS
2747        fprintf(stderr,
2748                        "lseek to %i (length %i, whence %i)\n",
2749                        iop->offset,
2750                        length,
2751                        whence);
2752#endif
2753        if ( SEEK_END == whence ) {
2754                /* rtems (4.6.2) libcsupport code 'lseek' uses iop->size to
2755                 * compute the offset. We don't want to track the file size
2756                 * by updating 'iop->size' constantly.
2757                 * Since lseek is the only place using iop->size, we work
2758                 * around this by tweaking the offset here...
2759                 */
2760                NfsNode node = iop->pathinfo.node_access;
2761                fattr   *fa  = &SERP_ATTR(node);
2762
2763                if (updateAttr(node, 0 /* only if old */)) {
2764                        return -1;
2765                }
2766                iop->offset = fa->size;
2767        }
2768
2769        /* this is particularly easy :-) */
2770        return iop->offset;
2771}
2772
2773static rtems_off64_t nfs_dir_lseek(
2774        rtems_libio_t *iop,
2775        rtems_off64_t  length,
2776        int            whence
2777)
2778{
2779DirInfo di = iop->file_info;
2780
2781        /* we don't support anything other than
2782         * rewinding
2783         */
2784        if (SEEK_SET != whence || 0 != length) {
2785                errno = ENOTSUP;
2786                return -1;
2787        }
2788
2789        /* rewind cookie */
2790        memset( &di->readdirargs.cookie,
2791                0,
2792                sizeof(di->readdirargs.cookie) );
2793
2794        di->eofreached = FALSE;
2795
2796        return iop->offset;
2797}
2798
2799#define nfs_link_lseek 0
2800
2801#if 0   /* structure types for reference */
2802struct fattr {
2803                ftype type;
2804                u_int mode;
2805                u_int nlink;
2806                u_int uid;
2807                u_int gid;
2808                u_int size;
2809                u_int blocksize;
2810                u_int rdev;
2811                u_int blocks;
2812                u_int fsid;
2813                u_int fileid;
2814                nfstime atime;
2815                nfstime mtime;
2816                nfstime ctime;
2817};
2818
2819struct  stat
2820{
2821                dev_t         st_dev;
2822                ino_t         st_ino;
2823                mode_t        st_mode;
2824                nlink_t       st_nlink;
2825                uid_t         st_uid;
2826                gid_t         st_gid;
2827                dev_t         st_rdev;
2828                rtems_off64_t st_size;
2829                /* SysV/sco doesn't have the rest... But Solaris, eabi does.  */
2830#if defined(__svr4__) && !defined(__PPC__) && !defined(__sun__)
2831                time_t        st_atime;
2832                time_t        st_mtime;
2833                time_t        st_ctime;
2834#else
2835                time_t        st_atime;
2836                long          st_spare1;
2837                time_t        st_mtime;
2838                long          st_spare2;
2839                time_t        st_ctime;
2840                long          st_spare3;
2841                long          st_blksize;
2842                long          st_blocks;
2843                long      st_spare4[2];
2844#endif
2845};
2846#endif
2847
2848/* common for file/dir/link */
2849static int nfs_fstat(
2850        rtems_filesystem_location_info_t *loc,
2851        struct stat                      *buf
2852)
2853{
2854NfsNode node = loc->node_access;
2855fattr   *fa  = &SERP_ATTR(node);
2856
2857        if (updateAttr(node, 0 /* only if old */)) {
2858                return -1;
2859        }
2860
2861/* done by caller
2862        memset(buf, 0, sizeof(*buf));
2863 */
2864
2865        /* translate */
2866
2867        /* one of the branches hopefully is optimized away */
2868        if (sizeof(ino_t) < sizeof(u_int)) {
2869        buf->st_dev             = NFS_MAKE_DEV_T_INO_HACK((NfsNode)loc->node_access);
2870        } else {
2871        buf->st_dev             = NFS_MAKE_DEV_T((NfsNode)loc->node_access);
2872        }
2873        buf->st_mode    = fa->mode;
2874        buf->st_nlink   = fa->nlink;
2875        buf->st_uid             = fa->uid;
2876        buf->st_gid             = fa->gid;
2877        buf->st_size    = fa->size;
2878        /* Set to "preferred size" of this NFS client implementation */
2879        buf->st_blksize = nfsStBlksize ? nfsStBlksize : fa->blocksize;
2880        buf->st_rdev    = fa->rdev;
2881        buf->st_blocks  = fa->blocks;
2882        buf->st_ino     = fa->fileid;
2883        buf->st_atime   = fa->atime.seconds;
2884        buf->st_mtime   = fa->mtime.seconds;
2885        buf->st_ctime   = fa->ctime.seconds;
2886
2887#if 0 /* NFS should return the modes */
2888        switch(fa->type) {
2889                default:
2890                case NFNON:
2891                case NFBAD:
2892                                break;
2893
2894                case NFSOCK: buf->st_mode |= S_IFSOCK; break;
2895                case NFFIFO: buf->st_mode |= S_IFIFO;  break;
2896                case NFREG : buf->st_mode |= S_IFREG;  break;
2897                case NFDIR : buf->st_mode |= S_IFDIR;  break;
2898                case NFBLK : buf->st_mode |= S_IFBLK;  break;
2899                case NFCHR : buf->st_mode |= S_IFCHR;  break;
2900                case NFLNK : buf->st_mode |= S_IFLNK;  break;
2901        }
2902#endif
2903
2904        return 0;
2905}
2906
2907/* a helper which does the real work for
2908 * a couple of handlers (such as chmod,
2909 * ftruncate or utime)
2910 */
2911static int
2912nfs_sattr(NfsNode node, sattr *arg, u_long mask)
2913{
2914
2915rtems_clock_time_value  now;
2916nfstime                                 nfsnow, t;
2917int                                             e;
2918u_int                                   mode;
2919
2920        if (updateAttr(node, 0 /* only if old */))
2921                return -1;
2922
2923        rtems_clock_get(RTEMS_CLOCK_GET_TIME_VALUE, &now);
2924
2925        /* TODO: add rtems EPOCH - UNIX EPOCH seconds */
2926        nfsnow.seconds  = now.seconds;
2927        nfsnow.useconds = now.microseconds;
2928
2929        /* merge permission bits into existing type bits */
2930        mode = SERP_ATTR(node).mode;
2931        if (mask & SATTR_MODE) {
2932                mode &= S_IFMT;
2933                mode |= arg->mode & ~S_IFMT;
2934        } else {
2935                mode = -1;
2936        }
2937        SERP_ARGS(node).sattrarg.attributes.mode  = mode;
2938
2939        SERP_ARGS(node).sattrarg.attributes.uid   =
2940                (mask & SATTR_UID)  ? arg->uid : -1;
2941
2942        SERP_ARGS(node).sattrarg.attributes.gid   =
2943                (mask & SATTR_GID)  ? arg->gid : -1;
2944
2945        SERP_ARGS(node).sattrarg.attributes.size  =
2946                (mask & SATTR_SIZE) ? arg->size : -1;
2947
2948        if (mask & SATTR_ATIME)
2949                t = arg->atime;
2950        else if (mask & SATTR_TOUCHA)
2951                t = nfsnow;
2952        else
2953                t.seconds = t.useconds = -1;
2954        SERP_ARGS(node).sattrarg.attributes.atime = t;
2955
2956        if (mask & SATTR_ATIME)
2957                t = arg->mtime;
2958        else if (mask & SATTR_TOUCHA)
2959                t = nfsnow;
2960        else
2961                t.seconds = t.useconds = -1;
2962        SERP_ARGS(node).sattrarg.attributes.mtime = t;
2963
2964        node->serporid.status = NFS_OK;
2965
2966        if ( nfscall( node->nfs->server,
2967                                                NFSPROC_SETATTR,
2968                                                (xdrproc_t)xdr_sattrargs,       &SERP_FILE(node),
2969                                                (xdrproc_t)xdr_attrstat,        &node->serporid) ) {
2970#if DEBUG & DEBUG_SYSCALLS
2971                fprintf(stderr,
2972                                "nfs_sattr (mask 0x%08x): %s",
2973                                mask,
2974                                strerror(errno));
2975#endif
2976                return -1;
2977        }
2978
2979        if (NFS_OK != (e=node->serporid.status) ) {
2980#if DEBUG & DEBUG_SYSCALLS
2981                fprintf(stderr,"nfs_sattr: %s\n",strerror(e));
2982#endif
2983                /* try at least to recover the current attributes */
2984                updateAttr(node, 1 /* force */);
2985                rtems_set_errno_and_return_minus_one(e);
2986        }
2987
2988        node->age = nowSeconds();
2989
2990        return 0;
2991}
2992
2993
2994/* common for file/dir/link */
2995static int nfs_fchmod(
2996        rtems_filesystem_location_info_t *loc,
2997        mode_t                            mode
2998)
2999{
3000sattr   arg;
3001
3002        arg.mode = mode;
3003        return nfs_sattr(loc->node_access, &arg, SATTR_MODE);
3004       
3005}
3006
3007/* just set the size attribute to 'length'
3008 * the server will take care of the rest :-)
3009 */
3010static int nfs_file_ftruncate(
3011        rtems_libio_t *iop,
3012        rtems_off64_t  length
3013)
3014{
3015sattr                                   arg;
3016
3017        arg.size = length;
3018        /* must not modify any other attribute; if we are not the owner
3019         * of the file or directory but only have write access changing
3020         * any attribute besides 'size' will fail...
3021         */
3022        return nfs_sattr(iop->pathinfo.node_access,
3023                                         &arg,
3024                                         SATTR_SIZE);
3025}
3026
3027#define nfs_dir_ftruncate 0
3028#define nfs_link_ftruncate 0
3029
3030/* not implemented */
3031#ifdef DECLARE_BODY
3032static int nfs_file_fpathconf(
3033        rtems_libio_t *iop,
3034        int name
3035)DECLARE_BODY
3036#else
3037#define nfs_file_fpathconf 0
3038#define nfs_dir_fpathconf 0
3039#define nfs_link_fpathconf 0
3040#endif
3041
3042/* unused */
3043#ifdef DECLARE_BODY
3044static int nfs_file_fsync(
3045        rtems_libio_t *iop
3046)DECLARE_BODY
3047#else
3048#define nfs_file_fsync 0
3049#define nfs_dir_fsync 0
3050#define nfs_link_fsync 0
3051#endif
3052
3053/* unused */
3054#ifdef DECLARE_BODY
3055static int nfs_file_fdatasync(
3056        rtems_libio_t *iop
3057)DECLARE_BODY
3058#else
3059#define nfs_file_fdatasync 0
3060#define nfs_dir_fdatasync 0
3061#define nfs_link_fdatasync 0
3062#endif
3063
3064/* unused */
3065#ifdef DECLARE_BODY
3066static int nfs_file_fcntl(
3067        int            cmd,
3068        rtems_libio_t *iop
3069)DECLARE_BODY
3070#else
3071#define nfs_file_fcntl 0
3072#define nfs_dir_fcntl 0
3073#define nfs_link_fcntl 0
3074#endif
3075
3076/* files and symlinks are removed
3077 * by the common nfs_unlink() routine.
3078 * NFS has a different NFSPROC_RMDIR
3079 * call, though...
3080 */
3081static int nfs_dir_rmnod(
3082        rtems_filesystem_location_info_t      *pathloc       /* IN */
3083)
3084{
3085        return nfs_do_unlink(pathloc, NFSPROC_RMDIR);
3086}
3087
3088/* the file handlers table */
3089static
3090struct _rtems_filesystem_file_handlers_r nfs_file_file_handlers = {
3091                nfs_file_open,                  /* OPTIONAL; may be NULL */
3092                nfs_file_close,                 /* OPTIONAL; may be NULL */
3093                nfs_file_read,                  /* OPTIONAL; may be NULL */
3094                nfs_file_write,                 /* OPTIONAL; may be NULL */
3095                nfs_file_ioctl,                 /* OPTIONAL; may be NULL */
3096                nfs_file_lseek,                 /* OPTIONAL; may be NULL */
3097                nfs_fstat,                              /* OPTIONAL; may be NULL */
3098                nfs_fchmod,                             /* OPTIONAL; may be NULL */
3099                nfs_file_ftruncate,             /* OPTIONAL; may be NULL */
3100                nfs_file_fpathconf,             /* OPTIONAL; may be NULL - UNUSED */
3101                nfs_file_fsync,                 /* OPTIONAL; may be NULL */
3102                nfs_file_fdatasync,             /* OPTIONAL; may be NULL */
3103                nfs_file_fcntl,                 /* OPTIONAL; may be NULL */
3104                nfs_unlink,                             /* OPTIONAL; may be NULL */
3105};
3106
3107/* the directory handlers table */
3108static
3109struct _rtems_filesystem_file_handlers_r nfs_dir_file_handlers = {
3110                nfs_dir_open,                   /* OPTIONAL; may be NULL */
3111                nfs_dir_close,                  /* OPTIONAL; may be NULL */
3112                nfs_dir_read,                   /* OPTIONAL; may be NULL */
3113                nfs_dir_write,                  /* OPTIONAL; may be NULL */
3114                nfs_dir_ioctl,                  /* OPTIONAL; may be NULL */
3115                nfs_dir_lseek,                  /* OPTIONAL; may be NULL */
3116                nfs_fstat,                              /* OPTIONAL; may be NULL */
3117                nfs_fchmod,                             /* OPTIONAL; may be NULL */
3118                nfs_dir_ftruncate,              /* OPTIONAL; may be NULL */
3119                nfs_dir_fpathconf,              /* OPTIONAL; may be NULL - UNUSED */
3120                nfs_dir_fsync,                  /* OPTIONAL; may be NULL */
3121                nfs_dir_fdatasync,              /* OPTIONAL; may be NULL */
3122                nfs_dir_fcntl,                  /* OPTIONAL; may be NULL */
3123                nfs_dir_rmnod,                          /* OPTIONAL; may be NULL */
3124};
3125
3126/* the link handlers table */
3127static
3128struct _rtems_filesystem_file_handlers_r nfs_link_file_handlers = {
3129                nfs_link_open,                  /* OPTIONAL; may be NULL */
3130                nfs_link_close,                 /* OPTIONAL; may be NULL */
3131                nfs_link_read,                  /* OPTIONAL; may be NULL */
3132                nfs_link_write,                 /* OPTIONAL; may be NULL */
3133                nfs_link_ioctl,                 /* OPTIONAL; may be NULL */
3134                nfs_link_lseek,                 /* OPTIONAL; may be NULL */
3135                nfs_fstat,                              /* OPTIONAL; may be NULL */
3136                nfs_fchmod,                             /* OPTIONAL; may be NULL */
3137                nfs_link_ftruncate,             /* OPTIONAL; may be NULL */
3138                nfs_link_fpathconf,             /* OPTIONAL; may be NULL - UNUSED */
3139                nfs_link_fsync,                 /* OPTIONAL; may be NULL */
3140                nfs_link_fdatasync,             /* OPTIONAL; may be NULL */
3141                nfs_link_fcntl,                 /* OPTIONAL; may be NULL */
3142                nfs_unlink,                             /* OPTIONAL; may be NULL */
3143};
3144
3145/* we need a dummy driver entry table to get a
3146 * major number from the system
3147 */
3148static
3149rtems_device_driver nfs_initialize(
3150                rtems_device_major_number       major,
3151                rtems_device_minor_number       minor,
3152                void                                            *arg
3153)
3154{
3155        /* we don't really use this routine because
3156     * we cannot supply an argument (contrary
3157     * to what the 'arg' parameter suggests - it
3158     * is always set to 0 by the generics :-()
3159     * and because we don't want the user to
3160     * have to deal with the major number (which
3161     * OTOH is something WE are interested in. The
3162     * only reason for using this API was getting
3163     * a major number, after all).
3164     *
3165         * Something must be present, however, to
3166         * reserve a slot in the driver table.
3167         */
3168        return RTEMS_SUCCESSFUL;
3169}
3170
3171static rtems_driver_address_table       drvNfs = {
3172                nfs_initialize,
3173                0,                                      /* open    */
3174                0,                                      /* close   */
3175                0,                                      /* read    */
3176                0,                                      /* write   */
3177                0                                       /* control */
3178};
3179
3180/* Dump a list of the currently mounted NFS to a  file */
3181int
3182nfsMountsShow(FILE *f)
3183{
3184char    *mntpt = 0;
3185Nfs             nfs;
3186
3187        if (!f)
3188                f = stdout;
3189
3190        if ( !(mntpt=malloc(MAXPATHLEN)) ) {
3191                fprintf(stderr,"nfsMountsShow(): no memory\n");
3192                return -1;
3193        }
3194       
3195        fprintf(f,"Currently Mounted NFS:\n");
3196
3197        LOCK(nfsGlob.llock);
3198
3199        for (nfs = nfsGlob.mounted_fs; nfs; nfs=nfs->next) {
3200                fprintf(f,"%s on ", nfs->mt_entry->dev);
3201                if (rtems_filesystem_resolve_location(mntpt, MAXPATHLEN, &nfs->mt_entry->mt_fs_root))
3202                        fprintf(f,"<UNABLE TO LOOKUP MOUNTPOINT>\n");
3203                else
3204                        fprintf(f,"%s\n",mntpt);
3205        }
3206
3207        UNLOCK(nfsGlob.llock);
3208
3209        free(mntpt);
3210        return 0;
3211}
3212
3213/* convenience wrapper
3214 *
3215 * NOTE: this routine calls NON-REENTRANT
3216 *       gethostbyname() if the host is
3217 *       not in 'dot' notation.
3218 */
3219int
3220nfsMount(char *uidhost, char *path, char *mntpoint)
3221{
3222rtems_filesystem_mount_table_entry_t    *mtab;
3223struct stat                                                             st;
3224int                                                                             devl;
3225char                                                                    *host;
3226int                                                                             rval = -1;
3227char                                                                    *dev =  0;
3228
3229        if (!uidhost || !path || !mntpoint) {
3230                fprintf(stderr,"usage: nfsMount(""[uid.gid@]host"",""path"",""mountpoint"")\n");
3231                nfsMountsShow(stderr);
3232                return -1;
3233        }
3234
3235        if ( !(dev = malloc((devl=strlen(uidhost) + 20 + strlen(path)+1))) ) {
3236                fprintf(stderr,"nfsMount: out of memory\n");
3237                return -1;
3238        }
3239
3240        /* Try to create the mount point if nonexistent */
3241        if (stat(mntpoint, &st)) {
3242                if (ENOENT != errno) {
3243                        perror("nfsMount trying to create mount point - stat failed");
3244                        goto cleanup;
3245                } else if (mkdir(mntpoint,0777)) {
3246                        perror("nfsMount trying to create mount point");
3247                        goto cleanup;
3248                }
3249        }
3250
3251        if ( !(host=strchr(uidhost,UIDSEP)) ) {
3252                host = uidhost;
3253        } else {
3254                host++;
3255        }
3256
3257        if (isdigit(*host)) {
3258                /* avoid using gethostbyname */
3259                sprintf(dev,"%s:%s",uidhost,path);
3260        } else {
3261                struct hostent *h;
3262
3263                /* copy the uid part (hostname will be
3264                 * overwritten)
3265                 */
3266                strcpy(dev, uidhost);
3267
3268                /* NOTE NOTE NOTE: gethostbyname is NOT
3269                 * thread safe. This is UGLY
3270                 */
3271
3272/* BEGIN OF NON-THREAD SAFE REGION */
3273
3274                h = gethostbyname(host);
3275
3276                if ( !h ||
3277                         !inet_ntop( AF_INET,
3278                                             (struct in_addr*)h->h_addr_list[0],
3279                                                 dev  + (host - uidhost),
3280                                                 devl - (host - uidhost) )
3281                        ) {
3282                        fprintf(stderr,"nfsMount: host '%s' not found\n",host);
3283                        goto cleanup;
3284                }
3285
3286/* END OF NON-THREAD SAFE REGION */
3287
3288                /* append ':<path>' */
3289                strcat(dev,":");
3290                strcat(dev,path);
3291        }
3292
3293        printf("Trying to mount %s on %s\n",dev,mntpoint);
3294
3295        if (mount(&mtab,
3296                          &nfs_fs_ops,
3297                          RTEMS_FILESYSTEM_READ_WRITE,
3298                          dev,
3299                          mntpoint)) {
3300                perror("nfsMount - mount");
3301                goto cleanup;
3302        }
3303
3304        rval = 0;
3305
3306cleanup:
3307        free(dev);
3308        return rval;
3309}
3310
3311/* HERE COMES A REALLY UGLY HACK */
3312
3313/* This is stupid; it is _very_ hard to find the path
3314 * leading to a rtems_filesystem_location_info_t node :-(
3315 * The only easy way is making the location the current
3316 * directory and issue a getcwd().
3317 * However, since we don't want to tamper with the
3318 * current directory, we must create a separate
3319 * task to do the job for us - sigh.
3320 */
3321
3322typedef struct ResolvePathArgRec_ {
3323        rtems_filesystem_location_info_t        *loc;   /* IN: location to resolve      */
3324        char                                                            *buf;   /* IN/OUT: buffer where to put the path */
3325        int                                                                     len;    /* IN: buffer length            */
3326        rtems_id                                                        sync;   /* IN: synchronization          */
3327        rtems_status_code                                       status; /* OUT: result                          */
3328} ResolvePathArgRec, *ResolvePathArg;
3329
3330static void
3331resolve_path(rtems_task_argument arg)
3332{
3333ResolvePathArg                                          rpa = (ResolvePathArg)arg;
3334rtems_filesystem_location_info_t        old;
3335
3336        /* IMPORTANT: let the helper task have its own libio environment (i.e. cwd) */
3337        if (RTEMS_SUCCESSFUL == (rpa->status = rtems_libio_set_private_env())) {
3338
3339                old = rtems_filesystem_current;
3340
3341                rtems_filesystem_current = *(rpa->loc);
3342
3343                if ( !getcwd(rpa->buf, rpa->len) )
3344                        rpa->status = RTEMS_UNSATISFIED;
3345
3346                /* must restore the cwd because 'freenode' will be called on it */
3347                rtems_filesystem_current = old;
3348        }
3349        rtems_semaphore_release(rpa->sync);
3350        rtems_task_delete(RTEMS_SELF);
3351}
3352
3353
3354/* a utility routine to find the path leading to a
3355 * rtems_filesystem_location_info_t node
3356 *
3357 * INPUT: 'loc' and a buffer 'buf' (length 'len') to hold the
3358 *        path.
3359 * OUTPUT: path copied into 'buf'
3360 *
3361 * RETURNS: 0 on success, RTEMS error code on error.
3362 */
3363rtems_status_code
3364rtems_filesystem_resolve_location(char *buf, int len, rtems_filesystem_location_info_t *loc)
3365{
3366ResolvePathArgRec       arg;
3367rtems_id                        tid = 0;
3368rtems_task_priority     pri;
3369rtems_status_code       status;
3370
3371        arg.loc  = loc;
3372        arg.buf  = buf;
3373        arg.len  = len;
3374        arg.sync = 0;
3375
3376        status = rtems_semaphore_create(
3377                                        rtems_build_name('r','e','s','s'),
3378                                        0,
3379                                        RTEMS_SIMPLE_BINARY_SEMAPHORE,
3380                                        0,
3381                                        &arg.sync);
3382
3383        if (RTEMS_SUCCESSFUL != status)
3384                goto cleanup;
3385
3386        rtems_task_set_priority(RTEMS_SELF, RTEMS_CURRENT_PRIORITY, &pri);
3387
3388        status = rtems_task_create(
3389                                        rtems_build_name('r','e','s','s'),
3390                                        pri,
3391                                        RTEMS_MINIMUM_STACK_SIZE + 50000,
3392                                        RTEMS_DEFAULT_MODES,
3393                                        RTEMS_DEFAULT_ATTRIBUTES,
3394                                        &tid);
3395
3396        if (RTEMS_SUCCESSFUL != status)
3397                goto cleanup;
3398
3399        status = rtems_task_start(tid, resolve_path, (rtems_task_argument)&arg);
3400
3401        if (RTEMS_SUCCESSFUL != status) {
3402                rtems_task_delete(tid);
3403                goto cleanup;
3404        }
3405
3406
3407        /* synchronize with the helper task */
3408        rtems_semaphore_obtain(arg.sync, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
3409
3410        status = arg.status;
3411
3412cleanup:
3413        if (arg.sync)
3414                rtems_semaphore_delete(arg.sync);
3415
3416        return status;
3417}
3418
3419int
3420nfsSetTimeout(uint32_t timeout_ms)
3421{
3422rtems_interrupt_level k;
3423uint32_t                  s,us;
3424
3425        if ( timeout_ms > 100000 ) {
3426                /* out of range */
3427                return -1;
3428        }
3429
3430        s  = timeout_ms/1000;
3431        us = (timeout_ms % 1000) * 1000;
3432
3433        rtems_interrupt_disable(k);
3434        _nfscalltimeout.tv_sec  = s;
3435        _nfscalltimeout.tv_usec = us;
3436        rtems_interrupt_enable(k);
3437
3438        return 0;
3439}
3440
3441uint32_t
3442nfsGetTimeout( void )
3443{
3444rtems_interrupt_level k;
3445uint32_t              s,us;
3446        rtems_interrupt_disable(k);
3447        s  = _nfscalltimeout.tv_sec;
3448        us = _nfscalltimeout.tv_usec;
3449        rtems_interrupt_enable(k);
3450        return s*1000 + us/1000;
3451}
Note: See TracBrowser for help on using the repository browser.