# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright (c) 1994 by Sun Microsystems, Inc. # include ../Makefile.master SUBDIRS = lib all install clean lint: $(SUBDIRS) clobber: $(SUBDIRS) $(RM) make.out lint.out all : TARGET = all clean : TARGET = clean clobber : TARGET = clobber lint : TARGET = lint install : TARGET = install $(SUBDIRS): FRC @cd $@; pwd; $(MAKE) $(TARGET) FRC: # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 1994 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" If you are looking for the rest of what used to be in /usr/src/stand, it's over in /usr/src/psm/stand now. # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2014 Gary Mills # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # include Makefile.com i386_SUBDIRS = # Hammerhead: sparc_SUBDIRS removed - amd64 only build SUBDIRS = fs/hsfs fs/nfs fs/ufs inet sa sock tcpstubs xdr \ tcp $($(MACH)_SUBDIRS) .PARALLEL: $(SUBDIRS) .KEEP_STATE: all : TARGET = all clean : TARGET = clean clobber : TARGET = clobber install : TARGET = install all clean clobber install: $(SUBDIRS) $(SUBDIRS): FRC cd $@; pwd; $(MAKE) $(TARGET) FRC: # # Cross-reference customization: set the include path to be reasonable. # XRINCDIRS = $(CPPINCS:-YI,%=-I%) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # # Common macro definitions and pattern rules for stand libraries. # Basically just a trivial wrapper around $(SRC)/lib/Makefile.lib. # include $(SRC)/lib/Makefile.lib include $(SRC)/stand/lib/Makefile.$(MACH) SRCDIR = . LIBS += $(LIBRARY) CFLAGS += $(CCVERBOSE) LDFLAGS = -r LDLIBS += -lsa # # Reset ROOTLIBDIR to an alternate directory so that we don't clash with # $(ROOT)/usr/lib. The Makefiles over in usr/src/psm expect to find our # libraries here. # ROOTLIBDIR = $(ROOT)/stand/lib # # Paths to a variety of commonly-referenced directories. Note that we use # relative paths so that references to filenames in the source (e.g., # through use of assert()) are not exposed absolutely (for reasons of # taste and to help make the binaries end up the same even when built from # different workspaces). Makefiles that are more than one directory level # deeper than this Makefile need to set DIRREL appropriately so that the # relative paths can still be accessed correctly. # TOPDIR = $(DIRREL)../../.. STANDDIR = $(DIRREL)../.. CMNNETDIR = $(TOPDIR)/common/net SYSDIR = $(TOPDIR)/uts # # As a courtesy to the numerous standalone libraries which are built from # sources living elsewhere, we provide a generic CMNDIR macro which the # library's Makefile can set (if need be) to the primary other directory # it grabs its sources from. # CMNDIR = . # # Configure the appropriate #defines and #include path for building # standalone bits. Note that we turn off access to /usr/include and # the proto area since those headers match libc's implementation, and # libc is of course not available to standalone binaries. # CPPDEFS = -D$(KARCH) -D_BOOT -D_KERNEL -D_MACHDEP CPPINCS = -YI,$(STANDDIR)/lib/sa -I$(STANDDIR)/lib/sa \ -I$(STANDDIR) -I$(SRCDIR) -I$(CMNDIR) \ -I$(STANDDIR)/$(MACH) -I$(SYSDIR)/common $(ARCHDIRS) \ -I$(SYSDIR)/sun4 -I$(SYSDIR)/$(KARCH) CPPFLAGS = $(CPPDEFS) $(CPPINCS) AS_CPPFLAGS = $(CPPDEFS) $(CPPINCS:-YI,%=-I%) ASFLAGS = -D__STDC__ -D_ASM # # CPPFLAGS values that *must* be included whenever linking with or # building libssl or libcrypto. # Exclusions here are for both legal and size reasons. # OPENSSL_SRC = ../../../common/openssl OPENSSL_BUILD_CPPFLAGS_sparc = -DB_ENDIAN OPENSSL_BUILD_CPPFLAGS = -DOPENSSL_NO_ECDH -DOPENSSL_NO_ECDSA \ -DOPENSSL_NO_HW_4758_CCA -DOPENSSL_NO_HW_AEP \ -DOPENSSL_NO_HW_ATALLA -DOPENSSL_NO_HW_CHIL \ -DOPENSSL_NO_HW_CSWIFT -DOPENSSL_NO_HW_GMP \ -DOPENSSL_NO_HW_NURON -DOPENSSL_NO_HW_PADLOCK \ -DOPENSSL_NO_HW_SUREWARE -DOPENSSL_NO_HW_UBSEC \ -DOPENSSL_NO_HW \ -DOPENSSL_NO_MD2 -DOPENSSL_NO_MD4 -DOPENSSL_NO_MDC2 \ -DOPENSSL_NO_RIPEMD -DOPENSSL_NO_RC3 -DOPENSSL_NO_RC4 \ -DOPENSSL_NO_EC -DOPENSSL_NO_RC5 -DOPENSSL_NO_IDEA \ -DOPENSSL_NO_CAST -DOPENSSL_NO_AES \ -DDEVRANDOM=\"/dev/urandom\" \ -I.. \ $(OPENSSL_BUILD_CPPFLAGS_$(MACH)) \ -I$(ROOT)/usr/include \ -I$(OPENSSL_SRC) -I$(OPENSSL_SRC)/crypto # # CPPFLAGS values that *must* be included whenever linking the DHCP # routines in $SRC/common/net/dhcp. # DHCPCPPFLAGS = -I$(CMNNETDIR)/dhcp # # CPPFLAGS values that *must* be included whenever linking with or # building libsock. # # The header files for libsock provide alternate definitions for data # types that are also defined in . To make sure we get the # right ones, prevent 's contents from being included. This # is shameful. # SOCKCPPFLAGS = -I$(STANDDIR)/lib/sock -D_SYS_STREAM_H # # Using Makefile.lib pulls in the stack protector. Explicitly disable it # as it is not initialized or supported in this environment currently. # STACKPROTECT = none .KEEP_STATE: # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # # We only support 64-bit builds on SPARC, so this is simple. # KARCH = sun4u ARCHDIRS = -I$(SYSDIR)/sparc -I$(SYSDIR)/sparc/v9 -I$(SYSDIR)/sun include $(SRC)/psm/Makefile.psm.64 CFLAGS64 += -xchip=ultra # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2006 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # all alllibs: $(LIBS) clean: $(RM) $(OBJS) $(CLEANFILES) clobber: clean $(RM) $(LIBS) $(CLOBBERFILES) install: all .WAIT $(ROOTLIBDIR) .WAIT $(ROOTLIBS) lint lintcheck: $$(SRCS) $(LINT.c) $(SRCS) -L$(ROOTLIBDIR) $(LDLIBS) objs: -@mkdir -p $@ $(LIBRARY): objs .WAIT $$(OBJS) $(BUILD.AR) $(POST_PROCESS_A) $(LINTLIB): $$(SRCS) $(LINT.c) -o $(LIBNAME) $(SRCS) 2>&1 objs/%.o: $(SRCDIR)/%.c $(COMPILE.c) -o $@ $< $(POST_PROCESS_O) objs/%.o: $(CMNDIR)/%.c $(COMPILE.c) -o $@ $< $(POST_PROCESS_O) objs/%.o: $(SHA1DIR)/%.c $(COMPILE.c) -o $@ $< $(POST_PROCESS_O) $(ROOTLIBDIR): $(INS.dir) $(ROOTLIBDIR)/%: % $(INS.file) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # DIRREL = ../ include ../../Makefile.com # # Right now, the filesystem modules are only clean when -y is used -- some # needs to go finish cleaning them up, at which point this can be removed. # lint lintcheck : LINTFLAGS += -y CERRWARN += -Wno-type-limits CERRWARN += -Wno-parentheses CERRWARN += $(CNOWARN_UNINIT) CERRWARN += -Wno-switch CERRWARN += -Wno-char-subscripts /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * This is mostly new code. Major revisions were made to allow multiple * file systems to share a common cache. While this consisted primarily * of including a "devid_t" pointer in the hash functions, I also re- * organized everything to eliminate much of the duplicated code that * had existed previously. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #ifndef ICACHE_SIZE /* * These should probably be defined in an architecture-specific header * file. The values below are analogous to those used in earlier versions * of this module. */ #define ICACHE_SIZE 350 /* Max number of I-node in file cache */ #define DCACHE_SIZE 1500 /* Max number of cached directories */ #define BCACHE_SIZE 250 /* Max number of cached disk blocks */ #endif #define Next 0 /* Next pointer in Fwd/Bak link */ #define Prev 1 /* Previous pointer in Fwd/Back links */ #define Frst 0 /* Ptr to first element of a chain */ #define Last 1 /* Ptr to last element of a chain */ #define Hash 2 /* Offset of hash chain ptrs. */ typedef struct cache { /* Generic cache element: */ struct cache *link[4]; /* .. Fwd/Bak links for hash chain & LRU */ struct cache **chn; /* .. Hash chain link */ int dev; /* .. Device file handle */ void *data; /* .. Ptr to associated data */ int size; /* .. Size of cached data */ } cache_t; typedef struct head { /* Generic cache header: */ cache_t *aged[2]; /* .. LRU list */ int (*cmp)(cache_t *); /* .. Ptr to comparison function */ int size; /* .. Size of "cache" objects */ int maxblks; /* .. Max number of cached elements */ int count; /* .. Current number of cached elements */ int hits; /* .. Total cache hits */ int searches; /* .. Total searches */ int purges; /* .. Total purges */ } head_t; /* Constructor for cache headers: */ #define cache_head(h, f, t, n) \ {{(cache_t *)&h, (cache_t *)&h}, f, sizeof (t), n} int read_opt; /* Number of times cache was bypassed */ static int x_dev; /* Target device ID saved here! */ static int x_len; /* length of object */ #define LOG2(x) \ (((x) <= 16) ? 4 : /* Yeah, it's ugly. But it works! */ \ (((x) <= 32) ? 5 : /* .. Binary log should be part of */ \ (((x) <= 64) ? 6 : /* .. the language! */ \ (((x) <= 128) ? 7 : 8)))) static cache_t * get_cache(cache_t *cap, head_t *chp) { /* * Search cache: * * The caller pass a pointer to the first "cache" object in the current * hash chain ["cap"] and a pointer to the corresponding cache header * ["chp"]. This routine follows the cache chain until it finds an * entry that matches both the current device [as noted in "x_dev"] * and the cache-specific comparison ["chp->cmp"]. * * Returns the address of the matching cache object or null if there * is none. */ while (cap) { /* * Check all entries on the cache chain. We expect * chains to be relatively short, so we use a simple * linear search. */ if ((x_dev == cap->dev) && (*chp->cmp)(cap)) { /* * Found the entry we're looking for! Move it * to the front of the cache header's LRU list * before returing its addres to the caller. */ cap->link[Next]->link[Prev] = cap->link[Prev]; cap->link[Prev]->link[Next] = cap->link[Next]; cap->link[Prev] = (cache_t *)chp->aged; cap->link[Next] = chp->aged[Frst]; chp->aged[Frst]->link[Prev] = cap; chp->aged[Frst] = cap; chp->hits += 1; break; } cap = cap->link[Hash+Next]; } chp->searches += 1; return (cap); } static cache_t * reclaim_cache(head_t *chp, int dev) { /* * Reclaim a cache element: * * This routine is used to: [a] free the oldest element from * the cache headed at "chp" and return the address of the * corresponding "cache_t" struct (iff dev == -1), or [b] free all * elements on the cache headed at "chp" that belong to the * indicated "dev"ice. */ cache_t *cap, *cxp; cache_t *cpp = (cache_t *)chp; while ((cap = cpp->link[Prev]) != (cache_t *)chp) { /* * We follow the cache's LRU chain from oldest to * newest member. This ensures that we remove only * the oldest element when we're called with a * negative "dev" argument. */ if ((dev == -1) || (dev == cap->dev)) { /* * This is one of the (perhaps the only) * elements we're supposed to free. Remove it * from both the LRU list and its associated * hash chain. Then free the data bound the * the cache_t element and, if "dev" is * not -1, the element itself! */ cap->link[Prev]->link[Next] = cap->link[Next]; cap->link[Next]->link[Prev] = cap->link[Prev]; if ((cxp = cap->link[Hash+Prev]) != 0) cxp->link[Hash+Next] = cap->link[Hash+Next]; else *(cap->chn) = cap->link[Hash+Next]; if ((cxp = cap->link[Hash+Next]) != 0) cxp->link[Hash+Prev] = cap->link[Hash+Prev]; bkmem_free((caddr_t)cap->data, cap->size); if (dev == -1) return (cap); bkmem_free((caddr_t)cap, chp->size); chp->count -= 1; } else { /* * Skip this element, it's not one of the * ones we want to free up. */ cpp = cap; } }; return (0); } static cache_t * set_cache(cache_t **ccp, head_t *chp, int noreclaim) { /* * Install a cache element: * * The caller passes the address of cache descriptor ["chp"] and the * hash chain into which the new element is to be linked ["ccp"]. This * routine allocates a new cache_t structure (or, if the maximum number * of elements has already been allocated, reclaims the oldest element * from the cache), links it into the indicated hash chain, and returns * its address to the caller. */ cache_t *cap; if ((chp->count < chp->maxblks) && (cap = (cache_t *)bkmem_alloc(chp->size))) { /* * We haven't reached the maximum cache size yet. * Allocate a new "cache_t" struct to be added to the * cache. */ chp->count += 1; } else { if (noreclaim) return (NULL); /* * Cache is full. Use the "reclaim_cache" routine to * remove the oldest element from the cache. This * will become the cache_t struct associated with the * new element. */ cap = reclaim_cache(chp, -1); chp->purges += 1; } bzero((char *)cap, chp->size); cap->chn = ccp; cap->link[Prev] = (cache_t *)chp; cap->link[Next] = chp->aged[Frst]; cap->link[Prev]->link[Next] = cap->link[Next]->link[Prev] = cap; if ((cap->link[Hash+Next] = *ccp) != 0) (*ccp)->link[Hash+Prev] = cap; return (*ccp = cap); } /* * The File Cache: * * This cache (also known as the inode cache) is used to keep track of all * files open on a given device. The only special data required to locate * a cache entry is the file reference number which is file-system dependent * (for UNIX file systems, it's an inode number). */ typedef struct icache { /* Inode cache element: */ cache_t ic_hdr; /* .. Standard header */ int ic_num; /* .. I-node number */ } ic_t; #define IC_MAX_HDRS (1 << LOG2(ICACHE_SIZE/6)) #define IC_HASH(d, i) (((d) + (i)) & (IC_MAX_HDRS - 1)) static int x_inode; static int /* Cache search predicate: */ cmp_icache(cache_t *p) { /* Just check the file number ("x_inode") ... */ return (((ic_t *)p)->ic_num == x_inode); } static head_t ic_head = cache_head(ic_head, cmp_icache, ic_t, ICACHE_SIZE); static cache_t *ic_hash[IC_MAX_HDRS]; void * get_icache(int dev, int inum) { /* * Search File Cache: * * This routine searches the file cache looking for the entry bound to * the given "dev"ice and file number ["inum"]. If said entry exists, * it returns the address of the associated file structure. Otherwise * it returns null. */ cache_t *icp; x_dev = dev; x_inode = inum; icp = get_cache(ic_hash[IC_HASH(dev, inum)], &ic_head); return (icp ? (caddr_t)icp->data : 0); } void set_icache(int dev, int inum, void *ip, int size) { /* * Build a File Cache Entry: * * This routne installs the "size"-byte file structure at * "*ip" in the inode cache where it may be retrieved by * subsequent call to get_icache. */ ic_t *icp = (ic_t *)set_cache(&ic_hash[IC_HASH(dev, inum)], &ic_head, 0); icp->ic_num = inum; icp->ic_hdr.data = ip; icp->ic_hdr.dev = dev; icp->ic_hdr.size = size; } int set_ricache(int dev, int inum, void *ip, int size) { /* * Reliably set the icache * * This routine is the same as set_icache except that it * will return 1 if the entry could not be entered into the cache * without a purge. */ ic_t *icp = (ic_t *)set_cache(&ic_hash[IC_HASH(dev, inum)], &ic_head, 1); if (icp == NULL) return (1); icp->ic_num = inum; icp->ic_hdr.data = ip; icp->ic_hdr.dev = dev; icp->ic_hdr.size = size; return (0); } /* * The Directory Cache: * * This cache is designed to speed directory searches. Each entry cor- * responds to a directory entry that was used in a pathname resolution. * The idea is that most files used by the boot wil be contained in a hand- * full of directories, so we can speed searches if we know ahead of time * just where these directories are. */ typedef struct dcache { /* Directory cache objects: */ cache_t dc_hdr; /* .. Standard header */ int dc_inum; /* .. File number */ int dc_pnum; /* .. Parent diretory's file number */ } dc_t; #define DC_MAX_HDRS (1 << LOG2(DCACHE_SIZE/6)) #define DC_HASH(d, n, l) (((d) + (n)[0] + (n)[(l)-1] + (l)) & (DC_MAX_HDRS-1)) static char *x_name; static int x_pnum; static int cmp_dcache(cache_t *p) /* Cache Search predicate: */ { /* Check name, length, and parent's file number */ return ((x_len == p->size) && (x_pnum == ((dc_t *)p)->dc_pnum) && (strcmp((char *)p->data, x_name) == 0)); } static head_t dc_head = cache_head(dc_head, cmp_dcache, dc_t, DCACHE_SIZE); static cache_t *dc_hash[DC_MAX_HDRS]; int get_dcache(int dev, char *name, int pnum) { /* * Search Directory Cache: * * This routine searches the directory cache for an entry * associated with directory number "pnum" from the given * file system that de-scribes a file of the given "name". * If we find such an entry, we return the corresponding file * number, 0 otherwise. */ dc_t *dcp; x_dev = dev; x_len = strlen(name)+1; x_pnum = pnum; x_name = name; dcp = (dc_t *)get_cache(dc_hash[DC_HASH(dev, name, x_len)], &dc_head); return (dcp ? dcp->dc_inum : 0); } void set_dcache(int dev, char *name, int pnum, int inum) { /* * Build Directory Cache Entry: * * This routine creates directory cache entries to be retrieved later * via "get_dcache". The cache key is composed of three parts: The * device specifier, the file name ("name"), and the file number of * the directory containing that name ("pnum"). The data portion of * the entry consists of the file number ("inum"). */ int len = strlen(name)+1; dc_t *dcp = (dc_t *)set_cache(&dc_hash[DC_HASH(dev, name, len)], &dc_head, 0); if (dcp->dc_hdr.data = (void *)bkmem_alloc(len)) { /* * Allocate a buffer for the pathname component, and * make this the "data" portion of the generalize * "cache_t" struct. Also fill in the cache-specific * fields (pnum, inum). */ dcp->dc_pnum = pnum; dcp->dc_inum = inum; dcp->dc_hdr.dev = dev; dcp->dc_hdr.size = len; bcopy(name, (char *)dcp->dc_hdr.data, len); } else { /* * Not enough memory to make a copy of the name! * There's probably not enough to do much else either! */ prom_panic("no memory for directory cache"); } } int set_rdcache(int dev, char *name, int pnum, int inum) { /* * Reliably set the dcache * * This routine is the same as set_dcache except that it * return 1 if the entry could not be entered into * the cache without a purge. */ int len = strlen(name) + 1; dc_t *dcp = (dc_t *)set_cache(&dc_hash[DC_HASH(dev, name, len)], &dc_head, 1); if (dcp == NULL) return (1); if ((dcp->dc_hdr.data = (void *)bkmem_alloc(len)) == NULL) { /* * Not enough memory to make a copy of the name! * There's probably not enough to do much else either! */ prom_panic("no memory for directory cache"); /* NOTREACHED */ } /* * Allocate a buffer for the pathname component, and * make this the "data" portion of the generalize * "cache_t" struct. Also fill in the cache-specific * fields (pnum, inum). */ dcp->dc_pnum = pnum; dcp->dc_inum = inum; dcp->dc_hdr.dev = dev; dcp->dc_hdr.size = len; bcopy(name, (char *)dcp->dc_hdr.data, len); return (0); } /* * Disk Block Cache: */ typedef struct bcache { /* Disk block cache objects: */ cache_t bc_hdr; /* .. Standard header */ unsigned long bc_blk; /* .. The block number */ } bc_t; #define BC_MAX_HDRS (1 << LOG2(BCACHE_SIZE/6)) #define BC_HASH(d, b, l) (((d) + (b) + ((l) >> 8)) & (BC_MAX_HDRS-1)) static unsigned long x_blkno; static int cmp_bcache(cache_t *p) /* Cache Search predicate: */ { /* Check block number, buffer size */ return ((x_len == p->size) && (x_blkno == ((bc_t *)p)->bc_blk)); } static head_t bc_head = cache_head(bc_head, cmp_bcache, bc_t, BCACHE_SIZE); static cache_t *bc_hash[BC_MAX_HDRS]; caddr_t get_bcache(fileid_t *fp) { /* * Search Disk Block Cache: * * This should be getting pretty monotonous by now. Aren't generalized * subroutines ("objects", if you prefer) great? */ cache_t *bcp; x_len = fp->fi_count; x_blkno = fp->fi_blocknum; x_dev = fp->fi_devp->di_dcookie; bcp = get_cache(bc_hash[BC_HASH(x_dev, x_blkno, x_len)], &bc_head); return (bcp ? (caddr_t)bcp->data : 0); } int set_bcache(fileid_t *fp) { /* * Insert Disk Block Cache Entry: * * In this case, we actually read the requested block into a * dynamically allocated buffer before inserting it into the * cache. If the read fails, we return a non-zero value. * * The search keys for disk blocks are the block number and * buffer size. The data associated with each entry is the * corresponding data buffer. */ bc_t *bcp; if (fp->fi_memp = bkmem_alloc(x_len = fp->fi_count)) { /* * We were able to succesffully allocate an input * buffer, now read the data into it. */ if (diskread(fp) != 0) { /* * I/O error on read. Free the input buffer, * print an error message, and bail out. */ bkmem_free(fp->fi_memp, x_len); printf("disk read error\n"); return (-1); } x_blkno = fp->fi_blocknum; x_dev = fp->fi_devp->di_dcookie; bcp = (bc_t *) set_cache(&bc_hash[BC_HASH(x_dev, x_blkno, x_len)], &bc_head, 0); bcp->bc_blk = x_blkno; bcp->bc_hdr.dev = x_dev; bcp->bc_hdr.size = x_len; bcp->bc_hdr.data = (void *)fp->fi_memp; } else { /* * We could be a bit more convervative here by * calling "set_cache" before we try to allocate a * buffer (thereby giving us a chance to re-use a * previously allocated buffer) but the error recovery * is a bit trickier, and if we're that short on memory * we'll have trouble elsewhere anyway! */ prom_panic("can't read - no memory"); } return (0); } void release_cache(int dev) { /* * Reclaim all cache entries: * * This routine is called by the file-system's "closeall" method. It * removes all cache entries associated with that file system from the * global cache and release any resources bound to said entrires. */ (void) reclaim_cache(&ic_head, dev); (void) reclaim_cache(&dc_head, dev); (void) reclaim_cache(&bc_head, dev); } void print_cache_data() { /* * Print some cacheing statistics ... */ static char *tag[] = { "inode", "directory", "disk block", 0}; static head_t *hdp[] = { &ic_head, &dc_head, &bc_head, 0}; int j; for (j = 0; tag[j]; j++) { /* * Print statistics maintained in the header * ("head_t" struct) of each of the above caches. */ head_t *hp = hdp[j]; if (j) printf("\n"); printf("%s cache:\n", tag[j]); printf(" max size %d\n", hp->maxblks); printf(" actual size %d\n", hp->count); printf(" total searches %d\n", hp->searches); printf(" cache hits %d\n", hp->hits); printf(" cache purges %d\n", hp->purges); } printf("\nread opts %d\n", read_opt); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1994-1996, 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include static char prom_dev_type = 0; /* * unix root slice offset for PROMS that do * not know about fdisk partitions or Solaris * slices. * the default is 0 for machines with proms that * do know how to interpret solaris slices. */ unsigned long unix_startblk = 0; /* * The various flavors of PROM make this grotesque. */ int diskread(fileid_t *filep) { int err; devid_t *devp; uint_t blocknum; /* add in offset of root slice */ blocknum = filep->fi_blocknum + unix_startblk; devp = filep->fi_devp; err = prom_seek(devp->di_dcookie, (unsigned long long)blocknum * (unsigned long long)DEV_BSIZE); if (err == -1) { printf("Seek error at block %x\n", blocknum); return (-1); } if ((err = prom_read(devp->di_dcookie, filep->fi_memp, filep->fi_count, blocknum, prom_dev_type)) != filep->fi_count) { printf("Short read. 0x%x chars read\n", err); return (-1); } return (0); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1994-1996, 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include static struct boot_fs_ops *dfl_fsw = (struct boot_fs_ops *)NULL; static char *fsmsg = "Fstype has not been selected yet!\n"; static char *msg_noops = "not fs_ops supplied\n"; /* * return fs_ops pointer for a given file system name */ struct boot_fs_ops * get_fs_ops_pointer(char *fsw_name) { int fsw_idx; for (fsw_idx = 0; fsw_idx < boot_nfsw; fsw_idx++) if (strcmp(boot_fsw[fsw_idx]->fsw_name, fsw_name) == 0) { return (boot_fsw[fsw_idx]); } return ((struct boot_fs_ops *)NULL); } /* * set default file system type */ void set_default_fs(char *fsw_name) { int fsw_idx; for (fsw_idx = 0; fsw_idx < boot_nfsw; fsw_idx++) if (strcmp(boot_fsw[fsw_idx]->fsw_name, fsw_name) == 0) { dfl_fsw = boot_fsw[fsw_idx]; return; } printf("Fstype <%s> is not recognized\n", fsw_name); prom_panic(""); } /* * clear default file system type */ void clr_default_fs(void) { dfl_fsw = NULL; } struct boot_fs_ops * get_default_fs(void) { return (dfl_fsw); } void boot_no_ops_void() { prom_panic(msg_noops); /*NOTREACHED*/ } int boot_no_ops() { prom_panic(msg_noops); /*NOTREACHED*/ return (0); } int close(int fd) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_close)(fd)); prom_panic(fsmsg); /*NOTREACHED*/ } int mountroot(char *str) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_mountroot)(str)); prom_panic(fsmsg); /*NOTREACHED*/ } int unmountroot(void) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_unmountroot)()); prom_panic(fsmsg); /*NOTREACHED*/ } /*ARGSUSED*/ int open(const char *filename, int flags) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_open)((char *)filename, flags)); prom_panic(fsmsg); /*NOTREACHED*/ } ssize_t read(int fd, void *buf, size_t size) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_read)(fd, buf, size)); prom_panic(fsmsg); /*NOTREACHED*/ } void closeall(int flag) { if (dfl_fsw != (struct boot_fs_ops *)NULL) { (*dfl_fsw->fsw_closeall)(flag); return; } prom_panic(fsmsg); /*NOTREACHED*/ } int fstat(int fd, struct stat *sb) { struct bootstat buf; int ret; if (dfl_fsw == NULL) prom_panic(fsmsg); ret = (*dfl_fsw->fsw_fstat)(fd, &buf); if (ret == -1) return (-1); sb->st_dev = buf.st_dev; sb->st_ino = buf.st_ino; sb->st_mode = buf.st_mode; sb->st_nlink = buf.st_nlink; sb->st_uid = buf.st_uid; sb->st_gid = buf.st_gid; sb->st_rdev = buf.st_rdev; sb->st_size = (off_t)buf.st_size; sb->st_blksize = buf.st_blksize; sb->st_blocks = buf.st_blocks; sb->st_atim.tv_sec = buf.st_atim.tv_sec; sb->st_atim.tv_nsec = buf.st_atim.tv_nsec; sb->st_mtim.tv_sec = buf.st_mtim.tv_sec; sb->st_mtim.tv_nsec = buf.st_mtim.tv_nsec; sb->st_ctim.tv_sec = buf.st_ctim.tv_sec; sb->st_ctim.tv_nsec = buf.st_ctim.tv_nsec; (void) memcpy(sb->st_fstype, buf.st_fstype, sizeof (sb->st_fstype)); return (0); } int stat(const char *filename, struct stat *sb) { int fd, ret = -1; if ((fd = open(filename, O_RDONLY)) != -1) { ret = fstat(fd, sb); (void) close(fd); } return (ret); } off_t lseek(int filefd, off_t addr, int whence) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_lseek)(filefd, addr, whence)); prom_panic(fsmsg); /*NOTREACHED*/ } /* * Kernel Interface */ int kern_open(char *str, int flags) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_open)(str, flags)); prom_panic(fsmsg); /*NOTREACHED*/ } /* * hi and lo refer to the MS end of the off_t word * and the LS end of the off_t word for when we want * to support 64-bit offsets. For now, lseek() just * supports 32 bits. */ /*ARGSUSED*/ off_t kern_lseek(int filefd, off_t hi, off_t lo) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_lseek)(filefd, lo, 0)); prom_panic(fsmsg); /*NOTREACHED*/ } ssize_t kern_read(int fd, caddr_t buf, size_t size) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_read)(fd, buf, size)); prom_panic(fsmsg); /*NOTREACHED*/ } int kern_close(int fd) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_close)(fd)); prom_panic(fsmsg); /*NOTREACHED*/ } int kern_fstat(int fd, struct bootstat *buf) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_fstat)(fd, buf)); prom_panic(fsmsg); /*NOTREACHED*/ } int kern_getdents(int fd, struct dirent *buf, size_t size) { if (dfl_fsw != (struct boot_fs_ops *)NULL) return ((*dfl_fsw->fsw_getdents)(fd, buf, size)); prom_panic(fsmsg); /*NOTREACHED*/ } int kern_mountroot(char *path) { return (mountroot(path)); } int kern_unmountroot(void) { return (unmountroot()); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include /* * Function prototypes */ static int promfs_mountroot(char *str); static int promfs_unmountroot(void); static int promfs_open(char *filename, int flags); static int promfs_close(int fd); static ssize_t promfs_read(int fd, caddr_t buf, size_t size); static off_t promfs_lseek(int fd, off_t offset, int whence); static int promfs_fstat(int fd, struct bootstat *stp); static void promfs_closeall(int flag); struct boot_fs_ops promfs_ops = { "promfs", promfs_mountroot, promfs_unmountroot, promfs_open, promfs_close, promfs_read, promfs_lseek, promfs_fstat, promfs_closeall, NULL }; static ihandle_t fsih; static int promfs_mountroot(char *str) { (void) prom_getprop(prom_chosennode(), str, (caddr_t)&fsih); return (fsih == -1); } static int promfs_unmountroot(void) { (void) prom_close(fsih); return (0); } /*ARGSUSED*/ static int promfs_open(char *filename, int flags) { return (prom_fopen(fsih, filename)); } static int promfs_close(int fd) { prom_fclose(fsih, fd); return (0); } static ssize_t promfs_read(int fd, caddr_t buf, size_t size) { return (prom_fread(fsih, fd, buf, size)); } /*ARGSUSED*/ static off_t promfs_lseek(int fd, off_t offset, int whence) { return (prom_fseek(fsih, fd, offset)); } static int promfs_fstat(int fd, struct bootstat *stp) { return (prom_fsize(fsih, fd, (size_t *)&stp->st_size)); } /*ARGSUSED*/ static void promfs_closeall(int flag) { } # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # LIBRARY = libhsfs.a OBJECTS = hsfsops.o include ../Makefile.com include ../../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2000 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" static char *hsfs_sig_tab[] = { SUSP_SP, SUSP_CE, SUSP_PD, SUSP_ST, SUSP_ER, RRIP_PX, RRIP_PN, RRIP_SL, RRIP_CL, RRIP_PL, RRIP_RE, RRIP_TF, RRIP_RR, RRIP_NM }; static int hsfs_num_sig = sizeof (hsfs_sig_tab) / sizeof (hsfs_sig_tab[0]); #define SUSP_SP_IX 0 #define SUSP_CE_IX 1 #define SUSP_PD_IX 2 #define SUSP_ST_IX 3 #define SUSP_ER_IX 4 #define RRIP_PX_IX 5 #define RRIP_PN_IX 6 #define RRIP_SL_IX 7 #define RRIP_CL_IX 8 #define RRIP_PL_IX 9 #define RRIP_RE_IX 10 #define RRIP_RF_IX 11 #define RRIP_RR_IX 12 #define RRIP_NM_IX 13 /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "hsfs_sig.h" #include #include #include #include #define hdbtodb(n) ((ISO_SECTOR_SIZE / DEV_BSIZE) * (n)) #define THE_EPOCH 1970 #define END_OF_TIME 2099 /* May not need this... */ static uint_t sua_offset = 0; /* The root inode on an HSFS filesystem can be anywhere! */ static uint_t root_ino = 0; /* This is both a flag and a value */ static fileid_t *head; /* Only got one of these...ergo, only 1 fs open at once */ static devid_t *devp; struct dirinfo { int loc; fileid_t *fi; }; struct hs_direct { struct direct hs_ufs_dir; struct hs_direntry hs_dir; }; /* * Function prototypes */ static int boot_hsfs_mountroot(char *str); static int boot_hsfs_unmountroot(void); static int boot_hsfs_open(char *filename, int flags); static int boot_hsfs_close(int fd); static ssize_t boot_hsfs_read(int fd, caddr_t buf, size_t size); static off_t boot_hsfs_lseek(int, off_t, int); static int boot_hsfs_fstat(int fd, struct bootstat *stp); static void boot_hsfs_closeall(int flag); static int boot_hsfs_getdents(int fd, struct dirent *dep, unsigned size); struct boot_fs_ops boot_hsfs_ops = { "hsfs", boot_hsfs_mountroot, boot_hsfs_unmountroot, boot_hsfs_open, boot_hsfs_close, boot_hsfs_read, boot_hsfs_lseek, boot_hsfs_fstat, boot_hsfs_closeall, boot_hsfs_getdents }; static ino_t find(fileid_t *, char *); static ino_t dlook(fileid_t *, char *); static int opendir(fileid_t *, ino_t); static struct hs_direct *readdir(struct dirinfo *); static uint_t parse_dir(fileid_t *, int, struct hs_direct *); static uint_t parse_susp(char *, uint_t *, struct hs_direct *); static void hs_seti(fileid_t *, struct hs_direct *, ino_t); static void hs_dodates(enum hs_vol_type, struct hs_direntry *, char *); static time_t hs_date_to_gmtime(int, int, int, int); /* * There is only 1 open (mounted) device at any given time. * So we can keep a single, global devp file descriptor to * use to index into the di[] array. This is not true for the * fi[] array. We can have more than one file open at once, * so there is no global fd for the fi[]. * The user program must save the fd passed back from open() * and use it to do subsequent read()'s. */ static int opendir(fileid_t *filep, ino_t inode) { struct hs_direct hsdep; int retval; /* Set up the saio request */ filep->fi_offset = 0; filep->fi_blocknum = hdbtodb(inode); filep->fi_count = ISO_SECTOR_SIZE; /* Maybe the block is in the disk block cache */ if ((filep->fi_memp = get_bcache(filep)) == NULL) { /* Not in the block cache so read it from disk */ if (retval = set_bcache(filep)) { return (retval); } } filep->fi_offset = 0; filep->fi_blocknum = hdbtodb(inode); if (inode != root_ino) return (0); if ((int)(parse_dir(filep, 0, &hsdep)) > 0) { hs_seti(filep, &hsdep, inode); return (0); } return (1); } static ino_t find(fileid_t *filep, char *path) { register char *q; char c; ino_t inode; if (path == NULL || *path == '\0') { printf("null path\n"); return (0); } if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("find(): path=<%s>\n", path); /* Read the ROOT directory */ if (opendir(filep, inode = root_ino)) { printf("find(): root_ino opendir() failed!\n"); return ((ino_t)-1); } while (*path) { while (*path == '/') path++; if (*(q = path) == '\0') break; while (*q != '/' && *q != '\0') q++; c = *q; *q = '\0'; if ((inode = dlook(filep, path)) != 0) { if (c == '\0') break; if (opendir(filep, inode)) { printf("find(): opendir(%d) failed!\n", inode); *q = c; return ((ino_t)-1); } *q = c; path = q; continue; } else { *q = c; return (0); } } return (inode); } static fileid_t * find_fp(int fd) { fileid_t *filep = head; if (fd >= 0) { while ((filep = filep->fi_forw) != head) if (fd == filep->fi_filedes) return (filep->fi_taken ? filep : 0); } return (0); } static ino_t dlook(fileid_t *filep, char *path) { int dv = filep->fi_devp->di_dcookie; register struct hs_direct *hsdep; register struct direct *udp; register struct inode *ip; struct dirinfo dirp; register int len; ino_t in; ip = filep->fi_inode; if (path == NULL || *path == '\0') return (0); if ((ip->i_smode & IFMT) != IFDIR) { return (0); } if (ip->i_size == 0) { return (0); } len = strlen(path); /* first look through the directory entry cache */ if (in = get_dcache(dv, path, ip->i_number)) { if ((filep->fi_inode = get_icache(dv, in)) != NULL) { filep->fi_offset = 0; filep->fi_blocknum = hdbtodb(in); return (in); } } dirp.loc = 0; dirp.fi = filep; for (hsdep = readdir(&dirp); hsdep != NULL; hsdep = readdir(&dirp)) { udp = &hsdep->hs_ufs_dir; if (udp->d_namlen == 1 && udp->d_name[0] == '.' && udp->d_name[1] == '\0') continue; if (udp->d_namlen == 2 && udp->d_name[0] == '.' && udp->d_name[1] == '.' && udp->d_name[2] == '\0') continue; if (udp->d_namlen == len && (strcmp(path, udp->d_name) == 0)) { set_dcache(dv, path, ip->i_number, udp->d_ino); hs_seti(filep, hsdep, udp->d_ino); filep->fi_offset = 0; filep->fi_blocknum = hdbtodb(udp->d_ino); /* put this entry into the cache */ return (udp->d_ino); } /* Allow "*" to print all names at that level, w/out match */ if (strcmp(path, "*") == 0) printf("%s\n", udp->d_name); } return (0); } /* * get next entry in a directory. */ static struct hs_direct * readdir(struct dirinfo *dirp) { static struct hs_direct hsdep; register struct direct *udp = &hsdep.hs_ufs_dir; register struct inode *ip; register fileid_t *filep; register daddr_t lbn; register int off; filep = dirp->fi; ip = filep->fi_inode; for (;;) { if (dirp->loc >= ip->i_size) { return (NULL); } off = dirp->loc & ((1 << ISO_SECTOR_SHIFT) - 1); if (off == 0) { lbn = hdbtodb(dirp->loc >> ISO_SECTOR_SHIFT); filep->fi_blocknum = lbn + hdbtodb(ip->i_number); filep->fi_count = ISO_SECTOR_SIZE; /* check the block cache */ if ((filep->fi_memp = get_bcache(filep)) == 0) if (set_bcache(filep)) return ((struct hs_direct *)-1); } dirp->loc += parse_dir(filep, off, &hsdep); if (udp->d_reclen == 0 && dirp->loc <= ip->i_size) { dirp->loc = roundup(dirp->loc, ISO_SECTOR_SIZE); continue; } return (&hsdep); } } /* * Get the next block of data from the file. If possible, dma right into * user's buffer */ static int getblock(fileid_t *filep, caddr_t buf, int count, int *rcount) { register struct inode *ip; register caddr_t p; register int off, size, diff; register daddr_t lbn; static int pos; static char ind[] = "|/-\\"; /* that's entertainment? */ static int blks_read; ip = filep->fi_inode; p = filep->fi_memp; if ((signed)filep->fi_count <= 0) { /* find the amt left to be read in the file */ diff = ip->i_size - filep->fi_offset; if (diff <= 0) { printf("Short read\n"); return (-1); } /* which block (or frag) in the file do we read? */ lbn = hdbtodb(filep->fi_offset >> ISO_SECTOR_SHIFT); /* which physical block on the device do we read? */ filep->fi_blocknum = lbn + hdbtodb(ip->i_number); off = filep->fi_offset & ((1 << ISO_SECTOR_SHIFT) - 1); size = sizeof (filep->fi_buf); if (size > ISO_SECTOR_SIZE) size = ISO_SECTOR_SIZE; filep->fi_count = size; filep->fi_memp = filep->fi_buf; /* * optimization if we are reading large blocks of data then * we can go directly to user's buffer */ *rcount = 0; if (off == 0 && count >= size) { filep->fi_memp = buf; if (diskread(filep)) { return (-1); } *rcount = size; filep->fi_count = 0; read_opt++; if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); return (0); } else if (diskread(filep)) return (-1); /* * round and round she goes (though not on every block.. * - OBP's take a fair bit of time to actually print stuff) */ if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); if (filep->fi_offset - off + size >= ip->i_size) filep->fi_count = diff + off; filep->fi_count -= off; p = &filep->fi_memp[off]; } filep->fi_memp = p; return (0); } /* * This is the high-level read function. It works like this. * We assume that our IO device buffers up some amount of * data ant that we can get a ptr to it. Thus we need * to actually call the device func about filesize/blocksize times * and this greatly increases our IO speed. When we already * have data in the buffer, we just return that data (with bcopy() ). */ static ssize_t boot_hsfs_read(int fd, caddr_t buf, size_t count) { size_t i, j; struct inode *ip; caddr_t n; fileid_t *filep; int rcount; if (!(filep = find_fp(fd))) { return (-1); } ip = filep->fi_inode; if (filep->fi_offset + count > ip->i_size) count = ip->i_size - filep->fi_offset; /* that was easy */ if ((i = count) == 0) return (0); n = buf; while (i > 0) { /* If we need to reload the buffer, do so */ if ((j = filep->fi_count) == 0) { (void) getblock(filep, buf, i, &rcount); i -= rcount; buf += rcount; filep->fi_offset += rcount; } else { /* else just bcopy from our buffer */ j = MIN(i, j); bcopy(filep->fi_memp, buf, (unsigned)j); buf += j; filep->fi_memp += j; filep->fi_offset += j; filep->fi_count -= j; i -= j; } } return (buf - n); } /* * This routine will open a device as it is known by the * V2 OBP. * Interface Defn: * err = mountroot(string); * err: 0 on success * -1 on failure * string: char string describing the properties of the device. * We must not dork with any fi[]'s here. Save that for later. */ static int boot_hsfs_mountroot(char *str) { ihandle_t h; struct hs_volume *fsp; char *bufp; if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("mountroot()\n"); /* * If already mounted, just return success. */ if (root_ino != 0) { return (0); } h = prom_open(str); if (h == 0) { printf("Cannot open %s\n", str); return (-1); } devp = (devid_t *)bkmem_alloc(sizeof (devid_t)); devp->di_taken = 1; devp->di_dcookie = h; devp->di_desc = (char *)bkmem_alloc(strlen(str) + 1); (void) strcpy(devp->di_desc, str); bzero(devp->un_fs.dummy, sizeof (devp->un_fs.dummy)); head = (fileid_t *)bkmem_alloc(sizeof (fileid_t)); head->fi_back = head->fi_forw = head; head->fi_filedes = 0; head->fi_taken = 0; /* Setup read of the "superblock" */ bzero(head->fi_buf, sizeof (head->fi_buf)); head->fi_devp = devp; head->fi_blocknum = hdbtodb(ISO_VOLDESC_SEC); head->fi_count = ISO_SECTOR_SIZE; head->fi_memp = head->fi_buf; head->fi_offset = 0; if (diskread(head)) { printf("mountroot(): read super block failed!\n"); boot_hsfs_closeall(1); return (-1); } bufp = head->fi_memp; fsp = (struct hs_volume *)devp->un_fs.dummy; /* Since RRIP is based on ISO9660, that's where we start */ if (ISO_DESC_TYPE(bufp) != ISO_VD_PVD || strncmp((char *)(ISO_std_id(bufp)), (char *)(ISO_ID_STRING), ISO_ID_STRLEN) != 0 || ISO_STD_VER(bufp) != ISO_ID_VER) { boot_hsfs_closeall(1); return (-1); } /* Now we fill in the volume descriptor */ fsp->vol_size = ISO_VOL_SIZE(bufp); fsp->lbn_size = ISO_BLK_SIZE(bufp); fsp->lbn_shift = ISO_SECTOR_SHIFT; fsp->lbn_secshift = ISO_SECTOR_SHIFT; fsp->vol_set_size = (ushort_t)ISO_SET_SIZE(bufp); fsp->vol_set_seq = (ushort_t)ISO_SET_SEQ(bufp); /* Make sure we have a valid logical block size */ if (fsp->lbn_size & ~(1 << fsp->lbn_shift)) { printf("%d byte logical block size invalid.\n", fsp->lbn_size); boot_hsfs_closeall(1); return (-1); } /* Since an HSFS root could be located anywhere on the media! */ root_ino = IDE_EXT_LBN(ISO_root_dir(bufp)); if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) { int i; printf("root_ino=%d\n", root_ino); printf("ID="); for (i = 0; i < ISO_ID_STRLEN; i++) printf("%c", *(ISO_std_id(bufp)+i)); printf(" VS=%d\n", fsp->vol_size); } return (0); } /* * Unmount the currently mounted root fs. In practice, this means * closing all open files and releasing resources. All of this * is done by boot_hsfs_closeall(). */ int boot_hsfs_unmountroot(void) { if (root_ino == 0) return (-1); boot_hsfs_closeall(1); return (0); } /* * We allocate an fd here for use when talking * to the file itself. */ /*ARGSUSED*/ static int boot_hsfs_open(char *filename, int flags) { fileid_t *filep; ino_t inode; static int filedes = 1; /* build and link a new file descriptor */ filep = (fileid_t *)bkmem_alloc(sizeof (fileid_t)); filep->fi_back = head->fi_back; filep->fi_forw = head; head->fi_back->fi_forw = filep; head->fi_back = filep; filep->fi_filedes = filedes++; filep->fi_taken = 1; filep->fi_path = (char *)bkmem_alloc(strlen(filename) + 1); (void) strcpy(filep->fi_path, filename); filep->fi_devp = devp; /* dev is already "mounted" */ filep->fi_inode = 0; inode = find(filep, filename); if (inode == (ino_t)0) { if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("open(%s) ENOENT\n", filename); (void) boot_hsfs_close(filep->fi_filedes); return (-1); } filep->fi_blocknum = hdbtodb(inode); filep->fi_offset = filep->fi_count = 0; if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("open(%s) fd=%d\n", filename, filep->fi_filedes); return (filep->fi_filedes); } /* * hsfs_fstat() only supports size, mode and times at present time. */ static int boot_hsfs_fstat(int fd, struct bootstat *stp) { fileid_t *filep; struct inode *ip; if (!(filep = find_fp(fd))) return (-1); ip = filep->fi_inode; stp->st_mode = 0; stp->st_size = 0; if (ip == NULL) return (0); switch (ip->i_smode & IFMT) { case IFDIR: stp->st_mode = S_IFDIR; break; case IFREG: stp->st_mode = S_IFREG; break; default: break; } stp->st_size = ip->i_size; /* file times */ stp->st_atim.tv_sec = ip->i_atime.tv_sec; stp->st_atim.tv_nsec = ip->i_atime.tv_usec * 1000; stp->st_mtim.tv_sec = ip->i_mtime.tv_sec; stp->st_mtim.tv_nsec = ip->i_mtime.tv_usec * 1000; stp->st_ctim.tv_sec = ip->i_ctime.tv_sec; stp->st_ctim.tv_nsec = ip->i_ctime.tv_usec * 1000; return (0); } /* * We don't do any IO here. * We just play games with the device pointers. */ /*ARGSUSED*/ static off_t boot_hsfs_lseek(int fd, off_t addr, int whence) { fileid_t *filep; if (!(filep = find_fp(fd))) return (-1); filep->fi_offset = addr; filep->fi_blocknum = addr / DEV_BSIZE; filep->fi_count = 0; return (0); } static int boot_hsfs_close(int fd) { fileid_t *filep; if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("close(%d)\n", fd); if (filep = find_fp(fd)) { /* Clear the ranks */ bkmem_free(filep->fi_path, strlen(filep->fi_path)+1); filep->fi_blocknum = filep->fi_count = filep->fi_offset = 0; filep->fi_memp = (caddr_t)0; filep->fi_devp = 0; filep->fi_taken = 0; /* unlink and deallocate node */ filep->fi_forw->fi_back = filep->fi_back; filep->fi_back->fi_forw = filep->fi_forw; bkmem_free((char *)filep, sizeof (fileid_t)); return (0); } else { /* Big problem */ printf("\nFile descrip %d not allocated!", fd); return (-1); } } /* closeall is now idempotent */ /*ARGSUSED*/ static void boot_hsfs_closeall(int flag) { fileid_t *filep = head; extern int verbosemode; if (devp == NULL) { if (head) prom_panic("boot_hsfs_closeall: head != NULL.\n"); return; } while ((filep = filep->fi_forw) != head) if (filep->fi_taken) if (boot_hsfs_close(filep->fi_filedes)) prom_panic("Filesystem may be inconsistent.\n"); release_cache(devp->di_dcookie); (void) prom_close(devp->di_dcookie); devp->di_taken = 0; if (verbosemode) print_cache_data(); bkmem_free((char *)devp, sizeof (devid_t)); bkmem_free((char *)head, sizeof (fileid_t)); root_ino = 0; devp = NULL; head = NULL; } static uint_t parse_dir(fileid_t *filep, int offset, struct hs_direct *hsdep) { char *bufp = (char *)(filep->fi_memp + offset); struct direct *udp = &hsdep->hs_ufs_dir; struct hs_direntry *hdp = &hsdep->hs_dir; uint_t ce_lbn; uint_t ce_len; uint_t nmlen; uint_t i; uchar_t c; int ret_code = 0; if ((udp->d_reclen = IDE_DIR_LEN(bufp)) == 0) return (0); hdp->ext_lbn = IDE_EXT_LBN(bufp); hdp->ext_size = IDE_EXT_SIZE(bufp); hs_dodates(HS_VOL_TYPE_ISO, hdp, bufp); hdp->xar_len = IDE_XAR_LEN(bufp); hdp->intlf_sz = IDE_INTRLV_SIZE(bufp); hdp->intlf_sk = IDE_INTRLV_SKIP(bufp); hdp->sym_link = NULL; udp->d_ino = hdp->ext_lbn; c = IDE_FLAGS(bufp); if (IDE_REGULAR_FILE(c)) { hdp->type = VREG; hdp->mode = IFREG; hdp->nlink = 1; } else if (IDE_REGULAR_DIR(c)) { hdp->type = VDIR; hdp->mode = IFDIR; hdp->nlink = 2; } else { printf("parse_dir(): file type=0x%x unknown.\n", c); return ((uint_t)-1); } /* Some initial conditions */ nmlen = IDE_NAME_LEN(bufp); c = *IDE_NAME(bufp); /* Special Case: Current Directory */ if (nmlen == 1 && c == '\0') { udp->d_name[0] = '.'; udp->d_name[1] = '\0'; udp->d_namlen = 1; /* Special Case: Parent Directory */ } else if (nmlen == 1 && c == '\001') { udp->d_name[0] = '.'; udp->d_name[1] = '.'; udp->d_name[2] = '\0'; udp->d_namlen = 2; /* Other file name */ } else { udp->d_namlen = 0; for (i = 0; i < nmlen; i++) { c = *(IDE_name(bufp)+i); if (c == ';') break; else if (c == ' ') continue; else udp->d_name[udp->d_namlen++] = c; } udp->d_name[udp->d_namlen] = '\0'; } /* System Use Fields */ ce_len = IDE_SUA_LEN(bufp); ce_lbn = 0; if ((int)(ce_len) > 0) { ce_lbn = parse_susp((char *)IDE_sys_use_area(bufp), &ce_len, hsdep); while (ce_lbn) { daddr_t save_blocknum = filep->fi_blocknum; daddr_t save_offset = filep->fi_offset; caddr_t save_memp = filep->fi_memp; uint_t save_count = filep->fi_count; #ifdef noisy print_io_req(filep, "parse_dir(): [I]"); #endif /* noisy */ filep->fi_blocknum = hdbtodb(ce_lbn); filep->fi_offset = 0; filep->fi_count = ISO_SECTOR_SIZE; #ifdef noisy print_io_req(filep, "parse_dir(): [0]"); #endif /* noisy */ if ((filep->fi_memp = get_bcache(filep)) == 0) ret_code = set_bcache(filep); #ifdef noisy print_io_req(filep, "parse_dir(): [1]"); #endif /* noisy */ if (ret_code) { filep->fi_blocknum = save_blocknum; filep->fi_offset = save_offset; filep->fi_memp = save_memp; filep->fi_count = save_count; printf("parse_dir(): " "set_bcache() failed (%d)\n", ret_code); break; } ce_lbn = parse_susp(filep->fi_memp, &ce_len, hsdep); filep->fi_blocknum = save_blocknum; filep->fi_offset = save_offset; filep->fi_memp = save_memp; filep->fi_count = save_count; #ifdef noisy print_io_req(filep, "parse_dir(): [2]"); #endif /* noisy */ } } return (udp->d_reclen); } static uint_t parse_susp(char *bufp, uint_t *ce_len, struct hs_direct *hsdep) { struct direct *udp = &hsdep->hs_ufs_dir; uchar_t *susp; uint_t cur_off = 0; uint_t blk_len = *ce_len; uint_t susp_len = 0; uint_t ce_lbn = 0; uint_t i; while (cur_off < blk_len) { susp = (uchar_t *)(bufp + cur_off); if (susp[0] == '\0' || susp[1] == '\0') break; susp_len = SUF_LEN(susp); if (susp_len == 0) break; for (i = 0; i < hsfs_num_sig; i++) { if (strncmp(hsfs_sig_tab[i], (char *)susp, SUF_SIG_LEN) == 0) { #ifdef noisy if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf(" SUSP_%c%c %d\n", susp[0], susp[1], susp_len); #endif /* noisy */ switch (i) { case SUSP_SP_IX: if (CHECK_BYTES_OK(susp)) { sua_offset = SP_SUA_OFFSET(susp); #ifdef lint /* this may not be needed */ i = (int)sua_offset; #endif /* lint */ } break; case SUSP_CE_IX: ce_lbn = CE_BLK_LOC(susp); *ce_len = CE_CONT_LEN(susp); #ifdef noisy if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("parse_susp(): " "CE: ce_lbn = %d " "ce_len=%d\n", ce_lbn, *ce_len); #endif /* noisy */ break; case SUSP_ST_IX: printf("parse_susp(): ST: returning " "%d\n", ce_lbn); return (ce_lbn); case RRIP_SL_IX: #ifdef noisy if ((boothowto & RB_DEBUG) && (boothowto & RB_VERBOSE)) printf("parse_susp(): " "******* SL *******\n"); #endif /* noisy */ break; case RRIP_RR_IX: break; case RRIP_NM_IX: if (!RRIP_NAME_FLAGS(susp)) { udp->d_namlen = RRIP_NAME_LEN(susp); bcopy((char *)RRIP_name(susp), (char *)udp->d_name, udp->d_namlen); udp->d_name [udp->d_namlen] = '\0'; } break; } cur_off += susp_len; break; } } if (i > hsfs_num_sig) { printf("parse_susp(): Bad SUSP\n"); cur_off = blk_len; break; } } return (ce_lbn); } static void hs_seti(fileid_t *filep, struct hs_direct *hsdep, ino_t inode) { register struct inode *ip; int dv = filep->fi_devp->di_dcookie; /* Try the inode cache first */ if ((filep->fi_inode = get_icache(dv, inode)) != NULL) return; filep->fi_inode = (struct inode *)bkmem_alloc(sizeof (struct inode)); ip = filep->fi_inode; bzero((char *)ip, sizeof (struct inode)); ip->i_size = hsdep->hs_dir.ext_size; ip->i_smode = hsdep->hs_dir.mode; ip->i_number = inode; ip->i_atime.tv_sec = hsdep->hs_dir.adate.tv_sec; ip->i_atime.tv_usec = hsdep->hs_dir.adate.tv_usec; ip->i_ctime.tv_sec = hsdep->hs_dir.cdate.tv_sec; ip->i_ctime.tv_usec = hsdep->hs_dir.cdate.tv_usec; ip->i_mtime.tv_sec = hsdep->hs_dir.mdate.tv_sec; ip->i_mtime.tv_usec = hsdep->hs_dir.mdate.tv_usec; set_icache(dv, inode, ip, sizeof (struct inode)); } #ifdef noisy static void print_io_req(fileid_t *filep, char *str) { printf("%s o=%d b=%d c=%d m=%x\n", str, filep->fi_offset, filep->fi_blocknum, filep->fi_count, (uint_t)filep->fi_memp); } #endif /* noisy */ static int boot_hsfs_getdents(int fd, struct dirent *dep, unsigned size) { /* * Read directory entries from the file open on "fd" into the * "size"-byte buffer at "dep" until the buffer is exhausted * or we reach EOF on the directory. Returns the number of * entries read. */ int n; int cnt = 0; struct dirinfo dir; struct hs_direct *hdp; unsigned long oldoff, oldblok; #define SLOP (sizeof (struct dirent) - offsetof(struct dirent, d_name[1])) if (!(dir.fi = find_fp(fd)) || ((dir.fi->fi_inode->i_smode & IFMT) != IFDIR)) { /* * Bogus file descriptor, bail out now! */ return (-1); } oldoff = dir.loc = dir.fi->fi_offset; oldblok = dir.fi->fi_blocknum; for (hdp = readdir(&dir); hdp; hdp = readdir(&dir)) { /* * Compute name length and break loop if there's not * enough space in the output buffer for the next * entry. * * NOTE: "SLOP" is the number of bytes inserted into the dirent * struct's "d_name" field by the compiler to preserve * alignment. */ n = strlen(hdp->hs_ufs_dir.d_name); n = roundup((sizeof (struct dirent) + ((n > SLOP) ? n : 0)), sizeof (off_t)); if (n > size) { dir.fi->fi_blocknum = oldblok; dir.fi->fi_offset = oldoff; break; } oldblok = dir.fi->fi_blocknum; oldoff = dir.loc; size -= n; cnt += 1; (void) strlcpy(dep->d_name, hdp->hs_ufs_dir.d_name, strlen(hdp->hs_ufs_dir.d_name) + 1); dep->d_ino = hdp->hs_ufs_dir.d_ino; dep->d_off = dir.loc; dep->d_reclen = (unsigned short)n; dep = (struct dirent *)((char *)dep + n); } #undef SLOP return (cnt); } static void hs_dodates(enum hs_vol_type type, struct hs_direntry *hdp, char *bufp) { if (type == HS_VOL_TYPE_HS) { hs_parse_dirdate(HDE_cdate(bufp), &hdp->cdate); hs_parse_dirdate(HDE_cdate(bufp), &hdp->adate); hs_parse_dirdate(HDE_cdate(bufp), &hdp->mdate); } else if (type == HS_VOL_TYPE_ISO) { hs_parse_dirdate(IDE_cdate(bufp), &hdp->cdate); hs_parse_dirdate(IDE_cdate(bufp), &hdp->adate); hs_parse_dirdate(IDE_cdate(bufp), &hdp->mdate); } else prom_panic("hs_dodates: bad volume type"); } /* * hs_parse_dirdate * * Parse the short 'directory-format' date into a Unix timeval. * This is the date format used in Directory Entries. * * If the date is not representable, make something up. */ void hs_parse_dirdate(uchar_t *dp, struct timeval *tvp) { int year, month, day, hour, minute, sec, gmtoff; year = HDE_DATE_YEAR(dp); month = HDE_DATE_MONTH(dp); day = HDE_DATE_DAY(dp); hour = HDE_DATE_HOUR(dp); minute = HDE_DATE_MIN(dp); sec = HDE_DATE_SEC(dp); gmtoff = HDE_DATE_GMTOFF(dp); tvp->tv_usec = 0; if (year < THE_EPOCH) { tvp->tv_sec = 0; } else { tvp->tv_sec = hs_date_to_gmtime(year, month, day, gmtoff); if (tvp->tv_sec != -1) { tvp->tv_sec += ((hour * 60) + minute) * 60 + sec; } } return; } /* * hs_parse_longdate * * Parse the long 'user-oriented' date into a Unix timeval. * This is the date format used in the Volume Descriptor. * * If the date is not representable, make something up. */ void hs_parse_longdate(uchar_t *dp, struct timeval *tvp) { int year, month, day, hour, minute, sec, gmtoff; year = HSV_DATE_YEAR(dp); month = HSV_DATE_MONTH(dp); day = HSV_DATE_DAY(dp); hour = HSV_DATE_HOUR(dp); minute = HSV_DATE_MIN(dp); sec = HSV_DATE_SEC(dp); gmtoff = HSV_DATE_GMTOFF(dp); tvp->tv_usec = 0; if (year < THE_EPOCH) { tvp->tv_sec = 0; } else { tvp->tv_sec = hs_date_to_gmtime(year, month, day, gmtoff); if (tvp->tv_sec != -1) { tvp->tv_sec += ((hour * 60) + minute) * 60 + sec; tvp->tv_usec = HSV_DATE_HSEC(dp) * 10000; } } } /* cumulative number of seconds per month, non-leap and leap-year versions */ static time_t cum_sec[] = { 0x0, 0x28de80, 0x4dc880, 0x76a700, 0x9e3400, 0xc71280, 0xee9f80, 0x1177e00, 0x1405c80, 0x167e980, 0x190c800, 0x1b85500 }; static time_t cum_sec_leap[] = { 0x0, 0x28de80, 0x4f1a00, 0x77f880, 0x9f8580, 0xc86400, 0xeff100, 0x118cf80, 0x141ae00, 0x1693b00, 0x1921980, 0x1b9a680 }; #define SEC_PER_DAY 0x15180 #define SEC_PER_YEAR 0x1e13380 /* * hs_date_to_gmtime * * Convert year(1970-2099)/month(1-12)/day(1-31) to seconds-since-1970/1/1. * * Returns -1 if the date is out of range. */ static time_t hs_date_to_gmtime(int year, int mon, int day, int gmtoff) { time_t sum; time_t *cp; int y; if ((year < THE_EPOCH) || (year > END_OF_TIME) || (mon < 1) || (mon > 12) || (day < 1) || (day > 31)) return (-1); /* * Figure seconds until this year and correct for leap years. * Note: 2000 is a leap year but not 2100. */ y = year - THE_EPOCH; sum = y * SEC_PER_YEAR; sum += ((y + 1) / 4) * SEC_PER_DAY; /* * Point to the correct table for this year and * add in seconds until this month. */ cp = ((y + 2) % 4) ? cum_sec : cum_sec_leap; sum += cp[mon - 1]; /* * Add in seconds until 0:00 of this day. * (days-per-month validation is not done here) */ sum += (day - 1) * SEC_PER_DAY; sum -= (gmtoff * 15 * 60); return (sum); } # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2004 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # LIBRARY = libnfs.a LOCOBJS = auth_none.o auth_unix.o bootparams.o getdents.o \ getdents3.o getdents4.o lookup.o mount.o \ nfsops.o nfs2ops.o nfs3ops.o nfs4ops.o pathname.o pmap.o rpc.o \ clnt_budp.o clnt_btcp.o nfs_xdr.o nfs3_xdr.o nfs4_xdr.o xdr_rec.o RPC_CMNOBJS = rpc_prot.o CMNOBJS = bootparam_xdr.o OBJECTS = $(LOCOBJS) $(RPC_CMNOBJS) $(CMNOBJS) include ../Makefile.com RPC_CMNDIR = $(TOPDIR)/uts/common/rpc CMNDIR = $(TOPDIR)/uts/common/fs/nfs SRCS = $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(RPC_CMNOBJS:%.o=$(RPC_CMNDIR)/%.c) \ $(CMNOBJS:%.o=$(CMNDIR)/%.c) LDLIBS += -linet -lsock -lxdr CPPFLAGS += $(SOCKCPPFLAGS) $(DHCPCPPFLAGS) -I../../inet CPPFLAGS += -I$(STANDDIR)/lib/sa -I$(TOPDIR)/head # # This is really wrong, but we have no choice since needs to # resolve types that are in . Thankfully, we don't use # anything from libsock.a that relies on the definition of an mblk_t. # CPPFLAGS += -U_SYS_STREAM_H objs/%.o: $(RPC_CMNDIR)/%.c $(COMPILE.c) -o $@ $< $(POST_PROCESS_O) include ../../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1997-1999 by Sun Microsystems, Inc. * All rights reserved. */ #ifndef _AUTH_INET_H #define _AUTH_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif extern struct opaque_auth _null_auth; extern AUTH *authnone_create(void); extern AUTH *authunix_create(char *, uid_t, gid_t, int, gid_t *); #ifdef __cplusplus } #endif #endif /* _AUTH_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* from SunOS 4.1 */ #pragma ident "%Z%%M% %I% %E% SMI" /* * modified for use by the boot program. * * auth_none.c * Creates a client authentication handle for passing "null" * credentials and verifiers to remote systems. */ #include #include #include #include "clnt.h" #define MAX_MARSHEL_SIZE 20 static struct auth_ops *authnone_ops(); static struct authnone_private { AUTH no_client; char marshalled_client[MAX_MARSHEL_SIZE]; uint_t mcnt; } *authnone_private; static struct authnone_private authnone_local; AUTH * authnone_create(void) { struct authnone_private *ap = authnone_private; XDR xdr_stream; XDR *xdrs; if (ap == 0) { ap = &authnone_local; authnone_private = ap; } if (!ap->mcnt) { ap->no_client.ah_cred = ap->no_client.ah_verf = _null_auth; ap->no_client.ah_ops = authnone_ops(); xdrs = &xdr_stream; xdrmem_create(xdrs, ap->marshalled_client, (uint_t)MAX_MARSHEL_SIZE, XDR_ENCODE); (void) xdr_opaque_auth(xdrs, &ap->no_client.ah_cred); (void) xdr_opaque_auth(xdrs, &ap->no_client.ah_verf); ap->mcnt = XDR_GETPOS(xdrs); XDR_DESTROY(xdrs); } return (&ap->no_client); } /*ARGSUSED*/ static bool_t authnone_marshal(AUTH *client, XDR *xdrs, struct cred *cr) { struct authnone_private *ap = authnone_private; if (ap == 0) return (0); return ((*xdrs->x_ops->x_putbytes)(xdrs, ap->marshalled_client, ap->mcnt)); } /* ARGSUSED */ static void authnone_verf(AUTH *foo) { } /* ARGSUSED */ static bool_t authnone_validate(AUTH *foo, struct opaque_auth *bar) { return (TRUE); } /* ARGSUSED */ static bool_t authnone_refresh(AUTH *foo, struct rpc_msg *bar, cred_t *cr) { return (FALSE); } /* ARGSUSED */ static void authnone_destroy(AUTH *foo) { } static struct auth_ops * authnone_ops(void) { static struct auth_ops ops; if (ops.ah_nextverf == NULL) { ops.ah_nextverf = authnone_verf; ops.ah_marshal = authnone_marshal; ops.ah_validate = authnone_validate; ops.ah_refresh = authnone_refresh; ops.ah_destroy = authnone_destroy; } return (&ops); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ /* * Adapted for use by the boot program. * * auth_unix.c, Implements UNIX style authentication parameters. * * The system is very weak. The client uses no encryption for its * credentials and only sends null verifiers. The server sends backs * null verifiers or optionally a verifier that suggests a new short hand * for the credentials. */ #include #include #include #include #include #include "clnt.h" #include #include #include #include #include "nfs_inet.h" static struct auth_ops *authunix_ops(); /* * This struct is pointed to by the ah_private field of an auth_handle. */ struct audata { struct opaque_auth au_origcred; /* original credentials */ struct opaque_auth au_shcred; /* short hand cred */ uint_t au_shfaults; /* short hand cache faults */ char au_marshed[MAX_AUTH_BYTES]; uint_t au_mpos; /* xdr pos at end of marshed */ }; #define AUTH_PRIVATE(auth) ((struct audata *)auth->ah_private) static void marshal_new_auth(AUTH *); #define dprintf if (boothowto & RB_DEBUG) printf /* * Create a unix style authenticator. * Returns an auth handle with the given stuff in it. */ AUTH * authunix_create(char *machname, uid_t uid, gid_t gid, int len, gid_t *aup_gids) { struct authunix_parms aup; char mymem[MAX_AUTH_BYTES]; XDR xdrs; AUTH *auth; struct audata *au; /* * Allocate and set up auth handle */ auth = (AUTH *) bkmem_alloc(sizeof (*auth)); if (auth == NULL) { prom_panic("authunix_create: Cannot allocate memory."); } au = (struct audata *)bkmem_alloc(sizeof (*au)); if (au == NULL) { prom_panic("authunix_create: Cannot allocate memory."); } /* setup authenticator. */ auth->ah_ops = authunix_ops(); auth->ah_private = (caddr_t)au; /* structure copies */ auth->ah_verf = au->au_shcred = _null_auth; au->au_shfaults = 0; /* * fill in param struct from the given params */ aup.aup_time = prom_gettime() / 1000; aup.aup_machname = machname; aup.aup_uid = uid; aup.aup_gid = gid; aup.aup_len = (uint_t)len; aup.aup_gids = (gid_t *)aup_gids; /* * Serialize the parameters into origcred */ xdrmem_create(&xdrs, mymem, MAX_AUTH_BYTES, XDR_ENCODE); if (!xdr_authunix_parms(&xdrs, &aup)) { prom_panic("authunix_create: xdr_authunix_parms failed"); } au->au_origcred.oa_length = len = XDR_GETPOS(&xdrs); au->au_origcred.oa_flavor = (uint_t)AUTH_UNIX; if ((au->au_origcred.oa_base = bkmem_alloc((uint_t)len)) == NULL) { prom_panic("authunix_create: memory alloc failed"); } (void) bcopy(mymem, au->au_origcred.oa_base, (uint_t)len); /* * set auth handle to reflect new cred. */ auth->ah_cred = au->au_origcred; marshal_new_auth(auth); return (auth); } /* * authunix operations */ /* ARGSUSED */ static void authunix_nextverf(AUTH *auth) { } /* ARGSUSED */ static bool_t authunix_marshal(AUTH *auth, XDR *xdrs, cred_t *cr) { struct audata *au = AUTH_PRIVATE(auth); return (XDR_PUTBYTES(xdrs, au->au_marshed, au->au_mpos)); } static bool_t authunix_validate(AUTH *auth, struct opaque_auth *verf) { struct audata *au; XDR xdrs; if (verf->oa_flavor == AUTH_SHORT) { au = AUTH_PRIVATE(auth); xdrmem_create(&xdrs, verf->oa_base, verf->oa_length, XDR_DECODE); if (xdr_opaque_auth(&xdrs, &au->au_shcred)) { auth->ah_cred = au->au_shcred; } else { xdrs.x_op = XDR_FREE; (void) xdr_opaque_auth(&xdrs, &au->au_shcred); au->au_shcred.oa_base = 0; auth->ah_cred = au->au_origcred; } marshal_new_auth(auth); } return (TRUE); } /*ARGSUSED*/ static bool_t authunix_refresh(AUTH *auth, struct rpc_msg *msg, cred_t *cr) { struct audata *au = AUTH_PRIVATE(auth); struct authunix_parms aup; XDR xdrs; int stat; if (auth->ah_cred.oa_base == au->au_origcred.oa_base) { /* there is no hope. Punt */ return (FALSE); } au->au_shfaults ++; /* first deserialize the creds back into a struct authunix_parms */ aup.aup_machname = (char *)0; aup.aup_gids = (gid_t *)0; xdrmem_create(&xdrs, au->au_origcred.oa_base, au->au_origcred.oa_length, XDR_DECODE); stat = xdr_authunix_parms(&xdrs, &aup); if (!stat) goto done; /* update the time and serialize in place */ aup.aup_time = (prom_gettime() / 1000); xdrs.x_op = XDR_ENCODE; (void) XDR_SETPOS(&xdrs, 0); stat = xdr_authunix_parms(&xdrs, &aup); if (!stat) goto done; auth->ah_cred = au->au_origcred; marshal_new_auth(auth); done: /* free the struct authunix_parms created by deserializing */ xdrs.x_op = XDR_FREE; (void) xdr_authunix_parms(&xdrs, &aup); XDR_DESTROY(&xdrs); return (stat); } static void authunix_destroy(AUTH *auth) { struct audata *au = AUTH_PRIVATE(auth); if (au->au_shcred.oa_base != NULL) bkmem_free(au->au_shcred.oa_base, au->au_shcred.oa_length); bkmem_free(auth->ah_private, sizeof (struct audata)); if (auth->ah_verf.oa_base != NULL) bkmem_free(auth->ah_verf.oa_base, auth->ah_verf.oa_length); bkmem_free((caddr_t)auth, sizeof (*auth)); } /* * Marshals (pre-serializes) an auth struct. * sets private data, au_marshed and au_mpos */ static void marshal_new_auth(AUTH *auth) { XDR xdr_stream; XDR *xdrs = &xdr_stream; struct audata *au = AUTH_PRIVATE(auth); xdrmem_create(xdrs, au->au_marshed, MAX_AUTH_BYTES, XDR_ENCODE); if ((!xdr_opaque_auth(xdrs, &(auth->ah_cred))) || (!xdr_opaque_auth(xdrs, &(auth->ah_verf)))) { dprintf("marshal_new_auth - Fatal marshalling problem"); } else { au->au_mpos = XDR_GETPOS(xdrs); } XDR_DESTROY(xdrs); } static struct auth_ops * authunix_ops(void) { static struct auth_ops ops; if (ops.ah_nextverf == 0) { ops.ah_nextverf = authunix_nextverf; ops.ah_marshal = authunix_marshal; ops.ah_validate = authunix_validate; ops.ah_refresh = authunix_refresh; ops.ah_destroy = authunix_destroy; } return (&ops); } /* * XDR for unix authentication parameters. */ bool_t xdr_authunix_parms(XDR *xdrs, struct authunix_parms *p) { if (xdr_u_int(xdrs, &(p->aup_time)) && xdr_string(xdrs, &(p->aup_machname), MAX_MACHINE_NAME) && xdr_int(xdrs, (int *)&(p->aup_uid)) && xdr_int(xdrs, (int *)&(p->aup_gid)) && xdr_array(xdrs, (caddr_t *)&(p->aup_gids), &(p->aup_len), NGRPS, sizeof (int), xdr_int)) { return (TRUE); } return (FALSE); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * This file contains routines responsible for getting the system's * name and boot params. Most of it comes from the SVR4 diskless boot * code (dlboot_inet), modified to work in a non socket environment. */ #include #include #include #include #include #include #include #include "clnt.h" #include #include #include #include #include #include #include #include #include #include "pmap.h" #include "brpc.h" #include "socket_inet.h" #include "ipv4.h" #include #include extern int errno; static struct bp_whoami_res bp; static char bp_hostname[SYS_NMLN+1]; static char bp_domainname[SYS_NMLN+1]; static struct in_addr responder; /* network order */ static const char *noserver = "No bootparam (%s) server responding; still trying...\n"; #define GETFILE_BTIMEO 1 #define GETFILE_BRETRIES 2 #define dprintf if (boothowto & RB_DEBUG) printf /* * Returns TRUE if it has set the global structure 'bp' to our boot * parameters, FALSE if some failure occurred. */ bool_t whoami(void) { struct bp_whoami_arg arg; struct sockaddr_in to, from; struct in_addr ipaddr; enum clnt_stat stat; bool_t retval = TRUE; int rexmit; /* retransmission interval */ int resp_wait; /* secs to wait for resp */ int namelen; int printed_waiting_msg; /* * Set our destination IP address to the limited broadcast address * (INADDR_BROADCAST). */ to.sin_family = AF_INET; to.sin_addr.s_addr = htonl(INADDR_BROADCAST); to.sin_port = htons(0); /* * Set up the arguments expected by bootparamd. */ arg.client_address.address_type = IP_ADDR_TYPE; ipv4_getipaddr(&ipaddr); ipaddr.s_addr = htonl(ipaddr.s_addr); bcopy((caddr_t)&ipaddr, (caddr_t)&arg.client_address.bp_address_u.ip_addr, sizeof (ipaddr)); /* * Retransmit/wait for up to resp_wait secs. */ rexmit = 0; /* start at default retransmission interval. */ resp_wait = 16; bp.client_name = &bp_hostname[0]; bp.domain_name = &bp_domainname[0]; /* * Do a broadcast call to find a bootparam daemon that * will tell us our hostname, domainname and any * router that we have to use to talk to our NFS server. */ printed_waiting_msg = 0; do { /* * First try the SunOS portmapper and if no reply is * received will then try the SVR4 rpcbind. * Either way, `bootpaddr' will be set to the * correct address for the bootparamd that responds. */ stat = bpmap_rmtcall((rpcprog_t)BOOTPARAMPROG, (rpcvers_t)BOOTPARAMVERS, (rpcproc_t)BOOTPARAMPROC_WHOAMI, xdr_bp_whoami_arg, (caddr_t)&arg, xdr_bp_whoami_res, (caddr_t)&bp, rexmit, resp_wait, &to, &from, AUTH_NONE); if (stat == RPC_TIMEDOUT && !printed_waiting_msg) { dprintf(noserver, "whoami"); printed_waiting_msg = 1; } /* * Retransmission interval for second and subsequent tries. * We expect first bpmap_rmtcall to retransmit and backoff to * at least this value. */ rexmit = resp_wait; resp_wait = 0; /* go to default wait now. */ } while (stat == RPC_TIMEDOUT); if (stat != RPC_SUCCESS) { dprintf("whoami RPC call failed with rpc status: %d\n", stat); retval = FALSE; goto done; } else { if (printed_waiting_msg && (boothowto & RB_VERBOSE)) printf("Bootparam response received\n"); /* Cache responder... We'll send our getfile here... */ responder.s_addr = from.sin_addr.s_addr; } namelen = strlen(bp.client_name); if (namelen > SYS_NMLN) { dprintf("whoami: hostname too long"); retval = FALSE; goto done; } if (namelen > 0) { if (boothowto & RB_VERBOSE) printf("hostname: %s\n", bp.client_name); (void) sethostname(bp.client_name, namelen); } else { dprintf("whoami: no host name\n"); retval = FALSE; goto done; } namelen = strlen(bp.domain_name); if (namelen > SYS_NMLN) { dprintf("whoami: domainname too long"); retval = FALSE; goto done; } if (namelen > 0) if (boothowto & RB_VERBOSE) printf("domainname: %s\n", bp.domain_name); else dprintf("whoami: no domain name\n"); if (bp.router_address.address_type == IP_ADDR_TYPE) { bcopy((caddr_t)&bp.router_address.bp_address_u.ip_addr, (caddr_t)&ipaddr, sizeof (ipaddr)); if (ntohl(ipaddr.s_addr) != INADDR_ANY) { dprintf("whoami: Router ip is: %s\n", inet_ntoa(ipaddr)); /* ipv4_route expects IP addresses in network order */ (void) ipv4_route(IPV4_ADD_ROUTE, RT_DEFAULT, NULL, &ipaddr); } } else dprintf("whoami: unknown gateway addr family %d\n", bp.router_address.address_type); done: return (retval); } /* * Returns: * 1) The ascii form of our root servers name in `server_name'. * 2) Pathname of our root on the server in `server_path'. * * NOTE: it's ok for getfile() to do dynamic allocation - it's only * used locally, then freed. If the server address returned from the * getfile call is different from our current destination address, * reset destination IP address to the new value. */ bool_t getfile(char *fileid, char *server_name, struct in_addr *server_ip, char *server_path) { struct bp_getfile_arg arg; struct bp_getfile_res res; enum clnt_stat stat; struct sockaddr_in to, from; int rexmit; int wait; uint_t max_retries = 0xFFFFFFFF; int def_rexmit = 0; int def_wait = 32; int printed_waiting_msg; /* * For non-root requests, set a smaller timeout */ if (strcmp(fileid, "root") != 0) { /* * Only send one request per call */ def_wait = GETFILE_BTIMEO; def_rexmit = GETFILE_BTIMEO; max_retries = GETFILE_BRETRIES; } arg.client_name = bp.client_name; arg.file_id = fileid; res.server_name = (bp_machine_name_t)bkmem_zalloc(SYS_NMLN + 1); res.server_path = (bp_path_t)bkmem_zalloc(SYS_NMLN + 1); if (res.server_name == NULL || res.server_path == NULL) { dprintf("getfile: rpc_call failed: No memory\n"); errno = ENOMEM; if (res.server_name != NULL) bkmem_free(res.server_name, SYS_NMLN + 1); if (res.server_path != NULL) bkmem_free(res.server_path, SYS_NMLN + 1); return (FALSE); } to.sin_family = AF_INET; to.sin_addr.s_addr = responder.s_addr; to.sin_port = htons(0); /* * Our addressing information was filled in by the call to * whoami(), so now send an rpc message to the * bootparam daemon requesting our server information. * * Wait only 32 secs for rpc_call to succeed. */ rexmit = def_rexmit; wait = def_wait; stat = brpc_call((rpcprog_t)BOOTPARAMPROG, (rpcvers_t)BOOTPARAMVERS, (rpcproc_t)BOOTPARAMPROC_GETFILE, xdr_bp_getfile_arg, (caddr_t)&arg, xdr_bp_getfile_res, (caddr_t)&res, rexmit, wait, &to, &from, AUTH_NONE); if (stat == RPC_TIMEDOUT) { /* * The server that answered the whoami doesn't * answer our getfile. Broadcast the call to all. Keep * trying forever. Set up for limited broadcast. */ to.sin_addr.s_addr = htonl(INADDR_BROADCAST); to.sin_port = htons(0); rexmit = def_rexmit; /* use default rexmit interval */ wait = def_wait; printed_waiting_msg = 0; do { /* * Limit the number of retries */ if (max_retries-- == 0) break; stat = bpmap_rmtcall((rpcprog_t)BOOTPARAMPROG, (rpcvers_t)BOOTPARAMVERS, (rpcproc_t)BOOTPARAMPROC_GETFILE, xdr_bp_getfile_arg, (caddr_t)&arg, xdr_bp_getfile_res, (caddr_t)&res, rexmit, wait, &to, &from, AUTH_NONE); if (stat == RPC_SUCCESS) { /* * set our destination addresses to * those of the server that responded. * It's probably our server, and we * can thus save arping for no reason later. */ responder.s_addr = from.sin_addr.s_addr; if (printed_waiting_msg && (boothowto & RB_VERBOSE)) { printf( "Bootparam response received.\n"); } break; } if (stat == RPC_TIMEDOUT && !printed_waiting_msg) { dprintf(noserver, "getfile"); printed_waiting_msg = 1; } /* * Retransmission interval for second and * subsequent tries. We expect first bpmap_rmtcall * to retransmit and backoff to at least this * value. */ rexmit = wait; wait = def_wait; } while (stat == RPC_TIMEDOUT); } if (stat == RPC_SUCCESS) { /* got the goods */ bcopy(res.server_name, server_name, strlen(res.server_name)); bcopy(res.server_path, server_path, strlen(res.server_path)); switch (res.server_address.address_type) { case IP_ADDR_TYPE: /* * server_address is where we will get our root * from. Replace destination entries in address if * necessary. */ bcopy((caddr_t)&res.server_address.bp_address_u.ip_addr, (caddr_t)server_ip, sizeof (struct in_addr)); break; default: dprintf("getfile: unknown address type %d\n", res.server_address.address_type); server_ip->s_addr = htonl(INADDR_ANY); bkmem_free(res.server_name, SYS_NMLN + 1); bkmem_free(res.server_path, SYS_NMLN + 1); return (FALSE); } } else { dprintf("getfile: rpc_call failed.\n"); bkmem_free(res.server_name, SYS_NMLN + 1); bkmem_free(res.server_path, SYS_NMLN + 1); return (FALSE); } bkmem_free(res.server_name, SYS_NMLN + 1); bkmem_free(res.server_path, SYS_NMLN + 1); return (TRUE); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _BRPC_H #define _BRPC_H #pragma ident "%Z%%M% %I% %E% SMI" #include #ifdef __cplusplus extern "C" { #endif #define RPC_ALLOWABLE_ERRORS (10) /* Threshold on receiving bad results */ #define RPC_REXMIT_MSEC (500) /* default 1/2 second retransmissions */ #define RPC_RCVWAIT_MSEC (20000) /* default response waittime */ extern enum clnt_stat brpc_call(rpcprog_t, rpcvers_t, rpcproc_t, xdrproc_t, caddr_t, xdrproc_t, caddr_t, int, int, struct sockaddr_in *, struct sockaddr_in *, uint_t); extern void rpc_disperr(struct rpc_err *stat); #ifdef __cplusplus } #endif #endif /* _BRPC_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * clnt.h - Client side remote procedure call interface. * Stripped down sockets based client for boot. */ #ifndef _RPC_CLNT_H #define _RPC_CLNT_H #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Error info. */ struct rpc_err { enum clnt_stat re_status; union { int RE_errno; /* realated system error */ enum auth_stat RE_why; /* why the auth error occurred */ } ru; #define re_errno ru.RE_errno #define re_why ru.RE_why }; /* * Client rpc handle. * Created by individual implementations, see e.g. rpc_udp.c. * Client is responsible for initializing auth, see e.g. auth_none.c. */ typedef struct __client { AUTH *cl_auth; /* authenticator */ struct clnt_ops { /* call remote procedure */ enum clnt_stat (*cl_call)(struct __client *, rpcproc_t, xdrproc_t, caddr_t, xdrproc_t, caddr_t, struct timeval); /* abort a call */ void (*cl_abort)(/* various */); /* get specific error code */ void (*cl_geterr)(struct __client *, struct rpc_err *); /* frees results */ bool_t (*cl_freeres)(struct __client *, xdrproc_t, caddr_t); /* destroy this structure */ void (*cl_destroy)(struct __client *); /* the ioctl() of rpc */ bool_t (*cl_control)(struct __client *, int, char *); } *cl_ops; caddr_t cl_private; /* private stuff */ } CLIENT; /* * client side rpc interface ops * * Parameter types are: * */ /* * enum clnt_stat * CLNT_CALL(rh, proc, xargs, argsp, xres, resp, timeout) * CLIENT *rh; * ulong_t proc; * xdrproc_t xargs; * caddr_t argsp; * xdrproc_t xres; * caddr_t resp; * struct timeval timeout; */ #define CLNT_CALL(rh, proc, xargs, argsp, xres, resp, secs) \ ((*(rh)->cl_ops->cl_call)(rh, proc, xargs, argsp, xres, resp, secs)) /* * void * CLNT_ABORT(rh); * CLIENT *rh; */ #define CLNT_ABORT(rh) ((*(rh)->cl_ops->cl_abort)(rh)) /* * struct rpc_err * CLNT_GETERR(rh); * CLIENT *rh; */ #define CLNT_GETERR(rh, errp) ((*(rh)->cl_ops->cl_geterr)(rh, errp)) /* * bool_t * CLNT_FREERES(rh, xres, resp); * CLIENT *rh; * xdrproc_t xres; * caddr_t resp; */ #define CLNT_FREERES(rh, xres, resp) ((*(rh)->cl_ops->cl_freeres)\ (rh, xres, resp)) /* * bool_t * CLNT_CONTROL(cl, request, info) * CLIENT *cl; * uint_t request; * char *info; */ #define CLNT_CONTROL(cl, rq, in) ((*(cl)->cl_ops->cl_control)(cl, rq, in)) /* * control operations that apply to both udp and tcp transports */ #define CLSET_TIMEOUT 1 /* set timeout (timeval) */ #define CLGET_TIMEOUT 2 /* get timeout (timeval) */ #define CLGET_SERVER_ADDR 3 /* get server's address (sockaddr) */ #define CLGET_FD 6 /* get connections file descriptor */ #define CLSET_FD_CLOSE 8 /* close fd while clnt_destroy */ #define CLSET_FD_NCLOSE 9 /* Do not close fd while clnt_destroy */ /* * udp only control operations */ #define CLSET_RETRY_TIMEOUT 4 /* set retry timeout (timeval) */ #define CLGET_RETRY_TIMEOUT 5 /* get retry timeout (timeval) */ /* * void * CLNT_DESTROY(rh); * CLIENT *rh; */ #define CLNT_DESTROY(rh) ((*(rh)->cl_ops->cl_destroy)(rh)) /* * By convention, procedure 0 takes null arguments and returns them */ #define NULLPROC ((ulong_t)0) /* * Below are the client handle creation routines for the various * implementations of client side rpc. They can return NULL if a * creation failure occurs. */ /* * UDP based rpc. * CLIENT * * clntbudp_create(raddr, program, version, wait, sockp) * struct sockaddr_in *raddr; * ulong_t program; * ulong_t version; * struct timeval wait; * int *sockp; * * Same as above, but you specify max packet sizes. * CLIENT * * clntbudp_bufcreate(raddr, program, version, wait, sockp, sendsz, recvsz) * struct sockaddr_in *raddr; * ulong_t program; * ulong_t version; * struct timeval wait; * int *sockp; * uint_t sendsz; * uint_t recvsz; */ extern CLIENT *clntbudp_create(struct sockaddr_in *raddr, rpcprog_t program, rpcvers_t version, struct timeval wait, int *sockp); extern CLIENT *clntbudp_bufcreate(struct sockaddr_in *raddr, rpcprog_t program, rpcvers_t version, struct timeval wait, int *sockp, uint_t sendsz, uint_t recvsz); /* * TCP based rpc. * CLIENT * * clntbtcp_create(raddr, program, version, wait, sockp, sendsz, recvsz) * struct sockaddr_in *raddr; * ulong_t program; * ulong_t version; * struct timeval wait; * int *sockp; * uint_t sendsz; * uint_t recvsz; * */ extern CLIENT *clntbtcp_create(struct sockaddr_in *raddr, rpcprog_t program, rpcvers_t version, struct timeval wait, int *sockp, uint_t sendsz, uint_t recvsz); /* * If a creation fails, the following allows the user to figure out why. */ struct rpc_createerr { enum clnt_stat cf_stat; struct rpc_err cf_error; /* useful when cf_stat == RPC_PMAPFAILURE */ }; extern struct rpc_createerr rpc_createerr; #define UDPMSGSIZE 8800 /* rpc imposed limit on udp msg size */ #define RPCSMALLMSGSIZE 400 /* a more reasonable packet size */ #define TCPMSGSIZE (32 * 1024) /* reasonably sized RPC/TCP msg */ #ifdef __cplusplus } #endif #endif /* !_RPC_CLNT_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ /* * Boot subsystem client side rpc (TCP) */ #include #include #include #include #include #include "socket_inet.h" #include "ipv4.h" #include "clnt.h" #include #include "brpc.h" #include "pmap.h" #include #include #include #include #include "auth_inet.h" #include #include #define dprintf if (boothowto & RB_DEBUG) printf #define MCALL_MSG_SIZE 24 extern int errno; extern void xdrrec_create(); extern bool_t xdrrec_endofrecord(); extern bool_t xdrrec_skiprecord(); /* * If we create another clnt type this should be * moved to a common file */ struct rpc_createerr rpc_createerr; static int readtcp(); static int writetcp(); static struct clnt_ops *clntbtcp_ops(); /* * Private data kept per client handle */ struct ct_data { int ct_sock; bool_t ct_closeit; struct sockaddr_in ct_raddr; uint_t ct_wait_msec; struct timeval ct_total; struct rpc_err ct_error; XDR ct_xdrs; char ct_mcall[MCALL_MSG_SIZE]; uint_t ct_mpos; uint_t ct_xdrpos; }; /* * Create a TCP based client handle. * If *sockp<0, *sockp is set to a newly created TCP socket. * If raddr->sin_port is 0 a binder on the remote machine * is consulted for the correct port number. * NB: It is the clients responsibility to close *sockp. * NB: The rpch->cl_auth is initialized to null authentication. * Caller may wish to set this something more useful. * * wait is the amount of time used between retransmitting a call if * no response has been heard; retransmition occurs until the actual * rpc call times out. * * sendsz and recvsz are the maximum allowable packet sizes that can be * sent and received. */ CLIENT * clntbtcp_create( struct sockaddr_in *raddr, rpcprog_t program, rpcvers_t version, struct timeval wait, int *sockp, uint_t sendsz, uint_t recvsz) { CLIENT *cl; struct ct_data *ct; struct rpc_msg call_msg; #if 0 /* XXX not yet */ int min_buf_sz; int pref_buf_sz = 64 * 1024; /* 64 KB */ socklen_t optlen; #endif /* not yet */ cl = (CLIENT *)bkmem_alloc(sizeof (CLIENT)); if (cl == NULL) { errno = ENOMEM; rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; return ((CLIENT *)NULL); } ct = (struct ct_data *)bkmem_alloc(sizeof (*ct)); if (ct == NULL) { errno = ENOMEM; rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto fooy; } if (raddr->sin_port == 0) { ushort_t port; if ((port = bpmap_getport(program, version, &(rpc_createerr.cf_stat), raddr, NULL)) == 0) { goto fooy; } raddr->sin_port = htons(port); } if (*sockp < 0) { struct sockaddr_in from; *sockp = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (*sockp < 0) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto fooy; } /* * Bootparams assumes a local net, so be sure to let lower * layer protocols know not to route. */ if (dontroute) { (void) setsockopt(*sockp, SOL_SOCKET, SO_DONTROUTE, (const void *)&dontroute, sizeof (dontroute)); } /* attempt to bind to priv port */ from.sin_family = AF_INET; ipv4_getipaddr(&from.sin_addr); from.sin_addr.s_addr = htonl(from.sin_addr.s_addr); from.sin_port = get_source_port(TRUE); if (bind(*sockp, (struct sockaddr *)&from, sizeof (from)) < 0) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; if (*sockp > 0) (void) close(*sockp); goto fooy; } if (connect(*sockp, (struct sockaddr *)raddr, sizeof (struct sockaddr_in)) < 0) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; if (*sockp > 0) (void) close(*sockp); goto fooy; } #if 0 /* XXX not yet */ /* * In the future we may want RPC to use larger transfer sizes * over TCP. In this case we will want to increase the * window size. */ /* * Resize the receive window if possible */ optlen = sizeof (int); if (getsockopt(*sockp, SOL_SOCKET, SO_RCVBUF, (void *)&min_buf_sz, &optlen) != 0) goto keep_going; if (min_buf_sz < pref_buf_sz) (void) setsockopt(*sockp, SOL_SOCKET, SO_RCVBUF, (const void *)&pref_buf_sz, sizeof (int)); keep_going: #endif /* not yet */ ct->ct_closeit = TRUE; } else ct->ct_closeit = FALSE; /* * Set up the private data */ ct->ct_sock = *sockp; ct->ct_wait_msec = 0; ct->ct_total.tv_sec = wait.tv_sec; ct->ct_total.tv_usec = -1; ct->ct_raddr = *raddr; /* * Initialize the call message */ /* * XXX - The xid might need to be randomized more. Imagine if there * are a rack of blade servers all booting at the same time. They * may cause havoc on the server with xid replays. */ call_msg.rm_xid = (uint_t)prom_gettime() + 1; call_msg.rm_direction = CALL; call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION; call_msg.rm_call.cb_prog = program; call_msg.rm_call.cb_vers = version; /* * pre-serialize the static part of the call msg and stash it away */ xdrmem_create(&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE, XDR_ENCODE); if (! xdr_callhdr(&(ct->ct_xdrs), &call_msg)) { if (ct->ct_closeit) (void) close(*sockp); goto fooy; } ct->ct_mpos = XDR_GETPOS(&(ct->ct_xdrs)); XDR_DESTROY(&(ct->ct_xdrs)); /* * XXX - Memory allocations can fail in xdrrec_create, so we need to * be able to catch those errors. */ xdrrec_create(&(ct->ct_xdrs), sendsz, recvsz, (caddr_t)ct, readtcp, writetcp); cl->cl_ops = clntbtcp_ops(); cl->cl_private = (caddr_t)ct; cl->cl_auth = authnone_create(); return (cl); fooy: if (ct) bkmem_free((caddr_t)ct, sizeof (*ct)); if (cl) bkmem_free((caddr_t)cl, sizeof (CLIENT)); return ((CLIENT *)NULL); } static enum clnt_stat clntbtcp_call( CLIENT *cl, rpcproc_t proc, xdrproc_t xargs, caddr_t argsp, xdrproc_t xdr_results, caddr_t resultsp, struct timeval utimeout) { struct ct_data *ct; XDR *xdrs; struct rpc_msg reply_msg; uint32_t x_id; uint32_t *msg_x_id; bool_t shipnow; int nrefreshes = 2; /* number of times to refresh cred */ struct timeval timeout; ct = (struct ct_data *)cl->cl_private; msg_x_id = (uint32_t *)ct->ct_mcall; xdrs = &(ct->ct_xdrs); ct->ct_total = utimeout; /* * We have to be able to wait for some non-zero period of time, so * use a default timeout. */ if (ct->ct_total.tv_sec == 0) ct->ct_total.tv_sec = RPC_RCVWAIT_MSEC / 1000; ct->ct_wait_msec = ct->ct_total.tv_sec * 1000 + ct->ct_total.tv_usec / 1000; timeout = ct->ct_total; shipnow = (xdr_results == (xdrproc_t)0 && timeout.tv_sec == 0 && timeout.tv_usec == 0) ? FALSE : TRUE; call_again: xdrs->x_op = XDR_ENCODE; ct->ct_error.re_status = RPC_SUCCESS; x_id = ntohl(++(*msg_x_id)); if ((! XDR_PUTBYTES(xdrs, ct->ct_mcall, ct->ct_mpos)) || (! XDR_PUTINT32(xdrs, (int32_t *)&proc)) || (! AUTH_MARSHALL(cl->cl_auth, xdrs, NULL)) || (! (*xargs)(xdrs, argsp))) { (void) xdrrec_endofrecord(xdrs, TRUE); ct->ct_error.re_status = RPC_CANTENCODEARGS; printf("clntbtcp_call: xdr encode args failed\n"); return (ct->ct_error.re_status); } if (!xdrrec_endofrecord(xdrs, shipnow)) { printf("clntbtcp_call: rpc cansend error\n"); ct->ct_error.re_status = RPC_CANTSEND; return (ct->ct_error.re_status); } if (!shipnow) return (RPC_SUCCESS); if (timeout.tv_sec == 0 && timeout.tv_usec == 0) { ct->ct_error.re_status = RPC_TIMEDOUT; return (ct->ct_error.re_status); } xdrs->x_op = XDR_DECODE; /* CONSTCOND */ while (TRUE) { reply_msg.acpted_rply.ar_verf = _null_auth; reply_msg.acpted_rply.ar_results.where = NULL; reply_msg.acpted_rply.ar_results.proc = xdr_void; if (!xdrrec_skiprecord(xdrs)) { return (ct->ct_error.re_status); } if (!xdr_replymsg(xdrs, &reply_msg)) { if (ct->ct_error.re_status == RPC_SUCCESS) continue; return (ct->ct_error.re_status); } if (reply_msg.rm_xid == x_id) { break; } } /* * process header */ _seterr_reply(&reply_msg, &(ct->ct_error)); if (ct->ct_error.re_status == RPC_SUCCESS) { if (!AUTH_VALIDATE(cl->cl_auth, &reply_msg.acpted_rply.ar_verf)) { ct->ct_error.re_status = RPC_AUTHERROR; ct->ct_error.re_why = AUTH_INVALIDRESP; } else if (!(*xdr_results)(xdrs, resultsp)) { if (ct->ct_error.re_status == RPC_SUCCESS) { ct->ct_error.re_status = RPC_CANTDECODERES; } } if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) { xdrs->x_op = XDR_FREE; (void) xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply.ar_verf)); } } else { if (nrefreshes-- && AUTH_REFRESH(cl->cl_auth, &reply_msg, NULL)) { goto call_again; } } return (ct->ct_error.re_status); } /* * Interface between xdr serializer and tcp connection. * Behaves like the system calls, read & write, but keeps some error state * around for the rpc level. */ static int readtcp(struct ct_data *ct, caddr_t buf, int len) { int inlen = 0; uint_t start, diff; struct sockaddr from; uint_t fromlen = sizeof (from); if (len <= 0) return (0); /* * Do non-blocking reads here until we get some data or timeout */ start = prom_gettime(); while ((inlen = recvfrom(ct->ct_sock, buf, len, 0, &from, &fromlen)) == 0) { diff = (uint_t)(prom_gettime() - start); if (diff > ct->ct_wait_msec) { errno = ETIMEDOUT; inlen = -1; break; } } #ifdef DEBUG printf("readtcp: inlen = %d\n", inlen); #endif switch (inlen) { case 0: /* premature eof */ ct->ct_error.re_errno = ECONNRESET; ct->ct_error.re_status = RPC_CANTRECV; inlen = -1; /* it's really an error */ break; case -1: ct->ct_error.re_errno = errno; ct->ct_error.re_status = RPC_CANTRECV; break; } return (inlen); } static int writetcp(ct, buf, len) struct ct_data *ct; caddr_t buf; int len; { register int i, cnt; for (cnt = len; cnt > 0; cnt -= i, buf += i) { if ((i = sendto(ct->ct_sock, (void *)buf, cnt, 0, (struct sockaddr *)&(ct->ct_raddr), sizeof (ct->ct_raddr))) == -1) { ct->ct_error.re_errno = errno; ct->ct_error.re_status = RPC_CANTSEND; return (-1); } } return (len); } static void clntbtcp_geterr( CLIENT *cl, struct rpc_err *errp) { struct ct_data *ct = (struct ct_data *)cl->cl_private; *errp = ct->ct_error; } static bool_t clntbtcp_freeres( CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr) { struct ct_data *ct = (struct ct_data *)cl->cl_private; XDR *xdrs = &(ct->ct_xdrs); xdrs->x_op = XDR_FREE; return ((*xdr_res)(xdrs, res_ptr)); } static void clntbtcp_abort() /* CLIENT *h; */ { } /* ARGSUSED */ static bool_t clntbtcp_control( CLIENT *cl, int request, char *info) { /* Not implemented in boot */ return (FALSE); } static void clntbtcp_destroy(CLIENT *cl) { struct ct_data *ct = (struct ct_data *)cl->cl_private; if (ct->ct_closeit) { (void) socket_close(ct->ct_sock); } XDR_DESTROY(&(ct->ct_xdrs)); bkmem_free((caddr_t)ct, (sizeof (struct ct_data))); bkmem_free((caddr_t)cl, sizeof (CLIENT)); } static struct clnt_ops * clntbtcp_ops() { static struct clnt_ops ops; if (ops.cl_call == NULL) { ops.cl_call = clntbtcp_call; ops.cl_abort = clntbtcp_abort; ops.cl_geterr = clntbtcp_geterr; ops.cl_freeres = clntbtcp_freeres; ops.cl_destroy = clntbtcp_destroy; ops.cl_control = clntbtcp_control; } return (&ops); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ /* * Boot subsystem client side rpc */ #include #include #include #include #include "socket_inet.h" #include "ipv4.h" #include "clnt.h" #include #include "brpc.h" #include "pmap.h" #include #include #include #include #include "auth_inet.h" #include #include #include #define dprintf if (boothowto & RB_DEBUG) printf /* retries to send RPC message when sendto fails */ #define RPC_UDP_SEND_RETRIES 3 extern int errno; /* * If we create another clnt type this should be * moved to a common file */ extern struct rpc_createerr rpc_createerr; static struct clnt_ops *clntbudp_ops(); /* * Private data kept per client handle */ struct cu_data { int cu_sock; bool_t cu_closeit; struct sockaddr_in cu_raddr; int cu_rlen; struct timeval cu_wait; struct timeval cu_total; struct rpc_err cu_error; XDR cu_outxdrs; uint_t cu_xdrpos; uint_t cu_sendsz; char *cu_outbuf; uint_t cu_recvsz; char cu_inbuf[1]; }; /* * Create a UDP based client handle. * If *sockp<0, *sockp is set to a newly created UPD socket. * If raddr->sin_port is 0 a binder on the remote machine * is consulted for the correct port number. * NB: It is the clients responsibility to close *sockp. * NB: The rpch->cl_auth is initialized to null authentication. * Caller may wish to set this something more useful. * * wait is the amount of time used between retransmitting a call if * no response has been heard; retransmition occurs until the actual * rpc call times out. * * sendsz and recvsz are the maximum allowable packet sizes that can be * sent and received. */ CLIENT * clntbudp_bufcreate(struct sockaddr_in *raddr, rpcprog_t program, rpcvers_t version, struct timeval wait, int *sockp, uint_t sendsz, uint_t recvsz) { CLIENT *cl; struct cu_data *cu; struct rpc_msg call_msg; cl = (CLIENT *)bkmem_alloc(sizeof (CLIENT)); if (cl == NULL) { errno = ENOMEM; rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; return ((CLIENT *)NULL); } sendsz = ((sendsz + 3) / 4) * 4; recvsz = ((recvsz + 3) / 4) * 4; cu = (struct cu_data *)bkmem_alloc(sizeof (*cu) + sendsz + recvsz); if (cu == NULL) { errno = ENOMEM; rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto fooy; } cu->cu_outbuf = &cu->cu_inbuf[recvsz]; if (raddr->sin_port == 0) { ushort_t port; if ((port = bpmap_getport(program, version, &(rpc_createerr.cf_stat), raddr, NULL)) == 0) { goto fooy; } raddr->sin_port = htons(port); } cl->cl_ops = clntbudp_ops(); cl->cl_private = (caddr_t)cu; cu->cu_raddr = *raddr; cu->cu_rlen = sizeof (cu->cu_raddr); cu->cu_wait = wait; cu->cu_total.tv_sec = -1; cu->cu_total.tv_usec = -1; cu->cu_sendsz = sendsz; cu->cu_recvsz = recvsz; call_msg.rm_xid = (uint_t)prom_gettime() + 1; call_msg.rm_direction = CALL; call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION; call_msg.rm_call.cb_prog = program; call_msg.rm_call.cb_vers = version; xdrmem_create(&(cu->cu_outxdrs), cu->cu_outbuf, sendsz, XDR_ENCODE); if (! xdr_callhdr(&(cu->cu_outxdrs), &call_msg)) { goto fooy; } cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs)); cu->cu_closeit = FALSE; if (*sockp < 0) { struct sockaddr_in from; *sockp = socket(PF_INET, SOCK_DGRAM, 0); if (*sockp < 0) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto fooy; } if (dontroute) { (void) setsockopt(*sockp, SOL_SOCKET, SO_DONTROUTE, (const void *)&dontroute, sizeof (dontroute)); } /* attempt to bind to priv port */ from.sin_family = AF_INET; ipv4_getipaddr(&from.sin_addr); from.sin_addr.s_addr = htonl(from.sin_addr.s_addr); from.sin_port = get_source_port(TRUE); if (bind(*sockp, (struct sockaddr *)&from, sizeof (from)) < 0) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto fooy; } cu->cu_closeit = TRUE; } cu->cu_sock = *sockp; cl->cl_auth = authnone_create(); return (cl); fooy: if (cu) bkmem_free((caddr_t)cu, sizeof (*cu) + sendsz + recvsz); if (cl) bkmem_free((caddr_t)cl, sizeof (CLIENT)); return ((CLIENT *)NULL); } CLIENT * clntbudp_create(struct sockaddr_in *raddr, rpcprog_t program, rpcvers_t version, struct timeval wait, int *sockp) { return (clntbudp_bufcreate(raddr, program, version, wait, sockp, UDPMSGSIZE, UDPMSGSIZE)); } static enum clnt_stat clntbudp_call(CLIENT *cl, rpcproc_t proc, xdrproc_t xargs, caddr_t argsp, xdrproc_t xresults, caddr_t resultsp, struct timeval utimeout) { struct cu_data *cu; XDR *xdrs; int outlen; int inlen; socklen_t fromlen; struct sockaddr_in from; struct rpc_msg reply_msg; XDR reply_xdrs; uint_t xdelay; int wait_time; bool_t ok; int nrefreshes = 2; /* number of times to refresh cred */ struct timeval timeout; int errors; short send_retries = RPC_UDP_SEND_RETRIES; cu = (struct cu_data *)cl->cl_private; if (cu->cu_total.tv_usec == -1) timeout = utimeout; /* use supplied timeout */ else timeout = cu->cu_total; /* use default timeout */ /* * set a media level timeout */ xdelay = cu->cu_wait.tv_sec + 1000 + cu->cu_wait.tv_usec / 1000; (void) setsockopt(cu->cu_sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&xdelay, sizeof (xdelay)); wait_time = (timeout.tv_sec * 1000) + (timeout.tv_usec / 1000); if (wait_time == 0) wait_time = RPC_RCVWAIT_MSEC; wait_time += prom_gettime(); errors = 0; call_again: xdrs = &(cu->cu_outxdrs); xdrs->x_op = XDR_ENCODE; (void) XDR_SETPOS(xdrs, cu->cu_xdrpos); /* * the transaction is the first thing in the out buffer */ (*(ushort_t *)(cu->cu_outbuf))++; if ((! XDR_PUTINT32(xdrs, (int32_t *)&proc)) || (! AUTH_MARSHALL(cl->cl_auth, xdrs, NULL)) || (! (*xargs)(xdrs, argsp))) return (cu->cu_error.re_status = RPC_CANTENCODEARGS); outlen = (int)XDR_GETPOS(xdrs); send_again: if (sendto(cu->cu_sock, cu->cu_outbuf, outlen, 0, (struct sockaddr *)&(cu->cu_raddr), cu->cu_rlen) != outlen) { if (errno == ETIMEDOUT) { /* * sendto() times out probably because * ARP times out while waiting for reply. * We retry sending RPC message again. */ if (send_retries-- > 0) { dprintf("clntbudp_call: timedout, try sending" "RPC again\n"); errno = 0; goto send_again; } cu->cu_error.re_status = RPC_TIMEDOUT; } else { cu->cu_error.re_status = RPC_CANTSEND; } cu->cu_error.re_errno = errno; return (cu->cu_error.re_status); } /* * sub-optimal code appears here because we have * some clock time to spare while the packets are in flight. * (We assume that this is actually only executed once.) */ recv_again: reply_msg.acpted_rply.ar_verf = _null_auth; reply_msg.acpted_rply.ar_results.where = resultsp; reply_msg.acpted_rply.ar_results.proc = xresults; for (;;) { if (errors >= RPC_ALLOWABLE_ERRORS) return (cu->cu_error.re_status); if (prom_gettime() >= wait_time) { cu->cu_error.re_errno = ETIMEDOUT; return (cu->cu_error.re_status = RPC_TIMEDOUT); } /* * Use MSG_DONTWAIT because we have set * a media level timeout above. */ fromlen = sizeof (struct sockaddr); inlen = recvfrom(cu->cu_sock, cu->cu_inbuf, (int)cu->cu_recvsz, MSG_DONTWAIT, (struct sockaddr *)&from, &fromlen); if (inlen < 0) { if (errno == EWOULDBLOCK) { /* * Media level has timedout * and no more data in buffers. */ goto send_again; } cu->cu_error.re_status = RPC_CANTRECV; if (errno == ETIMEDOUT) { errno = ETIMEDOUT; cu->cu_error.re_status = RPC_TIMEDOUT; } cu->cu_error.re_errno = errno; return (cu->cu_error.re_status); } if (inlen < sizeof (uint32_t)) continue; /* see if reply transaction id matches sent id */ if (*((uint32_t *)(cu->cu_inbuf)) != *((uint32_t *)(cu->cu_outbuf))) { dprintf("clntbudp_call: xid: 0x%x != 0x%x\n", *(uint32_t *)(cu->cu_inbuf), *(uint32_t *)(cu->cu_outbuf)); continue; } /* we now assume we have the proper reply */ break; } /* * now decode and validate the response */ xdrmem_create(&reply_xdrs, cu->cu_inbuf, (uint_t)inlen, XDR_DECODE); ok = xdr_replymsg(&reply_xdrs, &reply_msg); /* XDR_DESTROY(&reply_xdrs); save a few cycles on noop destroy */ if (!ok) { cu->cu_error.re_status = RPC_CANTDECODERES; return (cu->cu_error.re_status); } _seterr_reply(&reply_msg, &(cu->cu_error)); if (cu->cu_error.re_status == RPC_SUCCESS) { if (! AUTH_VALIDATE(cl->cl_auth, &reply_msg.acpted_rply.ar_verf)) { cu->cu_error.re_status = RPC_AUTHERROR; cu->cu_error.re_why = AUTH_INVALIDRESP; errors++; goto call_again; } if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) { xdrs->x_op = XDR_FREE; (void) xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply.ar_verf)); } return (cu->cu_error.re_status); } /* end successful completion */ if (cu->cu_error.re_status == RPC_AUTHERROR) { /* maybe our credentials need to be refreshed ... */ if (nrefreshes > 0 && AUTH_REFRESH(cl->cl_auth, NULL, NULL)) { nrefreshes--; } errors++; goto call_again; } /* Just keep trying till there's no data... */ errors++; dprintf("clntbudp_call: from: %s, error: ", inet_ntoa(from.sin_addr)); rpc_disperr(&cu->cu_error); goto recv_again; } static void clntbudp_geterr(CLIENT *cl, struct rpc_err *errp) { struct cu_data *cu = (struct cu_data *)cl->cl_private; *errp = cu->cu_error; } static bool_t clntbudp_freeres(CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr) { struct cu_data *cu = (struct cu_data *)cl->cl_private; XDR *xdrs = &(cu->cu_outxdrs); xdrs->x_op = XDR_FREE; return ((*xdr_res)(xdrs, res_ptr)); } static void clntbudp_abort(void) { } /* ARGSUSED */ static bool_t clntbudp_control(CLIENT *cl, int request, char *info) { /* CLNT_CONTROL is not used in boot */ return (FALSE); } static void clntbudp_destroy(CLIENT *cl) { struct cu_data *cu = (struct cu_data *)cl->cl_private; if (cu->cu_closeit) { (void) socket_close(cu->cu_sock); } XDR_DESTROY(&(cu->cu_outxdrs)); bkmem_free((caddr_t)cu, (sizeof (*cu) + cu->cu_sendsz + cu->cu_recvsz)); bkmem_free((caddr_t)cl, sizeof (CLIENT)); } static struct clnt_ops * clntbudp_ops(void) { static struct clnt_ops ops; if (ops.cl_call == NULL) { ops.cl_call = clntbudp_call; ops.cl_abort = clntbudp_abort; ops.cl_geterr = clntbudp_geterr; ops.cl_freeres = clntbudp_freeres; ops.cl_destroy = clntbudp_destroy; ops.cl_control = clntbudp_control; } return (&ops); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Stuff relating to directory reading ... */ #include #include #include #include "clnt.h" #include #include #include "nfs_inet.h" #include #include "brpc.h" #include #include #include #include #include #include "socket_inet.h" #include #include #define MAXDENTS 16 #define MINSIZ 20 /* * Boot needs to be cleaned up to use either dirent32 or dirent64, * in the meantime use dirent_t and always round to 8 bytes */ #define BDIRENT_RECLEN(namelen) \ ((offsetof(dirent_t, d_name[0]) + 1 + (namelen) + 7) & ~ 7) #define dprintf if (boothowto & RB_DEBUG) printf /* * Get directory entries: * * Uses the nfs "READDIR" operation to read directory entries * into a local buffer. These are then translated into file * system independent "dirent" structs and returned in the * caller's buffer. Returns the number of entries converted * (-1 if there's an error). * * Although the xdr functions can allocate memory, we have * a limited heap so we allocate our own space, * assuming the worst case of 256 byte names. * This is a space hog in our local buffer, so we want * the number of buffers to be small. To make sure we don't * get more names than we can handle, we tell the rpc * routine that we only have space for MAXDENT names if * they are all the minimum size. This keeps the return * packet unfragmented, but may result in lots of reads * to process a large directory. Since this is standalone * we don't worry about speed. With MAXDENTs at 16, the * local buffer is 4k. */ int nfsgetdents(struct nfs_file *nfp, struct dirent *dep, unsigned size) { entry *ep; readdirargs rda; readdirres res; enum clnt_stat status; struct { entry etlist[MAXDENTS]; char names[MAXDENTS][NFS_MAXNAMLEN+1]; } rdbuf; uint32_t offset; int j, cnt = 0; struct timeval zero_timeout = {0, 0}; /* default */ bzero((caddr_t)&res, sizeof (res)); bzero((caddr_t)&rda, sizeof (rda)); bzero((caddr_t)rdbuf.etlist, sizeof (rdbuf.etlist)); bcopy((caddr_t)&nfp->fh.fh2, (caddr_t)&rda.dir, NFS_FHSIZE); bcopy((caddr_t)nfp->cookie.cookie2, (caddr_t)rda.cookie, sizeof (nfscookie)); while (!res.readdirres_u.reply.eof) { /* * Keep issuing nfs calls until EOF is reached on * the directory or the user buffer is filled. */ for (j = 0; j < MAXDENTS; j++) { /* * Link our buffers together for the benefit of * XDR. We do this each time we issue the rpc call * JIC the xdr decode * routines screw up the linkage! */ rdbuf.etlist[j].name = rdbuf.names[(MAXDENTS-1) - j]; rdbuf.etlist[j].nextentry = (j < (MAXDENTS-1)) ? &rdbuf.etlist[j+1] : 0; } res.readdirres_u.reply.entries = rdbuf.etlist; /* * Cannot give the whole buffer unless every name is * 256 bytes! Assume the worst case of all 1 byte names. * This results in MINSIZ bytes/name in the xdr stream. */ rda.count = sizeof (res) + MAXDENTS*MINSIZ; bzero((caddr_t)rdbuf.names, sizeof (rdbuf.names)); status = CLNT_CALL(root_CLIENT, NFSPROC_READDIR, xdr_readdirargs, (caddr_t)&rda, xdr_readdirres, (caddr_t)&res, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs_getdents: RPC error\n"); return (-1); } if (res.status != NFS_OK) { /* * The most common failure here would be trying to * issue a getdents call on a non-directory! */ nfs_error(res.status); return (-1); } for (ep = rdbuf.etlist; ep; ep = ep->nextentry) { /* * Step thru all entries returned by NFS, converting * to the cannonical form and copying out to the * user's buffer. */ int n; /* * catch the case user called at EOF */ if ((n = strlen(ep->name)) == 0) return (cnt); n = BDIRENT_RECLEN(n); if (n > size) return (cnt); size -= n; (void) strlcpy(dep->d_name, ep->name, strlen(ep->name) + 1); dep->d_ino = ep->fileid; bcopy(ep->cookie, &offset, sizeof (nfscookie)); dep->d_off = offset; dep->d_reclen = (ushort_t)n; dep = (struct dirent *)((char *)dep + n); bcopy(ep->cookie, rda.cookie, sizeof (nfscookie)); bcopy(ep->cookie, nfp->cookie.cookie2, sizeof (nfscookie)); cnt++; } } return (cnt); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Stuff relating to NFSv3 directory reading ... */ #include #include #include #include "clnt.h" #include #include #include "nfs_inet.h" #include #include "brpc.h" #include #include #include #include #include #include "socket_inet.h" #include #include #define MAXDENTS 16 #define MINSIZ 20 /* * Boot needs to be cleaned up to use either dirent32 or dirent64, * in the meantime use dirent_t and always round to 8 bytes */ #define BDIRENT_RECLEN(namelen) \ ((offsetof(dirent_t, d_name[0]) + 1 + (namelen) + 7) & ~ 7) #define dprintf if (boothowto & RB_DEBUG) printf /* * Get directory entries: * * Uses the nfs "READDIR" operation to read directory entries * into a local buffer. These are then translated into file * system independent "dirent" structs and returned in the * caller's buffer. Returns the number of entries converted * (-1 if there's an error). * * Although the xdr functions can allocate memory, we have * a limited heap so we allocate our own space, * assuming the worst case of 256 byte names. * This is a space hog in our local buffer, so we want * the number of buffers to be small. To make sure we don't * get more names than we can handle, we tell the rpc * routine that we only have space for MAXDENT names if * they are all the minimum size. This keeps the return * packet unfragmented, but may result in lots of reads * to process a large directory. Since this is standalone * we don't worry about speed. With MAXDENTs at 16, the * local buffer is 4k. */ int nfs3getdents(struct nfs_file *nfp, struct dirent *dep, unsigned size) { int cnt = 0; entry3 *ep; READDIR3args rda; READDIR3res res; enum clnt_stat status; struct { entry3 etlist[MAXDENTS]; char names[MAXDENTS][NFS_MAXNAMLEN+1]; } rdbuf; int j; struct timeval zero_timeout = {0, 0}; /* default */ bzero((caddr_t)&res, sizeof (res)); bzero((caddr_t)&rda, sizeof (rda)); bzero((caddr_t)rdbuf.etlist, sizeof (rdbuf.etlist)); rda.dir.data.data_len = nfp->fh.fh3.len; rda.dir.data.data_val = nfp->fh.fh3.data; rda.cookie = nfp->cookie.cookie3; while (!res.READDIR3res_u.resok.reply.eof) { /* * Keep issuing nfs calls until EOF is reached on * the directory or the user buffer is filled. */ for (j = 0; j < MAXDENTS; j++) { /* * Link our buffers together for the benefit of * XDR. We do this each time we issue the rpc call * JIC the xdr decode * routines screw up the linkage! */ rdbuf.etlist[j].name = rdbuf.names[(MAXDENTS-1) - j]; rdbuf.etlist[j].nextentry = (j < (MAXDENTS-1)) ? &rdbuf.etlist[j+1] : 0; } res.READDIR3res_u.resok.reply.entries = rdbuf.etlist; /* * Cannot give the whole buffer unless every name is * 256 bytes! Assume the worst case of all 1 byte names. * This results in MINSIZ bytes/name in the xdr stream. */ rda.count = sizeof (res) + MAXDENTS*MINSIZ; bzero((caddr_t)rdbuf.names, sizeof (rdbuf.names)); status = CLNT_CALL(root_CLIENT, NFSPROC3_READDIR, xdr_READDIR3args, (caddr_t)&rda, xdr_READDIR3res, (caddr_t)&res, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs3_getdents: RPC error\n"); return (-1); } if (res.status != NFS3_OK) { /* * The most common failure here would be trying to * issue a getdents call on a non-directory! */ nfs3_error(res.status); return (-1); } for (ep = rdbuf.etlist; ep; ep = ep->nextentry) { /* * Step thru all entries returned by NFS, converting * to the cannonical form and copying out to the * user's buffer. */ int n; /* * catch the case user called at EOF */ if ((n = strlen(ep->name)) == 0) return (cnt); n = BDIRENT_RECLEN(n); if (n > size) return (cnt); size -= n; (void) strlcpy(dep->d_name, ep->name, strlen(ep->name) + 1); dep->d_ino = ep->fileid; dep->d_off = (off_t)ep->cookie; dep->d_reclen = (ushort_t)n; dep = (struct dirent *)((char *)dep + n); rda.cookie = ep->cookie; nfp->cookie.cookie3 = ep->cookie; cnt++; } } return (cnt); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Stuff relating to NFSv4 directory reading ... */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include "clnt.h" #include #include #include "nfs_inet.h" #include #include "brpc.h" #include #include #include #include #include #include "socket_inet.h" #include #include #define MAXDENTS 16 #define MINSIZ 20 /* * Boot needs to be cleaned up to use either dirent32 or dirent64, * in the meantime use dirent_t and always round to 8 bytes */ #define BDIRENT_RECLEN(namelen) \ ((offsetof(dirent_t, d_name[0]) + 1 + (namelen) + 7) & ~ 7) #define dprintf if (boothowto & RB_DEBUG) printf /* * Get directory entries: * * Uses the nfs "READDIR" operation to read directory entries * into a local buffer. These are then translated into file * system independent "dirent" structs and returned in the * caller's buffer. Returns the number of entries converted * (-1 if there's an error). * * Although the xdr functions can allocate memory, we have * a limited heap so we allocate our own space, * assuming the worst case of 256 byte names. * This is a space hog in our local buffer, so we want * the number of buffers to be small. To make sure we don't * get more names than we can handle, we tell the rpc * routine that we only have space for MAXDENT names if * they are all the minimum size. This keeps the return * packet unfragmented, but may result in lots of reads * to process a large directory. Since this is standalone * we don't worry about speed. With MAXDENTs at 16, the * local buffer is 4k. */ int nfs4getdents(struct nfs_file *nfp, struct dirent *dep, unsigned size) { int cnt = 0; b_entry4_t *ep; readdir4arg_t readdir_args; readdir4res_t readdir_res; attr4_bitmap1_t bitmap1; enum clnt_stat status; struct { b_entry4_t etlist[MAXDENTS]; char names[MAXDENTS][NFS_MAXNAMLEN+1]; } rdbuf; int j; struct timeval zero_timeout = {0, 0}; /* default */ utf8string str; char tagname[] = "inetboot readdir"; bzero((caddr_t)&readdir_res, sizeof (readdir4res_t)); bzero((caddr_t)&readdir_args, sizeof (readdir4arg_t)); bzero((caddr_t)rdbuf.etlist, sizeof (rdbuf.etlist)); str.utf8string_len = sizeof (tagname) - 1; str.utf8string_val = tagname; if (nfp->fh.fh4.len > 0) compound_init(&readdir_args.rd_arg, &str, 0, 2, &nfp->fh.fh4); else compound_init(&readdir_args.rd_arg, &str, 0, 2, NULL); readdir_args.rd_opreaddir = OP_READDIR; readdir_args.rd_cookie = nfp->cookie.cookie4; while (!readdir_res.rd_eof) { /* * Keep issuing nfs calls until EOF is reached on * the directory or the user buffer is filled. */ for (j = 0; j < MAXDENTS; j++) { /* * Link our buffers together for the benefit of * XDR. We do this each time we issue the rpc call * JIC the xdr decode * routines screw up the linkage! */ rdbuf.etlist[j].b_name.utf8string_len = NFS_MAXNAMLEN; rdbuf.etlist[j].b_name.utf8string_val = rdbuf.names[(MAXDENTS-1) - j]; rdbuf.etlist[j].b_nextentry = (j < (MAXDENTS-1)) ? &rdbuf.etlist[j+1] : 0; } readdir_res.rd_entries = rdbuf.etlist; /* * Cannot give the whole buffer unless every name is * 256 bytes! Assume the worst case of all 1 byte names. * This results in MINSIZ bytes/name in the xdr stream. */ readdir_args.rd_dircount = MAXDENTS * MINSIZ; readdir_args.rd_maxcount = sizeof (readdir4res_t) + (MAXDENTS * MINSIZ); bzero((caddr_t)rdbuf.names, sizeof (rdbuf.names)); /* * Set the attr bitmap, so we get the fileid back. */ bitmap1.word = 0; bitmap1.bm_fattr4_fileid = 1; readdir_args.rd_attr_req.b_bitmap_len = 1; readdir_args.rd_attr_req.b_bitmap_val[0] = bitmap1.word; status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_readdir4_args, (caddr_t)&readdir_args, xdr_readdir4_res, (caddr_t)&readdir_res, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs4_getdents: RPC error\n"); return (-1); } if (readdir_res.rd_status != NFS4_OK) { /* * The most common failure here would be trying to * issue a getdents call on a non-directory! */ nfs4_error(readdir_res.rd_status); return (-1); } /* * If we are reading from the beginning of the * directory we will need to create the "." and ".." * since we won't be getting them from the server. To obtain * the fileid's just issue a couple otw lookups to get the * info we need. */ if (readdir_args.rd_cookie == 0 && rdbuf.etlist[0].b_cookie > 2) { int n; int error; uint64_t fileid; struct vattr va; /* * Do a getattr for the '.' */ error = nfs4getattr(nfp, &va); if (error) return (-1); dep->d_name[0] = '.'; dep->d_name[1] = '\0'; dep->d_ino = va.va_nodeid; dep->d_off = 1; n = BDIRENT_RECLEN(1); dep->d_reclen = n; dep = (struct dirent *)((char *)dep + n); /* * Do a lookupp for the '..' */ (void) nfs4lookupp(nfp, &error, &fileid); if (error) return (-1); dep->d_name[0] = '.'; dep->d_name[1] = '.'; dep->d_name[2] = '\0'; dep->d_ino = fileid; dep->d_off = 2; n = BDIRENT_RECLEN(2); dep->d_reclen = n; dep = (struct dirent *)((char *)dep + n); } for (ep = rdbuf.etlist; ep; ep = ep->b_nextentry) { /* * Step thru all entries returned by NFS, converting * to the cannonical form and copying out to the * user's buffer. */ int n; int namlen; /* * catch the case user called at EOF */ if ((namlen = ep->b_name.utf8string_len) == 0) return (cnt); n = BDIRENT_RECLEN(namlen); if (n > size) return (cnt); size -= n; bcopy(ep->b_name.utf8string_val, dep->d_name, namlen); dep->d_name[namlen] = '\0'; dep->d_ino = ep->b_fileid; dep->d_off = (off_t)ep->b_cookie; dep->d_reclen = (ushort_t)n; dep = (struct dirent *)((char *)dep + n); readdir_args.rd_cookie = ep->b_cookie; nfp->cookie.cookie4 = ep->b_cookie; cnt++; } } return (cnt); } #!/bin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # ident "%Z%%M% %I% %E% SMI" # find_files "s.*" usr/src/common/net/dhcp /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ /* * This file contains the file lookup code for NFS. */ #include #include "brpc.h" #include #include #include #include #include #include "clnt.h" #include #include #include #include #include "nfs_inet.h" #include "socket_inet.h" #include #include #include #include #include #include #include #include #include "mac.h" static int root_inum = 1; /* Dummy i-node number for root */ static int next_inum = 1; /* Next dummy i-node number */ #define dprintf if (boothowto & RB_DEBUG) printf /* * starting at current directory (root for us), lookup the pathname. * return the file handle of said file. */ static int stlookuppn(struct st_pathname *pnp, struct nfs_file *cfile, bool_t needroothandle); /* * For NFSv4 we may be calling lookup in the context of evaluating the * root path. In this case we set needroothandle to TRUE. */ int lookup(char *pathname, struct nfs_file *cur_file, bool_t needroothandle) { struct st_pathname pnp; int error; static char lkup_path[NFS_MAXPATHLEN]; /* pn_alloc doesn't */ pnp.pn_buf = &lkup_path[0]; bzero(pnp.pn_buf, NFS_MAXPATHLEN); error = stpn_get(pathname, &pnp); if (error) return (error); error = stlookuppn(&pnp, cur_file, needroothandle); return (error); } static int stlookuppn(struct st_pathname *pnp, struct nfs_file *cfile, bool_t needroothandle) { char component[NFS_MAXNAMLEN+1]; /* buffer for component */ int nlink = 0; int error = 0; int dino, cino; struct nfs_file *cdp = NULL; *cfile = roothandle; /* structure copy - start at the root. */ dino = root_inum; begin: /* * Each time we begin a new name interpretation (e.g. * when first called and after each symbolic link is * substituted), we allow the search to start at the * root directory if the name starts with a '/', otherwise * continuing from the current directory. */ component[0] = '\0'; if (stpn_peekchar(pnp) == '/') { if (!needroothandle) *cfile = roothandle; dino = root_inum; stpn_skipslash(pnp); } next: /* * Make sure we have a directory. */ if (!cfile_is_dir(cfile)) { error = ENOTDIR; goto bad; } /* * Process the next component of the pathname. */ error = stpn_stripcomponent(pnp, component); if (error) goto bad; /* * Check for degenerate name (e.g. / or "") * which is a way of talking about a directory, * e.g. "/." or ".". */ if (component[0] == '\0') return (0); /* * Handle "..": two special cases. * 1. If at root directory (e.g. after chroot) * then ignore it so can't get out. * 2. If this vnode is the root of a mounted * file system, then replace it with the * vnode which was mounted on so we take the * .. in the other file system. */ if (strcmp(component, "..") == 0) { if (cfile == &roothandle) goto skip; } /* * Perform a lookup in the current directory. * We create a simple negative lookup cache by storing * inode -1 to indicate file not found. */ cino = get_dcache(mac_get_dev(), component, dino); if (cino == -1) return (ENOENT); #ifdef DEBUG dprintf("lookup: component %s pathleft %s\n", component, pnp->pn_path); #endif if ((cino == 0) || ((cdp = (struct nfs_file *)get_icache(mac_get_dev(), cino)) == 0)) { struct nfs_file *lkp; /* * If an RPC error occurs, error is not changed, * else it is the NFS error if NULL is returned. */ error = -1; switch (cfile->version) { case NFS_VERSION: lkp = nfslookup(cfile, component, &error); break; case NFS_V3: lkp = nfs3lookup(cfile, component, &error); break; case NFS_V4: lkp = nfs4lookup(cfile, component, &error); break; default: printf("lookup: NFS Version %d not supported\n", cfile->version); lkp = NULL; break; } /* * Check for RPC error */ if (error == -1) { printf("lookup: lookup RPC error\n"); return (error); } /* * Check for NFS error */ if (lkp == NULL) { if ((error != NFSERR_NOENT) && (error != NFS3ERR_NOENT) && (error != NFS4ERR_NOENT)) { #ifdef DEBUG dprintf("lookup: lkp is NULL with error %d\n", error); #endif return (error); } #ifdef DEBUG dprintf("lookup: lkp is NULL with error %d\n", error); #endif /* * File not found so set cached inode to -1 */ set_dcache(mac_get_dev(), component, dino, -1); return (error); } if (cdp = (struct nfs_file *) bkmem_alloc(sizeof (struct nfs_file))) { /* * Save this entry in cache for next time ... */ if (!cino) cino = ++next_inum; *cdp = *lkp; set_dcache(mac_get_dev(), component, dino, cino); set_icache(mac_get_dev(), cino, cdp, sizeof (struct nfs_file)); } else { /* * Out of memory, clear cache keys so we don't get * confused later. */ cino = 0; cdp = lkp; } } dino = cino; /* * If we hit a symbolic link and there is more path to be * translated or this operation does not wish to apply * to a link, then place the contents of the link at the * front of the remaining pathname. */ if (cfile_is_lnk(cdp)) { struct st_pathname linkpath; static char path_tmp[NFS_MAXPATHLEN]; /* used for symlinks */ char *pathp; linkpath.pn_buf = &path_tmp[0]; nlink++; if (nlink > MAXSYMLINKS) { error = ELOOP; goto bad; } switch (cdp->version) { case NFS_VERSION: error = nfsgetsymlink(cdp, &pathp); break; case NFS_V3: error = nfs3getsymlink(cdp, &pathp); break; case NFS_V4: error = nfs4getsymlink(cdp, &pathp); break; default: printf("getsymlink: NFS Version %d not supported\n", cdp->version); error = ENOTSUP; break; } if (error) goto bad; (void) stpn_get(pathp, &linkpath); if (stpn_pathleft(&linkpath) == 0) (void) stpn_set(&linkpath, "."); error = stpn_combine(pnp, &linkpath); /* linkpath before pn */ if (error) goto bad; goto begin; } if (needroothandle) { roothandle = *cdp; needroothandle = FALSE; } *cfile = *cdp; skip: /* * Skip to next component of the pathname. * If no more components, return last directory (if wanted) and * last component (if wanted). */ if (stpn_pathleft(pnp) == 0) { (void) stpn_set(pnp, component); return (0); } /* * skip over slashes from end of last component */ stpn_skipslash(pnp); goto next; bad: /* * Error. */ return (error); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1988 AT&T */ /* All Rights Reserved */ #include #include #include #include #include #include #include #include #include "clnt.h" #include #include #include #include "brpc.h" #include "auth_inet.h" #include "pmap.h" #include #include #include "nfs_inet.h" #include #include #include #include #include #include "socket_inet.h" #include "ipv4.h" #include "mac.h" #include #include #include "dhcpv4.h" #include /* ARP timeout in milliseconds for BOOTP/RARP */ #define ARP_INETBOOT_TIMEOUT 1000 struct nfs_file roothandle; /* root file handle */ static char root_hostname[SYS_NMLN]; /* server hostname */ static char my_hostname[MAXHOSTNAMELEN]; static char root_pathbuf[NFS_MAXPATHLEN]; /* the root's path */ static char root_boot_file[NFS_MAXPATHLEN]; /* optional boot file */ static struct sockaddr_in root_to; /* server sock ip */ /* in network order */ CLIENT *root_CLIENT = NULL; /* CLIENT handle */ int dontroute = FALSE; /* In case rarp/bootparams was selected */ char rootopts[MAX_PATH_LEN]; static gid_t fake_gids = 1; /* fake gids list for auth_unix */ extern void set_default_filename(char *); /* boot.c */ /* * xdr routines used by mount. */ bool_t xdr_fhstatus(XDR *xdrs, struct fhstatus *fhsp) { if (!xdr_int(xdrs, (int *)&fhsp->fhs_status)) return (FALSE); if (fhsp->fhs_status == 0) { return (xdr_fhandle(xdrs, fhsp->fhstatus_u.fhs_fhandle)); } return (TRUE); } bool_t xdr_fhandle(XDR *xdrs, fhandle fhp) { return (xdr_opaque(xdrs, (char *)fhp, NFS_FHSIZE)); } bool_t xdr_path(XDR *xdrs, char **pathp) { return (xdr_string(xdrs, pathp, MNTPATHLEN)); } bool_t xdr_fhandle3(XDR *xdrs, fhandle3 *objp) { return (xdr_bytes(xdrs, (char **)&objp->fhandle3_val, (uint_t *)&objp->fhandle3_len, FHSIZE3)); } bool_t xdr_mountstat3(XDR *xdrs, mountstat3 *objp) { return (xdr_enum(xdrs, (enum_t *)objp)); } bool_t xdr_mountres3_ok(XDR *xdrs, mountres3_ok *objp) { if (!xdr_fhandle3(xdrs, &objp->fhandle)) return (FALSE); return (xdr_array(xdrs, (char **)&objp->auth_flavors.auth_flavors_val, (uint_t *)&objp->auth_flavors.auth_flavors_len, ~0, sizeof (int), (xdrproc_t)xdr_int)); } bool_t xdr_mountres3(XDR *xdrs, mountres3 *objp) { if (!xdr_mountstat3(xdrs, &objp->fhs_status)) return (FALSE); if (objp->fhs_status == MNT_OK) return (xdr_mountres3_ok(xdrs, &objp->mountres3_u.mountinfo)); return (TRUE); } static int nfsmountroot(char *path, struct nfs_file *filep) { int rexmit; int resp_wait; enum clnt_stat status; struct fhstatus root_tmp; /* to pass to rpc/xdr */ /* * Wait up to 16 secs for first response, retransmitting expon. */ rexmit = 0; /* default retransmission interval */ resp_wait = 16; do { status = brpc_call((rpcprog_t)MOUNTPROG, (rpcvers_t)MOUNTVERS, (rpcproc_t)MOUNTPROC_MNT, xdr_path, (caddr_t)&path, xdr_fhstatus, (caddr_t)&(root_tmp), rexmit, resp_wait, &root_to, NULL, AUTH_UNIX); if (status == RPC_TIMEDOUT) { dprintf("boot: %s:%s mount server not responding.\n", root_hostname, path); } rexmit = resp_wait; resp_wait = 0; /* use default wait time. */ } while (status == RPC_TIMEDOUT); if ((status != RPC_SUCCESS) || (root_tmp.fhs_status != 0)) { nfs_error(root_tmp.fhs_status); root_to.sin_port = 0; return (-1); } /* * Since the mount succeeded, we'll mark the filep's * status as NFS_OK, and its type as NFDIR. If these * points aren't the case, then we wouldn't be here. */ bcopy(&root_tmp.fhstatus_u.fhs_fhandle, &filep->fh.fh2, FHSIZE); filep->ftype.type2 = NFDIR; filep->version = NFS_VERSION; nfs_readsize = nfs_readsize < NFS_MAXDATA ? nfs_readsize : NFS_MAXDATA; /* * Set a reasonable lower limit on readsize */ nfs_readsize = (nfs_readsize != 0 && nfs_readsize < 512) ? 512 : nfs_readsize; return (0); } int setup_root_vars(void) { size_t buflen; uint16_t readsize; /* * Root server name. Required. */ buflen = sizeof (root_hostname); if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTSRVR_NAME, 0, root_hostname, &buflen)) { root_hostname[buflen] = '\0'; } else { dprintf("BOUND: Missing Root Server Name Option\n"); errno = EINVAL; return (-1); } /* * Root server IP. Required. */ buflen = sizeof (root_to.sin_addr); if (!dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTSRVR_IP, 0, &root_to.sin_addr, &buflen)) { dprintf("BOUND: Missing Root Server IP Option\n"); errno = EINVAL; return (-1); } /* * Root path Required. */ buflen = sizeof (root_pathbuf); if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTPATH, 0, root_pathbuf, &buflen)) { root_pathbuf[buflen] = '\0'; } else { dprintf("BOUND: Missing Root Path Option\n"); errno = EINVAL; return (-1); } /* * Optional Bootfile path. */ buflen = sizeof (root_boot_file); if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_BOOTFILE, 0, root_boot_file, &buflen)) { root_boot_file[buflen] = '\0'; dprintf("BOUND: Optional Boot File is: %s\n", root_boot_file); } /* if we got a boot file name, use it as the default */ if (root_boot_file[0] != '\0') set_default_filename(root_boot_file); /* * Set the NFS read size. The mount code will adjust it to * the maximum size. */ buflen = sizeof (readsize); if (dhcp_getinfo(DSYM_VENDOR, VS_BOOT_NFS_READSIZE, 0, &readsize, &buflen)) { nfs_readsize = ntohs(readsize); if (boothowto & RB_VERBOSE) { printf("Boot NFS read size: %d\n", nfs_readsize); } } /* * Optional rootopts. */ buflen = sizeof (rootopts); if (dhcp_getinfo(DSYM_VENDOR, VS_NFSMNT_ROOTOPTS, 0, rootopts, &buflen)) { rootopts[buflen] = '\0'; dprintf("BOUND: Optional Rootopts is: %s\n", rootopts); } return (0); } static void mnt3_error(enum mountstat3 status) { if (!(boothowto & RB_DEBUG)) return; switch (status) { case MNT_OK: printf("Mount: No error.\n"); break; case MNT3ERR_PERM: printf("Mount: Not owner.\n"); break; case MNT3ERR_NOENT: printf("Mount: No such file or directory.\n"); break; case MNT3ERR_IO: printf("Mount: I/O error.\n"); break; case MNT3ERR_ACCES: printf("Mount: Permission denied.\n"); break; case MNT3ERR_NOTDIR: printf("Mount: Not a directory.\n"); break; case MNT3ERR_INVAL: printf("Mount: Invalid argument.\n"); break; case MNT3ERR_NAMETOOLONG: printf("Mount: File name too long.\n"); break; case MNT3ERR_NOTSUPP: printf("Mount: Operation not supported.\n"); break; case MNT3ERR_SERVERFAULT: printf("Mount: Server fault.\n"); break; default: printf("Mount: unknown error.\n"); break; } } static int nfs3mountroot(char *path, struct nfs_file *filep) { int rexmit; int resp_wait; struct mountres3 res3; enum clnt_stat status; /* * Wait up to 16 secs for first response, retransmitting expon. */ rexmit = 0; /* default retransmission interval */ resp_wait = 16; /* * Try to mount using V3 */ do { bzero(&res3, sizeof (struct mountres3)); status = brpc_call((rpcprog_t)MOUNTPROG, (rpcvers_t)MOUNTVERS3, (rpcproc_t)MOUNTPROC_MNT, xdr_path, (caddr_t)&path, xdr_mountres3, (caddr_t)&res3, rexmit, resp_wait, &root_to, NULL, AUTH_UNIX); if (status != RPC_TIMEDOUT) break; dprintf("boot: %s:%s mount server not responding.\n", root_hostname, path); rexmit = resp_wait; resp_wait = 0; /* use default wait time. */ xdr_free(xdr_mountres3, (caddr_t)&res3); } while (status == RPC_TIMEDOUT); if ((status != RPC_SUCCESS) || (res3.fhs_status != MNT_OK)) { mnt3_error(res3.fhs_status); root_to.sin_port = 0; return (-1); } /* * Since the mount succeeded, we'll mark the filep's * status as NFS_OK, and its type as NF3DIR. If these * points aren't the case, then we wouldn't be here. */ filep->fh.fh3.len = res3.mountres3_u.mountinfo.fhandle.fhandle3_len; bcopy(res3.mountres3_u.mountinfo.fhandle.fhandle3_val, filep->fh.fh3.data, filep->fh.fh3.len); filep->ftype.type3 = NF3DIR; filep->version = NFS_V3; /* * Hardwire in a known reasonable upper limit of 32K */ nfs_readsize = nfs_readsize < 32 * 1024 ? nfs_readsize : 32 * 1024; /* * Set a reasonable lower limit on readsize */ nfs_readsize = (nfs_readsize != 0 && nfs_readsize < 512) ? 512 : nfs_readsize; xdr_free(xdr_mountres3, (caddr_t)&res3); return (0); } /* * Setup v4 client for inetboot */ static int nfs4init(char *path, uint16_t nfs_port) { struct timeval wait; int fd = -1; int error = 0; enum clnt_stat rpc_stat; struct nfs_file rootpath; wait.tv_sec = RPC_RCVWAIT_MSEC / 1000; wait.tv_usec = 0; /* * If we haven't explicitly set the port number, set to the standard * 2049 and don't cause a rpcbind request. */ if (nfs_port == 0) nfs_port = 2049; root_to.sin_port = htons(nfs_port); /* * Support TCP only */ root_CLIENT = clntbtcp_create(&root_to, NFS_PROGRAM, NFS_V4, wait, &fd, NFS4BUF_SIZE, NFS4BUF_SIZE); if (root_CLIENT == NULL) { root_to.sin_port = 0; return (-1); } root_CLIENT->cl_auth = authunix_create(my_hostname, 0, 1, 1, &fake_gids); /* * Send NULL proc the server first to see if V4 exists */ rpc_stat = CLNT_CALL(root_CLIENT, NFSPROC4_NULL, xdr_void, NULL, xdr_void, NULL, wait); if (rpc_stat != RPC_SUCCESS) { dprintf("boot: NULL proc failed NFSv4 service not available\n"); AUTH_DESTROY(root_CLIENT->cl_auth); CLNT_DESTROY(root_CLIENT); root_to.sin_port = 0; return (-1); } /* * Do a lookup to get to the root_path. This is nice since it can * handle multicomponent lookups. */ roothandle.version = NFS_V4; roothandle.ftype.type4 = NF4DIR; roothandle.fh.fh4.len = 0; /* Force a PUTROOTFH */ roothandle.offset = (uint_t)0; /* it's a directory! */ error = lookup(path, &rootpath, TRUE); if (error) { printf("boot: lookup %s failed\n", path); return (-1); } roothandle = rootpath; /* structure copy */ /* * Hardwire in a known reasonable upper limit of 32K */ nfs_readsize = nfs_readsize < 32 * 1024 ? nfs_readsize : 32 * 1024; /* * Set a reasonable lower limit on readsize */ nfs_readsize = (nfs_readsize != 0 && nfs_readsize < 512) ? 512 : nfs_readsize; return (0); } static int atoi(const char *p) { int n; int c, neg = 0; if (!isdigit(c = *p)) { while (c == ' ' || c == '\t' || c == '\n') c = *++p; switch (c) { case '-': neg++; /* FALLTHROUGH */ case '+': c = *++p; } if (!isdigit(c)) return (0); } for (n = '0' - c; isdigit(c = *++p); ) { n *= 10; /* two steps to avoid unnecessary overflow */ n += '0' - c; /* accum neg to avoid surprises at MAX */ } return (neg ? n : -n); } /* * Parse suboptions from a string. * Same as getsubopt(3C). */ static int getsubopt(char **optionsp, char * const *tokens, char **valuep) { char *s = *optionsp, *p; int i; size_t optlen; *valuep = NULL; if (*s == '\0') return (-1); p = strchr(s, ','); /* find next option */ if (p == NULL) { p = s + strlen(s); } else { *p++ = '\0'; /* mark end and point to next */ } *optionsp = p; /* point to next option */ p = strchr(s, '='); /* find value */ if (p == NULL) { optlen = strlen(s); *valuep = NULL; } else { optlen = p - s; *valuep = ++p; } for (i = 0; tokens[i] != NULL; i++) { if ((optlen == strlen(tokens[i])) && (strncmp(s, tokens[i], optlen) == 0)) return (i); } /* no match, point value at option and return error */ *valuep = s; return (-1); } /* * The only interesting NFS mount options for initiating the kernel * all others are ignored. */ static char *optlist[] = { #define OPT_RSIZE 0 MNTOPT_RSIZE, #define OPT_TIMEO 1 MNTOPT_TIMEO, #define OPT_VERS 2 MNTOPT_VERS, #define OPT_PROTO 3 MNTOPT_PROTO, #define OPT_PORT 4 MNTOPT_PORT, NULL }; /* * This routine will open a device as it is known by the V2 OBP. It * then goes thru the stuff necessary to initialize the network device, * get our network parameters, (using DHCP or rarp/bootparams), and * finally actually go and get the root filehandle. Sound like fun? * Suuurrrree. Take a look. * * Returns 0 if things worked. -1 if we crashed and burned. */ int boot_nfs_mountroot(char *str) { int status; enum clnt_stat rpc_stat; char *root_path = &root_pathbuf[0]; /* to make XDR happy */ struct timeval wait; int fd; int bufsize; char *opts, *val; int nfs_version = 0; int istcp = 1; int nfs_port = 0; /* Cause pmap to get port */ struct sockaddr_in tmp_addr; /* throw away */ if (root_CLIENT != NULL) { AUTH_DESTROY(root_CLIENT->cl_auth); CLNT_DESTROY(root_CLIENT); root_CLIENT = NULL; } root_to.sin_family = AF_INET; root_to.sin_addr.s_addr = htonl(INADDR_ANY); root_to.sin_port = htons(0); mac_init(str); (void) ipv4_setpromiscuous(TRUE); if (get_netconfig_strategy() == NCT_BOOTP_DHCP) { if (boothowto & RB_VERBOSE) printf("Using BOOTP/DHCP...\n"); if (dhcp() != 0 || setup_root_vars() != 0) { (void) ipv4_setpromiscuous(FALSE); if (boothowto & RB_VERBOSE) printf("BOOTP/DHCP configuration failed!\n"); return (-1); } /* now that we have an IP address, turn off promiscuous mode */ (void) ipv4_setpromiscuous(FALSE); } else { /* Use RARP/BOOTPARAMS. RARP will try forever... */ if (boothowto & RB_VERBOSE) printf("Using RARP/BOOTPARAMS...\n"); mac_call_rarp(); /* * Since there is no way to determine our netmask, and therefore * figure out if the router we got is useful, we assume all * services are local. Use DHCP if this bothers you. */ dontroute = TRUE; /* * We are trying to keep the ARP response * timeout on the lower side with BOOTP/RARP. * We are doing this for BOOTP/RARP where policy * doesn't allow to route the packets outside * the subnet as it has no idea about the * netmask. By doing so, we are reducing * ARP response timeout for any packet destined * for outside booting clients subnet. Client can * not expect such ARP replies and will finally * timeout after a long delay. This would cause * booting client to get stalled for a longer * time. We can not avoid accepting any outside * subnet packets accidentally destined for the * booting client. */ mac_set_arp_timeout(ARP_INETBOOT_TIMEOUT); /* now that we have an IP address, turn off promiscuous mode */ (void) ipv4_setpromiscuous(FALSE); /* get our hostname */ if (whoami() == FALSE) return (-1); /* get our bootparams. */ if (getfile("root", root_hostname, &root_to.sin_addr, root_pathbuf) == FALSE) return (-1); /* get our rootopts. */ (void) getfile("rootopts", root_hostname, &tmp_addr.sin_addr, rootopts); } /* mount root */ if (boothowto & RB_VERBOSE) { printf("root server: %s (%s)\n", root_hostname, inet_ntoa(root_to.sin_addr)); printf("root directory: %s\n", root_pathbuf); } /* * Assumes we've configured the stack and thus know our * IP address/hostname, either by using DHCP or rarp/bootparams. */ (void) gethostname(my_hostname, sizeof (my_hostname)); wait.tv_sec = RPC_RCVWAIT_MSEC / 1000; wait.tv_usec = 0; /* * Parse out the interesting root options, if an invalid * or unknown option is provided, silently ignore it and * use the defaults. */ opts = rootopts; while (*opts) { int ival; switch (getsubopt(&opts, optlist, &val)) { case OPT_RSIZE: if (val == NULL || !isdigit(*val)) break; nfs_readsize = atoi(val); break; case OPT_TIMEO: if (val == NULL || !isdigit(*val)) break; ival = atoi(val); wait.tv_sec = ival / 10; wait.tv_usec = (ival % 10) * 100000; break; case OPT_VERS: if (val == NULL || !isdigit(*val)) break; nfs_version = atoi(val); break; case OPT_PROTO: if (val == NULL || isdigit(*val)) break; if ((strncmp(val, "udp", 3) == 0)) istcp = 0; else istcp = 1; /* must be tcp */ break; case OPT_PORT: if (val == NULL || !isdigit(*val)) break; nfs_port = atoi(val); /* * Currently nfs_dlinet.c doesn't support setting * the root NFS port. Delete this when it does. */ nfs_port = 0; break; default: /* * Unknown options are silently ignored */ break; } } /* * If version is set, then try that version first. */ switch (nfs_version) { case NFS_VERSION: if (nfsmountroot(root_path, &roothandle) == 0) goto domount; break; case NFS_V3: if (nfs3mountroot(root_path, &roothandle) == 0) goto domount; break; case NFS_V4: /* * With v4 we skip the mount and go straight to * setting the root filehandle. Because of this we * do things slightly differently and obtain our * client handle first. */ if (istcp && nfs4init(root_path, nfs_port) == 0) { /* * If v4 init succeeded then we are done. Just return. */ return (0); } } /* * If there was no chosen version or the chosen version failed * try all versions in order, this may still fail to boot * at the kernel level if the options are not right, but be * generous at this early stage. */ if (istcp && nfs4init(root_path, nfs_port) == 0) { /* * If v4 init succeeded then we are done. Just return. */ return (0); } if (nfs3mountroot(root_path, &roothandle) == 0) goto domount; if ((status = nfsmountroot(root_path, &roothandle)) != 0) return (status); domount: /* * Only v2 and v3 go on from here. */ roothandle.offset = (uint_t)0; /* it's a directory! */ root_to.sin_port = htons(nfs_port); /* NFS is next after mount */ /* * Create the CLIENT handle for NFS operations */ if (roothandle.version == NFS_VERSION) bufsize = NFSBUF_SIZE; else bufsize = NFS3BUF_SIZE; /* * First try TCP then UDP (unless UDP asked for explicitly), if mountd * alows this version but neither transport is available we are stuck. */ if (istcp) { fd = -1; root_CLIENT = clntbtcp_create(&root_to, NFS_PROGRAM, roothandle.version, wait, &fd, bufsize, bufsize); if (root_CLIENT != NULL) { root_CLIENT->cl_auth = authunix_create(my_hostname, 0, 1, 1, &fake_gids); /* * Send NULL proc, check if the server really exists */ rpc_stat = CLNT_CALL(root_CLIENT, 0, xdr_void, NULL, xdr_void, NULL, wait); if (rpc_stat == RPC_SUCCESS) return (0); AUTH_DESTROY(root_CLIENT->cl_auth); CLNT_DESTROY(root_CLIENT); root_CLIENT = NULL; } /* Fall through to UDP case */ } fd = -1; root_CLIENT = clntbudp_bufcreate(&root_to, NFS_PROGRAM, roothandle.version, wait, &fd, bufsize, bufsize); if (root_CLIENT == NULL) return (-1); root_CLIENT->cl_auth = authunix_create(my_hostname, 0, 1, 1, &fake_gids); /* * Send NULL proc, check if the server really exists */ rpc_stat = CLNT_CALL(root_CLIENT, 0, xdr_void, NULL, xdr_void, NULL, wait); if (rpc_stat == RPC_SUCCESS) return (0); AUTH_DESTROY(root_CLIENT->cl_auth); CLNT_DESTROY(root_CLIENT); root_CLIENT = NULL; return (-1); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Simple nfs ops - open, close, read, and lseek. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include "clnt.h" #include #include #include #include #include #include "nfs_inet.h" #include #include #include #include #include #include #include "brpc.h" #include #define dprintf if (boothowto & RB_DEBUG) printf static struct timeval zero_timeout = {0, 0}; /* default */ /* * NFS Version 2 specific functions */ ssize_t nfsread(struct nfs_file *filep, char *buf, size_t size) { readargs read_args; readres read_res; enum clnt_stat read_stat; uint_t readcnt = 0; /* # bytes read by nfs */ uint_t count = 0; /* # bytes transferred to buf */ int done = FALSE; /* last block has come in */ int framing_errs = 0; /* stack errors */ char *buf_offset; /* current buffer offset */ struct timeval timeout; static uint_t pos; /* progress indicator counter */ static char ind[] = "|/-\\"; /* progress indicator */ static int blks_read; read_args.file = filep->fh.fh2; /* structure copy */ read_args.offset = filep->offset; buf_offset = buf; /* Optimize for reads of less than one block size */ if (nfs_readsize == 0) nfs_readsize = READ_SIZE; if (size < nfs_readsize) read_args.count = size; else read_args.count = nfs_readsize; do { /* use the user's buffer to stuff the data into. */ read_res.readres_u.reply.data.data_val = buf_offset; /* * Handle the case where the file does not end * on a block boundary. */ if ((count + read_args.count) > size) read_args.count = size - count; timeout.tv_sec = NFS_REXMIT_MIN; /* Total wait for call */ timeout.tv_usec = 0; do { read_stat = CLNT_CALL(root_CLIENT, NFSPROC_READ, xdr_readargs, (caddr_t)&read_args, xdr_readres, (caddr_t)&read_res, timeout); if (read_stat == RPC_TIMEDOUT) { dprintf("NFS read(%d) timed out. Retrying...\n", read_args.count); /* * If the remote is there and trying to respond, * but our stack is having trouble reassembling * the reply, reduce the read size in an * attempt to compensate. Reset the * transmission and reply wait timers. */ if (errno == ETIMEDOUT) framing_errs++; if (framing_errs > NFS_MAX_FERRS && read_args.count > NFS_READ_DECR) { read_args.count -= NFS_READ_DECR; nfs_readsize -= NFS_READ_DECR; dprintf("NFS Read size now %d.\n", nfs_readsize); timeout.tv_sec = NFS_REXMIT_MIN; framing_errs = 0; } else { if (timeout.tv_sec < NFS_REXMIT_MAX) timeout.tv_sec++; else timeout.tv_sec = 0; /* default RPC */ } } } while (read_stat == RPC_TIMEDOUT); if (read_stat != RPC_SUCCESS) return (-1); readcnt = read_res.readres_u.reply.data.data_len; /* * Handle the case where the file is simply empty, and * nothing could be read. */ if (readcnt == 0) break; /* eof */ /* * Handle the case where the file is smaller than * the size of the read request, thus the request * couldn't be completely filled. */ if (readcnt < read_args.count) { #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("nfsread(): partial read %d" " instead of %d\n", readcnt, read_args.count); #endif done = TRUE; /* update the counts and exit */ } /* update various offsets */ count += readcnt; filep->offset += readcnt; buf_offset += readcnt; read_args.offset += readcnt; /* * round and round she goes (though not on every block.. * - OBP's take a fair bit of time to actually print stuff) */ if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); } while (count < size && !done); return (count); } static vtype_t nf_to_vt[] = { VNON, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK }; int nfsgetattr(struct nfs_file *nfp, struct vattr *vap) { enum clnt_stat getattr_stat; attrstat getattr_res; fattr *na; struct timeval timeout = {0, 0}; /* default */ getattr_stat = CLNT_CALL(root_CLIENT, NFSPROC_GETATTR, xdr_nfs_fh, (caddr_t)&(nfp->fh.fh2), xdr_attrstat, (caddr_t)&getattr_res, timeout); if (getattr_stat != RPC_SUCCESS) { dprintf("nfs_getattr: RPC error %d\n", getattr_stat); return (-1); } if (getattr_res.status != NFS_OK) { nfs_error(getattr_res.status); return (getattr_res.status); } /* adapted from nattr_to_vattr() in nfs_client.c */ na = &getattr_res.attrstat_u.attributes; if (vap->va_mask & AT_TYPE) { if (na->type < NFNON || na->type > NFSOCK) vap->va_type = VBAD; else vap->va_type = nf_to_vt[na->type]; } if (vap->va_mask & AT_MODE) vap->va_mode = na->mode; if (vap->va_mask & AT_SIZE) vap->va_size = na->size; if (vap->va_mask & AT_NODEID) vap->va_nodeid = na->fileid; if (vap->va_mask & AT_ATIME) { vap->va_atime.tv_sec = na->atime.seconds; vap->va_atime.tv_nsec = na->atime.useconds * 1000; } if (vap->va_mask & AT_CTIME) { vap->va_ctime.tv_sec = na->ctime.seconds; vap->va_ctime.tv_nsec = na->ctime.useconds * 1000; } if (vap->va_mask & AT_MTIME) { vap->va_mtime.tv_sec = na->mtime.seconds; vap->va_mtime.tv_nsec = na->mtime.useconds * 1000; } #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("nfs_getattr(): done.\n"); #endif return (getattr_res.status); } /* * Display nfs error messages. */ /*ARGSUSED*/ void nfs_error(enum nfsstat status) { if (!(boothowto & RB_DEBUG)) return; switch (status) { case NFSERR_PERM: printf("NFS: Not owner.\n"); break; case NFSERR_NOENT: #ifdef NFS_OPS_DEBUG printf("NFS: No such file or directory.\n"); #endif /* NFS_OPS_DEBUG */ break; case NFSERR_IO: printf("NFS: IO ERROR occurred on NFS server.\n"); break; case NFSERR_NXIO: printf("NFS: No such device or address.\n"); break; case NFSERR_ACCES: printf("NFS: Permission denied.\n"); break; case NFSERR_EXIST: printf("NFS: File exists.\n"); break; case NFSERR_NODEV: printf("NFS: No such device.\n"); break; case NFSERR_NOTDIR: printf("NFS: Not a directory.\n"); break; case NFSERR_ISDIR: printf("NFS: Is a directory.\n"); break; case NFSERR_FBIG: printf("NFS: File too large.\n"); break; case NFSERR_NOSPC: printf("NFS: No space left on device.\n"); break; case NFSERR_ROFS: printf("NFS: Read-only filesystem.\n"); break; case NFSERR_NAMETOOLONG: printf("NFS: File name too long.\n"); break; case NFSERR_NOTEMPTY: printf("NFS: Directory not empty.\n"); break; case NFSERR_DQUOT: printf("NFS: Disk quota exceeded.\n"); break; case NFSERR_STALE: printf("NFS: Stale file handle.\n"); break; case NFSERR_WFLUSH: printf("NFS: server's write cache has been flushed.\n"); break; default: printf("NFS: unknown error.\n"); break; } } struct nfs_file * nfslookup(struct nfs_file *dir, char *name, int *nstat) { static struct nfs_file cd; diropargs dirop; diropres res_lookup; enum clnt_stat status; *nstat = (int)NFS_OK; bcopy(&dir->fh.fh2, &dirop.dir, NFS_FHSIZE); dirop.name = name; status = CLNT_CALL(root_CLIENT, NFSPROC_LOOKUP, xdr_diropargs, (caddr_t)&dirop, xdr_diropres, (caddr_t)&res_lookup, zero_timeout); if (status != RPC_SUCCESS) { dprintf("lookup: RPC error.\n"); return (NULL); } if (res_lookup.status != NFS_OK) { nfs_error(res_lookup.status); *nstat = (int)res_lookup.status; return (NULL); } bzero((caddr_t)&cd, sizeof (struct nfs_file)); cd.version = NFS_VERSION; cd.ftype.type2 = res_lookup.diropres_u.diropres.attributes.type; bcopy(&res_lookup.diropres_u.diropres.file, &cd.fh.fh2, NFS_FHSIZE); return (&cd); } /* * Gets symbolic link into pathname. */ int nfsgetsymlink(struct nfs_file *cfile, char **path) { enum clnt_stat status; struct readlinkres linkres; static char symlink_path[NFS_MAXPATHLEN]; /* * linkres needs a zeroed buffer to place path data into: */ bzero(symlink_path, NFS_MAXPATHLEN); linkres.readlinkres_u.data = &symlink_path[0]; status = CLNT_CALL(root_CLIENT, NFSPROC_READLINK, xdr_nfs_fh, (caddr_t)&cfile->fh.fh2, xdr_readlinkres, (caddr_t)&linkres, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfsgetsymlink: RPC call failed.\n"); return (-1); } if (linkres.status != NFS_OK) { nfs_error(linkres.status); return (linkres.status); } *path = linkres.readlinkres_u.data; return (NFS_OK); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include /* * Xdr routines for NFS ops. */ static bool_t xdr_b_nfs_fh3(XDR *xdrs, nfs_fh3 *objp) { return (xdr_bytes(xdrs, (char **)&objp->data.data_val, (uint_t *)&objp->data.data_len, NFS3_FHSIZE)); } static bool_t xdr_b_fattr3(XDR *xdrs, fattr3 *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->type)) return (FALSE); if (!xdr_u_int(xdrs, &objp->mode)) return (FALSE); if (!xdr_u_int(xdrs, &objp->nlink)) return (FALSE); if (!xdr_u_int(xdrs, &objp->uid)) return (FALSE); if (!xdr_u_int(xdrs, &objp->gid)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->size)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->used)) return (FALSE); if (!xdr_u_int(xdrs, &objp->rdev.specdata1)) return (FALSE); if (!xdr_u_int(xdrs, &objp->rdev.specdata2)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->fsid)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->fileid)) return (FALSE); if (!xdr_u_int(xdrs, &objp->atime.seconds)) return (FALSE); if (!xdr_u_int(xdrs, &objp->atime.nseconds)) return (FALSE); if (!xdr_u_int(xdrs, &objp->mtime.seconds)) return (FALSE); if (!xdr_u_int(xdrs, &objp->mtime.nseconds)) return (FALSE); if (!xdr_u_int(xdrs, &objp->ctime.seconds)) return (FALSE); return (xdr_u_int(xdrs, &objp->ctime.nseconds)); } static bool_t xdr_b_post_op_attr(XDR *xdrs, post_op_attr *objp) { if (!xdr_bool(xdrs, &objp->attributes_follow)) return (FALSE); switch (objp->attributes_follow) { case TRUE: return (xdr_b_fattr3(xdrs, &objp->post_op_attr_u.attributes)); case FALSE: return (TRUE); default: return (FALSE); } } static bool_t xdr_b_diropargs3(XDR *xdrs, diropargs3 *objp) { if (!xdr_b_nfs_fh3(xdrs, &objp->dir)) return (FALSE); return (xdr_string(xdrs, &objp->name, ~0)); } bool_t xdr_GETATTR3args(XDR *xdrs, GETATTR3args *objp) { return (xdr_b_nfs_fh3(xdrs, &objp->object)); } static bool_t xdr_b_GETATTR3resok(XDR *xdrs, GETATTR3resok *objp) { return (xdr_b_fattr3(xdrs, &objp->obj_attributes)); } bool_t xdr_GETATTR3res(XDR *xdrs, GETATTR3res *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->status)) return (FALSE); if (objp->status == NFS3_OK) return (xdr_b_GETATTR3resok(xdrs, &objp->GETATTR3res_u.resok)); return (TRUE); } bool_t xdr_LOOKUP3args(XDR *xdrs, LOOKUP3args *objp) { return (xdr_b_diropargs3(xdrs, &objp->what)); } static bool_t xdr_b_LOOKUP3resok(XDR *xdrs, LOOKUP3resok *objp) { if (!xdr_b_nfs_fh3(xdrs, &objp->object)) return (FALSE); if (!xdr_b_post_op_attr(xdrs, &objp->obj_attributes)) return (FALSE); return (xdr_b_post_op_attr(xdrs, &objp->dir_attributes)); } static bool_t xdr_b_LOOKUP3resfail(XDR *xdrs, LOOKUP3resfail *objp) { return (xdr_b_post_op_attr(xdrs, &objp->dir_attributes)); } bool_t xdr_LOOKUP3res(XDR *xdrs, LOOKUP3res *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->status)) return (FALSE); if (objp->status == NFS3_OK) return (xdr_b_LOOKUP3resok(xdrs, &objp->LOOKUP3res_u.resok)); return (xdr_b_LOOKUP3resfail(xdrs, &objp->LOOKUP3res_u.resfail)); } bool_t xdr_READLINK3args(XDR *xdrs, READLINK3args *objp) { return (xdr_b_nfs_fh3(xdrs, &objp->symlink)); } static bool_t xdr_b_READLINK3resok(XDR *xdrs, READLINK3resok *objp) { if (!xdr_b_post_op_attr(xdrs, &objp->symlink_attributes)) return (FALSE); return (xdr_string(xdrs, &objp->data, ~0)); } static bool_t xdr_b_READLINK3resfail(XDR *xdrs, READLINK3resfail *objp) { return (xdr_b_post_op_attr(xdrs, &objp->symlink_attributes)); } bool_t xdr_READLINK3res(XDR *xdrs, READLINK3res *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->status)) return (FALSE); if (objp->status == NFS3_OK) return (xdr_b_READLINK3resok(xdrs, &objp->READLINK3res_u.resok)); return (xdr_b_READLINK3resfail(xdrs, &objp->READLINK3res_u.resfail)); } bool_t xdr_READ3args(XDR *xdrs, READ3args *objp) { if (!xdr_b_nfs_fh3(xdrs, &objp->file)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->offset)) return (FALSE); return (xdr_u_int(xdrs, &objp->count)); } static bool_t xdr_b_READ3resok(XDR *xdrs, READ3resok *objp) { if (!xdr_b_post_op_attr(xdrs, &objp->file_attributes)) return (FALSE); if (!xdr_u_int(xdrs, &objp->count)) return (FALSE); if (!xdr_bool(xdrs, &objp->eof)) return (FALSE); return (xdr_bytes(xdrs, (char **)&objp->data.data_val, (uint_t *)&objp->data.data_len, ~0)); } static bool_t xdr_b_READ3resfail(XDR *xdrs, READ3resfail *objp) { return (xdr_b_post_op_attr(xdrs, &objp->file_attributes)); } bool_t xdr_READ3res(XDR *xdrs, READ3res *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->status)) return (FALSE); if (objp->status == NFS3_OK) return (xdr_b_READ3resok(xdrs, &objp->READ3res_u.resok)); return (xdr_b_READ3resfail(xdrs, &objp->READ3res_u.resfail)); } bool_t xdr_READDIR3args(XDR *xdrs, READDIR3args *objp) { if (!xdr_b_nfs_fh3(xdrs, &objp->dir)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->cookie)) return (FALSE); if (!xdr_opaque(xdrs, objp->cookieverf, NFS3_COOKIEVERFSIZE)) return (FALSE); return (xdr_u_int(xdrs, &objp->count)); } static bool_t xdr_b_entry3(XDR *xdrs, entry3 *objp) { if (!xdr_u_longlong_t(xdrs, &objp->fileid)) return (FALSE); if (!xdr_string(xdrs, &objp->name, ~0)) return (FALSE); if (!xdr_u_longlong_t(xdrs, &objp->cookie)) return (FALSE); return (xdr_pointer(xdrs, (char **)&objp->nextentry, sizeof (entry3), (xdrproc_t)xdr_b_entry3)); } static bool_t xdr_b_READDIR3resok(XDR *xdrs, READDIR3resok *objp) { if (!xdr_b_post_op_attr(xdrs, &objp->dir_attributes)) return (FALSE); if (!xdr_opaque(xdrs, objp->cookieverf, NFS3_COOKIEVERFSIZE)) return (FALSE); if (!xdr_pointer(xdrs, (char **)&objp->reply.entries, sizeof (entry3), (xdrproc_t)xdr_b_entry3)) return (FALSE); return (xdr_bool(xdrs, &objp->reply.eof)); } static bool_t xdr_b_READDIR3resfail(XDR *xdrs, READDIR3resfail *objp) { return (xdr_b_post_op_attr(xdrs, &objp->dir_attributes)); } bool_t xdr_READDIR3res(XDR *xdrs, READDIR3res *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->status)) return (FALSE); if (objp->status == NFS3_OK) return (xdr_b_READDIR3resok(xdrs, &objp->READDIR3res_u.resok)); return (xdr_b_READDIR3resfail(xdrs, &objp->READDIR3res_u.resfail)); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Simple nfs V3 ops */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include "clnt.h" #include #include #include #include #include #include "nfs_inet.h" #include #include #include #include #include #include #include "brpc.h" #include #define dprintf if (boothowto & RB_DEBUG) printf /* * NFS Version 3 specific functions */ ssize_t nfs3read(struct nfs_file *filep, char *buf, size_t size) { READ3args read_args; READ3res read_res; enum clnt_stat read_stat; uint_t readcnt = 0; /* # bytes read by nfs */ uint_t count = 0; /* # bytes transferred to buf */ int done = FALSE; /* last block has come in */ int framing_errs = 0; /* stack errors */ char *buf_offset; /* current buffer offset */ struct timeval timeout; static uint_t pos; /* progress indicator counter */ static char ind[] = "|/-\\"; /* progress indicator */ static int blks_read; read_args.file.data.data_len = filep->fh.fh3.len; read_args.file.data.data_val = filep->fh.fh3.data; read_args.offset = filep->offset; bzero(&read_res, sizeof (read_res)); buf_offset = buf; /* Optimize for reads of less than one block size */ if (nfs_readsize == 0) nfs_readsize = READ3_SIZE; if (size < nfs_readsize) read_args.count = size; else read_args.count = nfs_readsize; do { /* use the user's buffer to stuff the data into. */ read_res.READ3res_u.resok.data.data_val = buf_offset; /* * Handle the case where the file does not end * on a block boundary. */ if ((count + read_args.count) > size) read_args.count = size - count; timeout.tv_sec = NFS_REXMIT_MIN; /* Total wait for call */ timeout.tv_usec = 0; do { read_stat = CLNT_CALL(root_CLIENT, NFSPROC3_READ, xdr_READ3args, (caddr_t)&read_args, xdr_READ3res, (caddr_t)&read_res, timeout); if (read_stat == RPC_TIMEDOUT) { dprintf("NFS read(%d) timed out. Retrying...\n", read_args.count); /* * If the remote is there and trying to respond, * but our stack is having trouble reassembling * the reply, reduce the read size in an * attempt to compensate. Reset the * transmission and reply wait timers. */ if (errno == ETIMEDOUT) framing_errs++; if (framing_errs > NFS_MAX_FERRS && read_args.count > NFS_READ_DECR) { read_args.count /= 2; nfs_readsize /= 2; dprintf("NFS Read size now %d.\n", nfs_readsize); timeout.tv_sec = NFS_REXMIT_MIN; framing_errs = 0; } else { if (timeout.tv_sec < NFS_REXMIT_MAX) timeout.tv_sec++; else timeout.tv_sec = 0; /* default RPC */ } } } while (read_stat == RPC_TIMEDOUT); if (read_stat != RPC_SUCCESS) return (-1); if (read_res.status != NFS3_OK) return (-1); readcnt = read_res.READ3res_u.resok.data.data_len; /* * If we are at EOF, update counts and exit */ if (read_res.READ3res_u.resok.eof == TRUE) done = TRUE; /* * Handle the case where the file is smaller than * the size of the read request, thus the request * couldn't be completely filled. */ if (readcnt < read_args.count) { #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("nfs3read(): partial read %d" " instead of %d\n", readcnt, read_args.count); #endif done = TRUE; /* update the counts and exit */ } /* update various offsets */ count += readcnt; filep->offset += readcnt; buf_offset += readcnt; read_args.offset += readcnt; /* * round and round she goes (though not on every block.. * - OBP's take a fair bit of time to actually print stuff) */ if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); } while (count < size && !done); return (count); } int nfs3getattr(struct nfs_file *nfp, struct vattr *vap) { enum clnt_stat getattr_stat; GETATTR3args getattr_args; GETATTR3res getattr_res; fattr3 *na; struct timeval timeout = {0, 0}; /* default */ vtype_t nf3_to_vt[] = { VBAD, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK, VFIFO }; bzero(&getattr_args, sizeof (getattr_args)); getattr_args.object.data.data_len = nfp->fh.fh3.len; getattr_args.object.data.data_val = nfp->fh.fh3.data; bzero(&getattr_res, sizeof (getattr_res)); getattr_stat = CLNT_CALL(root_CLIENT, NFSPROC3_GETATTR, xdr_GETATTR3args, (caddr_t)&getattr_args, xdr_GETATTR3res, (caddr_t)&getattr_res, timeout); if (getattr_stat != RPC_SUCCESS) { dprintf("nfs_getattr: RPC error %d\n", getattr_stat); return (-1); } if (getattr_res.status != NFS3_OK) { nfs3_error(getattr_res.status); return (getattr_res.status); } na = &getattr_res.GETATTR3res_u.resok.obj_attributes; if (vap->va_mask & AT_TYPE) { if (na->type < NF3REG || na->type > NF3FIFO) vap->va_type = VBAD; else vap->va_type = nf3_to_vt[na->type]; } if (vap->va_mask & AT_MODE) vap->va_mode = (mode_t)na->mode; if (vap->va_mask & AT_SIZE) vap->va_size = (u_offset_t)na->size; if (vap->va_mask & AT_NODEID) vap->va_nodeid = (u_longlong_t)na->fileid; if (vap->va_mask & AT_ATIME) { vap->va_atime.tv_sec = na->atime.seconds; vap->va_atime.tv_nsec = na->atime.nseconds; } if (vap->va_mask & AT_CTIME) { vap->va_ctime.tv_sec = na->ctime.seconds; vap->va_ctime.tv_nsec = na->ctime.nseconds; } if (vap->va_mask & AT_MTIME) { vap->va_mtime.tv_sec = na->mtime.seconds; vap->va_mtime.tv_nsec = na->mtime.nseconds; } return (NFS3_OK); } /* * Display nfs error messages. */ /*ARGSUSED*/ void nfs3_error(enum nfsstat3 status) { if (!(boothowto & RB_DEBUG)) return; switch (status) { case NFS3_OK: printf("NFS: No error.\n"); break; case NFS3ERR_PERM: printf("NFS: Not owner.\n"); break; case NFS3ERR_NOENT: #ifdef NFS_OPS_DEBUG printf("NFS: No such file or directory.\n"); #endif /* NFS_OPS_DEBUG */ break; case NFS3ERR_IO: printf("NFS: IO ERROR occurred on NFS server.\n"); break; case NFS3ERR_NXIO: printf("NFS: No such device or address.\n"); break; case NFS3ERR_ACCES: printf("NFS: Permission denied.\n"); break; case NFS3ERR_EXIST: printf("NFS: File exists.\n"); break; case NFS3ERR_XDEV: printf("NFS: Cross device hard link.\n"); break; case NFS3ERR_NODEV: printf("NFS: No such device.\n"); break; case NFS3ERR_NOTDIR: printf("NFS: Not a directory.\n"); break; case NFS3ERR_ISDIR: printf("NFS: Is a directory.\n"); break; case NFS3ERR_INVAL: printf("NFS: Invalid argument.\n"); break; case NFS3ERR_FBIG: printf("NFS: File too large.\n"); break; case NFS3ERR_NOSPC: printf("NFS: No space left on device.\n"); break; case NFS3ERR_ROFS: printf("NFS: Read-only filesystem.\n"); break; case NFS3ERR_MLINK: printf("NFS: Too many hard links.\n"); break; case NFS3ERR_NAMETOOLONG: printf("NFS: File name too long.\n"); break; case NFS3ERR_NOTEMPTY: printf("NFS: Directory not empty.\n"); break; case NFS3ERR_DQUOT: printf("NFS: Disk quota exceeded.\n"); break; case NFS3ERR_STALE: printf("NFS: Stale file handle.\n"); break; case NFS3ERR_REMOTE: printf("NFS: Remote file in path.\n"); break; case NFS3ERR_BADHANDLE: printf("NFS: Illegal NFS file handle.\n"); break; case NFS3ERR_NOT_SYNC: printf("NFS: Synchronization mismatch.\n"); break; case NFS3ERR_BAD_COOKIE: printf("NFS: Stale Cookie.\n"); break; case NFS3ERR_NOTSUPP: printf("NFS: Operation is not supported.\n"); break; case NFS3ERR_TOOSMALL: printf("NFS: Buffer too small.\n"); break; case NFS3ERR_SERVERFAULT: printf("NFS: Server fault.\n"); break; case NFS3ERR_BADTYPE: printf("NFS: Unsupported object type.\n"); break; case NFS3ERR_JUKEBOX: printf("NFS: Resource temporarily unavailable.\n"); break; default: printf("NFS: unknown error.\n"); break; } } struct nfs_file * nfs3lookup(struct nfs_file *dir, char *name, int *nstat) { struct timeval zero_timeout = {0, 0}; /* default */ static struct nfs_file cd; LOOKUP3args dirop; LOOKUP3res res_lookup; enum clnt_stat status; *nstat = (int)NFS3_OK; bzero((caddr_t)&dirop, sizeof (LOOKUP3args)); bzero((caddr_t)&res_lookup, sizeof (LOOKUP3res)); dirop.what.dir.data.data_len = dir->fh.fh3.len; dirop.what.dir.data.data_val = dir->fh.fh3.data; dirop.what.name = name; status = CLNT_CALL(root_CLIENT, NFSPROC3_LOOKUP, xdr_LOOKUP3args, (caddr_t)&dirop, xdr_LOOKUP3res, (caddr_t)&res_lookup, zero_timeout); if (status != RPC_SUCCESS) { dprintf("lookup: RPC error.\n"); return (NULL); } if (res_lookup.status != NFS3_OK) { nfs3_error(res_lookup.status); *nstat = (int)res_lookup.status; (void) CLNT_FREERES(root_CLIENT, xdr_LOOKUP3res, (caddr_t)&res_lookup); return (NULL); } bzero((caddr_t)&cd, sizeof (struct nfs_file)); cd.version = NFS_V3; /* * Server must supply post_op_attr's */ if (res_lookup.LOOKUP3res_u.resok.obj_attributes.attributes_follow == FALSE) { printf("nfs3lookup: server fails to return post_op_attr\n"); (void) CLNT_FREERES(root_CLIENT, xdr_LOOKUP3res, (caddr_t)&res_lookup); return (NULL); } cd.ftype.type3 = res_lookup.LOOKUP3res_u.resok.obj_attributes .post_op_attr_u.attributes.type; cd.fh.fh3.len = res_lookup.LOOKUP3res_u.resok.object.data.data_len; bcopy(res_lookup.LOOKUP3res_u.resok.object.data.data_val, cd.fh.fh3.data, cd.fh.fh3.len); (void) CLNT_FREERES(root_CLIENT, xdr_LOOKUP3res, (caddr_t)&res_lookup); return (&cd); } /* * Gets symbolic link into pathname. */ int nfs3getsymlink(struct nfs_file *cfile, char **path) { struct timeval zero_timeout = {0, 0}; /* default */ enum clnt_stat status; struct READLINK3res linkres; struct READLINK3args linkargs; static char symlink_path[NFS_MAXPATHLEN]; bzero(&linkargs, sizeof (linkargs)); linkargs.symlink.data.data_len = cfile->fh.fh3.len; linkargs.symlink.data.data_val = cfile->fh.fh3.data; /* * linkres needs a zeroed buffer to place path data into: */ bzero(&linkres, sizeof (linkres)); bzero(symlink_path, NFS_MAXPATHLEN); linkres.READLINK3res_u.resok.data = symlink_path; status = CLNT_CALL(root_CLIENT, NFSPROC3_READLINK, xdr_READLINK3args, (caddr_t)&linkargs, xdr_READLINK3res, (caddr_t)&linkres, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs3getsymlink: RPC call failed.\n"); return (-1); } if (linkres.status != NFS3_OK) { nfs3_error(linkres.status); return (linkres.status); } *path = symlink_path; return (NFS3_OK); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2015 Nexenta Systems, Inc. All rights reserved. */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include #include #include #include #include "nfs_inet.h" #define dprintf if (boothowto & RB_DEBUG) printf /* * XDR routines for NFSv4 ops. */ static bool_t xdr_b_utf8string(XDR *xdrs, utf8string *objp) { return (xdr_bytes(xdrs, (char **)&objp->utf8string_val, (uint_t *)&objp->utf8string_len, NFS4_MAX_UTF8STRING)); } static bool_t xdr_nfs_bfh4(XDR *xdrs, struct nfs_bfh4 *objp) { char *data = (char *)&objp->data; return (xdr_bytes(xdrs, (char **)&data, (uint_t *)&objp->len, NFS4_FHSIZE)); } static bool_t xdr_b_putfh4_args(XDR *xdrs, putfh4arg_t *objp) { if (!xdr_u_int(xdrs, (uint_t *)&objp->pf_opnum)) return (FALSE); return (xdr_nfs_bfh4(xdrs, (struct nfs_bfh4 *)&objp->pf_filehandle)); } /* * Common xdr routines for compound. Let the specific op routines handle * op specific portions of the compound. */ static bool_t xdr_b_compound_args(XDR *xdrs, b_compound_t *objp) { if (!xdr_b_utf8string(xdrs, &objp->ca_tag)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->ca_minorversion)) return (FALSE); if (!xdr_u_int(xdrs, &objp->ca_argarray_len)) return (FALSE); if (objp->ca_isputrootfh) return (xdr_u_int(xdrs, &objp->ca_opputfh.pf_opnum)); return (xdr_b_putfh4_args(xdrs, &objp->ca_opputfh)); } static bool_t xdr_b_compound_res(XDR *xdrs, b_compound_t *objp) { if (!xdr_enum(xdrs, (enum_t *)&objp->cr_status)) return (FALSE); if (!xdr_b_utf8string(xdrs, &objp->cr_tag)) return (FALSE); if (!xdr_u_int(xdrs, &objp->cr_resarray_len)) return (FALSE); if (!xdr_u_int(xdrs, &objp->cr_opputfh)) return (FALSE); return (xdr_enum(xdrs, (enum_t *)&objp->cr_putfh_status)); } static bool_t xdr_b_bitmap4(XDR *xdrs, b_bitmap4_t *objp) { char *arp = (char *)&objp->b_bitmap_val; return (xdr_array(xdrs, (char **)&arp, (uint_t *)&objp->b_bitmap_len, ~0, sizeof (uint_t), (xdrproc_t)xdr_u_int)); } static bool_t xdr_b_stateid4(XDR *xdrs, stateid4 *objp) { if (!xdr_u_int(xdrs, (uint_t *)&objp->seqid)) return (FALSE); return (xdr_opaque(xdrs, objp->other, NFS4_OTHER_SIZE)); } bool_t xdr_getattr4_args(XDR *xdrs, getattr4arg_t *objp) { if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->ga_arg)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->ga_opgetattr)) return (FALSE); return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->ga_attr_req)); } static bool_t xdr_b_getattr_res_common(XDR *xdrs, getattrres_cmn_t *objp) { if (!xdr_u_int(xdrs, (uint_t *)&objp->gc_opgetattr)) return (FALSE); if (!xdr_enum(xdrs, (enum_t *)&objp->gc_attr_status)) return (FALSE); /* * If the getattr suceeded, proceed and begin to decode the attributes. */ if (objp->gc_attr_status == NFS4_OK) { char attrvals[sizeof (b_fattr4_t)]; char *ap = attrvals; if (!xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->gc_retattr)) return (FALSE); bzero(&attrvals, sizeof (attrvals)); if (!xdr_bytes(xdrs, (char **)&ap, (uint_t *)&objp->gc_attrlist_len, sizeof (b_fattr4_t))) return (FALSE); #ifdef DEBUG printf("xdr_b_getattr_res_common: attrlist_len = %d\n", objp->gc_attrlist_len); #endif /* * Go through the bitmap and see if the server * sent us anything. */ if (objp->gc_attrlist_len > 0) { XDR mxdrs; b_fattr4_t *fattrp = &objp->gc_attrs; attr4_bitmap1_t bitmap1; attr4_bitmap2_t bitmap2; #ifdef DEBUG int i; printf("dumping contents of attr buffer\n"); for (i = 0; i < objp->gc_attrlist_len; i++) { printf("[%d] = 0x%x\n", i, ap[i]); } #endif bitmap1.word = objp->gc_retattr.b_bitmap_val[0]; bitmap2.word = objp->gc_retattr.b_bitmap_val[1]; #ifdef DEBUG printf("xdr_b_getattr_res_common: bitmap1 = %d " " bitmap2 = %d\n", bitmap1.word, bitmap2.word); #endif xdrmem_create(&mxdrs, ap, objp->gc_attrlist_len, XDR_DECODE); /* * Start with the first bitmap */ if (bitmap1.word > 0) { if (bitmap1.bm_supported_attrs) { if (!xdr_b_bitmap4(&mxdrs, (b_bitmap4_t *)&fattrp-> b_supported_attrs)) return (FALSE); } if (bitmap1.bm_fattr4_type) { if (!xdr_enum(&mxdrs, (enum_t *)&fattrp->b_fattr4_type)) { return (FALSE); } } if (bitmap1.bm_fattr4_size) { if (!xdr_u_longlong_t(&mxdrs, (u_longlong_t *)&fattrp-> b_fattr4_size)) return (FALSE); } if (bitmap1.bm_fattr4_fsid) { if (!xdr_u_longlong_t(&mxdrs, (u_longlong_t *)&fattrp-> b_fattr4_fsid.major)) return (FALSE); if (!xdr_u_longlong_t(&mxdrs, (u_longlong_t *)&fattrp-> b_fattr4_fsid.minor)) return (FALSE); } if (bitmap1.bm_fattr4_filehandle) { if (!xdr_nfs_bfh4(&mxdrs, (struct nfs_bfh4 *)&fattrp-> b_fattr4_filehandle)) return (FALSE); } if (bitmap1.bm_fattr4_fileid) { if (!xdr_u_longlong_t(&mxdrs, (u_longlong_t *)&fattrp-> b_fattr4_fileid)) return (FALSE); } } /* * Now the second bitmap */ if (bitmap2.word > 0) { if (bitmap2.bm_fattr4_mode) { if (!xdr_u_int(&mxdrs, (uint_t *)&objp-> gc_attrs.b_fattr4_mode)) return (FALSE); } if (bitmap2.bm_fattr4_time_access) { if (!xdr_longlong_t(&mxdrs, (longlong_t *)&objp->gc_attrs. b_fattr4_time_access.seconds)) return (FALSE); if (!xdr_u_int(&mxdrs, (uint_t *)&objp->gc_attrs. b_fattr4_time_access.nseconds)) return (FALSE); } if (bitmap2.bm_fattr4_time_metadata) { if (!xdr_longlong_t(&mxdrs, (longlong_t *)&objp->gc_attrs. b_fattr4_time_metadata.seconds)) return (FALSE); if (!xdr_u_int(&mxdrs, (uint_t *)&objp->gc_attrs. b_fattr4_time_metadata.nseconds)) return (FALSE); } if (bitmap2.bm_fattr4_time_modify) { if (!xdr_longlong_t(&mxdrs, (longlong_t *)&objp->gc_attrs. b_fattr4_time_modify.seconds)) return (FALSE); if (!xdr_u_int(&mxdrs, (uint_t *)&objp->gc_attrs. b_fattr4_time_modify.nseconds)) return (FALSE); } } } } return (TRUE); } bool_t xdr_getattr4_res(XDR *xdrs, getattr4res_t *objp) { if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->gr_res)) return (FALSE); return (xdr_b_getattr_res_common(xdrs, (getattrres_cmn_t *)&objp->gr_cmn)); } bool_t xdr_lookup4_args(XDR *xdrs, lookup4arg_t *objp) { if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->la_arg)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->la_oplookup)) return (FALSE); if (!xdr_b_utf8string(xdrs, (utf8string *)&objp->la_pathname)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->la_opgetattr)) return (FALSE); return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->la_attr_req)); } bool_t xdr_lookup4_res(XDR *xdrs, lookup4res_t *objp) { if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->lr_res)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->lr_oplookup)) return (FALSE); if (!xdr_enum(xdrs, (enum_t *)&objp->lr_lookup_status)) return (FALSE); if (objp->lr_lookup_status == NFS4_OK) { return (xdr_b_getattr_res_common(xdrs, (getattrres_cmn_t *)&objp->lr_gcmn)); } return (TRUE); } bool_t xdr_lookupp4_args(XDR *xdrs, lookupp4arg_t *objp) { if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->la_arg)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->la_oplookupp)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->la_opgetattr)) return (FALSE); return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->la_attr_req)); } bool_t xdr_read4_args(XDR *xdrs, read4arg_t *objp) { if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->r_arg)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->r_opread)) return (FALSE); if (!xdr_b_stateid4(xdrs, (stateid4 *)&objp->r_stateid)) return (FALSE); if (!xdr_u_longlong_t(xdrs, (u_longlong_t *)&objp->r_offset)) return (FALSE); return (xdr_u_int(xdrs, (uint_t *)&objp->r_count)); } bool_t xdr_read4_res(XDR *xdrs, read4res_t *objp) { if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->r_res)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->r_opread)) return (FALSE); if (!xdr_enum(xdrs, (enum_t *)&objp->r_status)) return (FALSE); if (objp->r_status == NFS4_OK) { if (!xdr_bool(xdrs, (bool_t *)&objp->r_eof)) return (FALSE); return (xdr_bytes(xdrs, (char **)&objp->r_data_val, (uint_t *)&objp->r_data_len, ~0)); } return (TRUE); } bool_t xdr_readdir4_args(XDR *xdrs, readdir4arg_t *objp) { if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->rd_arg)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_opreaddir)) return (FALSE); if (!xdr_u_longlong_t(xdrs, (u_longlong_t *)&objp->rd_cookie)) return (FALSE); if (!xdr_opaque(xdrs, objp->rd_cookieverf, NFS4_VERIFIER_SIZE)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_dircount)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_maxcount)) return (FALSE); return (xdr_b_bitmap4(xdrs, (b_bitmap4_t *)&objp->rd_attr_req)); } static bool_t xdr_b_entry4(XDR *xdrs, b_entry4_t *objp) { uint_t attrlen; char attrvals[sizeof (b_fattr4_t)]; char *ap = attrvals; XDR mxdrs; if (!xdr_u_longlong_t(xdrs, (u_longlong_t *)&objp->b_cookie)) return (FALSE); if (!xdr_b_utf8string(xdrs, &objp->b_name)) return (FALSE); bzero(&attrvals, sizeof (attrvals)); if (!xdr_bytes(xdrs, (char **)&ap, (uint_t *)&attrlen, sizeof (b_fattr4_t))) return (FALSE); /* * We are *only* interested in the fileid, so just extract that. */ if (attrlen < sizeof (uint64_t)) return (FALSE); xdrmem_create(&mxdrs, ap, attrlen, XDR_DECODE); if (!xdr_u_longlong_t(&mxdrs, (u_longlong_t *)&objp->b_fileid)) return (FALSE); return (xdr_pointer(xdrs, (char **)&objp->b_nextentry, sizeof (b_entry4_t), (xdrproc_t)xdr_b_entry4)); } bool_t xdr_readdir4_res(XDR *xdrs, readdir4res_t *objp) { if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->rd_res)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->rd_opreaddir)) return (FALSE); if (!xdr_enum(xdrs, (enum_t *)&objp->rd_status)) return (FALSE); if (objp->rd_status == NFS4_OK) { if (!xdr_opaque(xdrs, objp->rd_cookieverf, NFS4_VERIFIER_SIZE)) return (FALSE); if (!xdr_pointer(xdrs, (char **)&objp->rd_entries, sizeof (b_entry4_t), (xdrproc_t)xdr_b_entry4)) return (FALSE); return (xdr_bool(xdrs, &objp->rd_eof)); } return (TRUE); } bool_t xdr_readlink4_args(XDR *xdrs, readlink4arg_t *objp) { if (!xdr_b_compound_args(xdrs, (b_compound_t *)&objp->rl_arg)) return (FALSE); return (xdr_u_int(xdrs, (uint_t *)&objp->rl_opreadlink)); } bool_t xdr_readlink4_res(XDR *xdrs, readlink4res_t *objp) { if (!xdr_b_compound_res(xdrs, (b_compound_t *)&objp->rl_res)) return (FALSE); if (!xdr_u_int(xdrs, (uint_t *)&objp->rl_opreadlink)) return (FALSE); if (!xdr_enum(xdrs, (enum_t *)&objp->rl_status)) return (FALSE); if (objp->rl_status == NFS4_OK) return (xdr_b_utf8string(xdrs, (utf8string *)&objp->rl_link)); return (TRUE); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Simple nfs V4 ops */ #include #include #include #include "clnt.h" #include #include #include #include #include #include "nfs_inet.h" #include #include #include #include #include #include #include "brpc.h" #include #define dprintf if (boothowto & RB_DEBUG) printf static struct timeval zero_timeout = {0, 0}; /* default */ /* * NFS Version 4 specific functions */ ssize_t nfs4read(struct nfs_file *filep, char *buf, size_t size) { enum clnt_stat status; read4arg_t readargs; read4res_t readres; char *buf_offset; uint_t count = 0; uint_t readcnt = 0; bool_t done = FALSE; struct timeval timeout; int framing_errs = 0; static uint_t pos; static char ind[] = "|/-\\"; static int blks_read; utf8string str; char tagname[] = "inetboot read"; bzero(&readres, sizeof (readres)); str.utf8string_len = sizeof (tagname) - 1; str.utf8string_val = tagname; /* * read */ buf_offset = buf; if (nfs_readsize == 0) nfs_readsize = READ4_SIZE; if (size < nfs_readsize) readargs.r_count = size; else readargs.r_count = nfs_readsize; if (filep->fh.fh4.len > 0) compound_init(&readargs.r_arg, &str, 0, 2, &filep->fh.fh4); else compound_init(&readargs.r_arg, &str, 0, 2, NULL); readargs.r_opread = OP_READ; /* * zero out the stateid field */ bzero(&readargs.r_stateid, sizeof (readargs.r_stateid)); readargs.r_offset = filep->offset; do { readres.r_data_val = buf_offset; if ((count + readargs.r_count) > size) readargs.r_count = size - count; timeout.tv_sec = NFS_REXMIT_MIN; timeout.tv_usec = 0; do { status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_read4_args, (caddr_t)&readargs, xdr_read4_res, (caddr_t)&readres, timeout); if (status == RPC_TIMEDOUT) { dprintf("NFS read(%d) timed out. Retrying...\n", readargs.r_count); if (errno == ETIMEDOUT) framing_errs++; if (framing_errs > NFS_MAX_FERRS && readargs.r_count > NFS_READ_DECR) { readargs.r_count /= 2; nfs_readsize /= 2; dprintf("NFS read size now %d.\n", nfs_readsize); timeout.tv_sec = NFS_REXMIT_MIN; framing_errs = 0; } else { if (timeout.tv_sec < NFS_REXMIT_MAX) timeout.tv_sec++; else timeout.tv_sec = 0; } } } while (status == RPC_TIMEDOUT); if (status != RPC_SUCCESS) return (-1); if (readres.r_status != NFS4_OK) { nfs4_error(readres.r_status); return (-1); } readcnt = readres.r_data_len; if (readres.r_eof == TRUE) done = TRUE; if (readcnt < readargs.r_count) { #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("nfs4read: partial read %d instead " "of %d\n", readcnt, readargs.count); #endif done = TRUE; } count += readcnt; filep->offset += readcnt; buf_offset += readcnt; readargs.r_offset += readcnt; if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); } while (count < size && !done); return (count); } static vtype_t nf4_to_vt[] = { VBAD, VREG, VDIR, VBLK, VCHR, VLNK, VSOCK, VFIFO }; int nfs4getattr(struct nfs_file *nfp, struct vattr *vap) { enum clnt_stat status; attr4_bitmap1_t bitmap1; attr4_bitmap2_t bitmap2; getattr4arg_t getattrargs; getattr4res_t getattrres; b_fattr4_t *bfattr4; utf8string str; char tagname[] = "inetboot getattr"; bzero(&getattrres, sizeof (getattrres)); /* * Putfh */ str.utf8string_len = sizeof (tagname) - 1; str.utf8string_val = tagname; if (nfp->fh.fh4.len > 0) compound_init(&getattrargs.ga_arg, &str, 0, 2, &nfp->fh.fh4); else compound_init(&getattrargs.ga_arg, &str, 0, 2, NULL); /* * getattr */ getattrargs.ga_opgetattr = OP_GETATTR; /* * Set up the attribute bitmap. We pretty much need everything * except for the filehandle and supported attrs. */ bitmap1.word = 0; bitmap1.bm_fattr4_type = 1; bitmap1.bm_fattr4_size = 1; bitmap1.bm_fattr4_fileid = 1; bitmap2.word = 0; bitmap2.bm_fattr4_mode = 1; bitmap2.bm_fattr4_time_access = 1; bitmap2.bm_fattr4_time_metadata = 1; bitmap2.bm_fattr4_time_modify = 1; getattrargs.ga_attr_req.b_bitmap_len = NFS4_MAX_BITWORDS; getattrargs.ga_attr_req.b_bitmap_val[0] = bitmap1.word; getattrargs.ga_attr_req.b_bitmap_val[1] = bitmap2.word; status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_getattr4_args, (caddr_t)&getattrargs, xdr_getattr4_res, (caddr_t)&getattrres, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs4getattr: RPC error %d\n", status); return (-1); } if (getattrres.gr_attr_status != NFS4_OK) { nfs4_error(getattrres.gr_attr_status); return (getattrres.gr_attr_status); } bfattr4 = &getattrres.gr_attrs; if (vap->va_mask & AT_TYPE) { if (bfattr4->b_fattr4_type < NF4REG || bfattr4->b_fattr4_type > NF4FIFO) vap->va_type = VBAD; else vap->va_type = nf4_to_vt[bfattr4->b_fattr4_type]; } if (vap->va_mask & AT_MODE) vap->va_mode = (mode_t)bfattr4->b_fattr4_mode; if (vap->va_mask & AT_SIZE) vap->va_size = (u_offset_t)bfattr4->b_fattr4_size; if (vap->va_mask & AT_NODEID) vap->va_nodeid = (uint64_t)bfattr4->b_fattr4_fileid; /* * XXX - may need to do something more here. */ if (vap->va_mask & AT_ATIME) { vap->va_atime.tv_sec = bfattr4->b_fattr4_time_access.seconds; vap->va_atime.tv_nsec = bfattr4->b_fattr4_time_access.nseconds; } if (vap->va_mask & AT_CTIME) { vap->va_ctime.tv_sec = bfattr4->b_fattr4_time_metadata.seconds; vap->va_ctime.tv_nsec = bfattr4->b_fattr4_time_metadata.nseconds; } if (vap->va_mask & AT_MTIME) { vap->va_mtime.tv_sec = bfattr4->b_fattr4_time_modify.seconds; vap->va_mtime.tv_nsec = bfattr4->b_fattr4_time_modify.nseconds; } return (NFS4_OK); } /* * Display nfs error messages. */ /*ARGSUSED*/ void nfs4_error(enum nfsstat4 status) { if (!(boothowto & RB_DEBUG)) return; switch (status) { case NFS4_OK: printf("NFS: No error.\n"); break; case NFS4ERR_PERM: printf("NFS: Not owner.\n"); break; case NFS4ERR_NOENT: #ifdef NFS_OPS_DEBUG printf("NFS: No such file or directory.\n"); #endif /* NFS_OPS_DEBUG */ break; case NFS4ERR_IO: printf("NFS: IO ERROR occurred on NFS server.\n"); break; case NFS4ERR_NXIO: printf("NFS: No such device or address.\n"); break; case NFS4ERR_ACCESS: printf("NFS: Permission denied.\n"); break; case NFS4ERR_EXIST: printf("NFS: File exists.\n"); break; case NFS4ERR_XDEV: printf("NFS: Cross device hard link.\n"); break; case NFS4ERR_NOTDIR: printf("NFS: Not a directory.\n"); break; case NFS4ERR_ISDIR: printf("NFS: Is a directory.\n"); break; case NFS4ERR_INVAL: printf("NFS: Invalid argument.\n"); break; case NFS4ERR_FBIG: printf("NFS: File too large.\n"); break; case NFS4ERR_NOSPC: printf("NFS: No space left on device.\n"); break; case NFS4ERR_ROFS: printf("NFS: Read-only filesystem.\n"); break; case NFS4ERR_MLINK: printf("NFS: Too many hard links.\n"); break; case NFS4ERR_NAMETOOLONG: printf("NFS: File name too long.\n"); break; case NFS4ERR_NOTEMPTY: printf("NFS: Directory not empty.\n"); break; case NFS4ERR_DQUOT: printf("NFS: Disk quota exceeded.\n"); break; case NFS4ERR_STALE: printf("NFS: Stale file handle.\n"); break; case NFS4ERR_BADHANDLE: printf("NFS: Illegal NFS file handle.\n"); break; case NFS4ERR_BAD_COOKIE: printf("NFS: Stale Cookie.\n"); break; case NFS4ERR_NOTSUPP: printf("NFS: Operation is not supported.\n"); break; case NFS4ERR_TOOSMALL: printf("NFS: Buffer too small.\n"); break; case NFS4ERR_SERVERFAULT: printf("NFS: Server fault.\n"); break; case NFS4ERR_BADTYPE: printf("NFS: Unsupported object type.\n"); break; case NFS4ERR_BAD_STATEID: printf("NFS: Bad stateid\n"); break; case NFS4ERR_BAD_SEQID: printf("NFS: Bad seqid\n"); break; default: printf("NFS: unknown error.\n"); break; } } /* * lookup one component. for multicomponent lookup use a driver like lookup(). */ struct nfs_file * nfs4lookup(struct nfs_file *dir, char *name, int *nstat) { static struct nfs_file cd; attr4_bitmap1_t bitmap1; lookup4arg_t lookupargs; lookup4res_t lookupres; enum clnt_stat status; utf8string str; char tagname[] = "inetboot lookup"; /* * NFSv4 uses a special LOOKUPP op * for looking up the parent directory. */ if (strcmp(name, "..") == 0) return (nfs4lookupp(dir, nstat, NULL)); *nstat = (int)NFS4_OK; bzero(&lookupres, sizeof (lookupres)); /* * Check if we have a filehandle and initialize the compound * with putfh or putrootfh appropriately. */ str.utf8string_len = sizeof (tagname) - 1; str.utf8string_val = tagname; if (dir->fh.fh4.len > 0) compound_init(&lookupargs.la_arg, &str, 0, 3, &dir->fh.fh4); else compound_init(&lookupargs.la_arg, &str, 0, 3, NULL); /* * lookup */ lookupargs.la_oplookup = OP_LOOKUP; /* * convert the pathname from char * to utf8string */ lookupargs.la_pathname.utf8string_len = strlen(name); lookupargs.la_pathname.utf8string_val = bkmem_alloc(lookupargs.la_pathname.utf8string_len); if (lookupargs.la_pathname.utf8string_val == NULL) { dprintf("nfs4lookup: bkmem_alloc failed\n"); return (NULL); } bcopy(name, lookupargs.la_pathname.utf8string_val, lookupargs.la_pathname.utf8string_len); /* * Setup the attr bitmap. All we need is the type and filehandle info */ lookupargs.la_opgetattr = OP_GETATTR; bitmap1.word = 0; bitmap1.bm_fattr4_type = 1; bitmap1.bm_fattr4_filehandle = 1; lookupargs.la_attr_req.b_bitmap_len = 1; lookupargs.la_attr_req.b_bitmap_val[0] = bitmap1.word; lookupargs.la_attr_req.b_bitmap_val[1] = 0; status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_lookup4_args, (caddr_t)&lookupargs, xdr_lookup4_res, (caddr_t)&lookupres, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs4lookup: RPC error. status %d\n", status); return (NULL); } if (lookupres.lr_lookup_status != NFS4_OK) { #ifdef DEBUG dprintf("nfs4lookup: lookup status = %d\n", lookupres.lr_lookup_status); #endif nfs4_error(lookupres.lr_lookup_status); *nstat = (int)lookupres.lr_lookup_status; if (lookupargs.la_pathname.utf8string_val != NULL) bkmem_free(lookupargs.la_pathname.utf8string_val, lookupargs.la_pathname.utf8string_len); return (NULL); } if (lookupres.lr_attr_status != NFS4_OK) { #ifdef DEBUG dprintf("nfs4lookup: getattr status = %d\n", lookupres.lr_attr_status); #endif nfs4_error(lookupres.lr_attr_status); *nstat = (int)lookupres.lr_attr_status; if (lookupargs.la_pathname.utf8string_val != NULL) bkmem_free(lookupargs.la_pathname.utf8string_val, lookupargs.la_pathname.utf8string_len); return (NULL); } /* * We have all the information we need to update the file pointer */ bzero((caddr_t)&cd, sizeof (struct nfs_file)); cd.version = NFS_V4; cd.ftype.type4 = lookupres.lr_attrs.b_fattr4_type; cd.fh.fh4.len = lookupres.lr_attrs.b_fattr4_filehandle.len; bcopy(lookupres.lr_attrs.b_fattr4_filehandle.data, cd.fh.fh4.data, cd.fh.fh4.len); /* * Free the arg string */ if (lookupargs.la_pathname.utf8string_val != NULL) bkmem_free(lookupargs.la_pathname.utf8string_val, lookupargs.la_pathname.utf8string_len); return (&cd); } /* * lookup parent directory. */ struct nfs_file * nfs4lookupp(struct nfs_file *dir, int *nstat, uint64_t *fileid) { static struct nfs_file cd; attr4_bitmap1_t bitmap1; lookupp4arg_t lookuppargs; lookup4res_t lookupres; enum clnt_stat status; utf8string str; char tagname[] = "inetboot lookupp"; *nstat = (int)NFS4_OK; bzero(&lookupres, sizeof (lookupres)); /* * Check if we have a filehandle and initialize the compound * with putfh or putrootfh appropriately. */ str.utf8string_len = sizeof (tagname) - 1; str.utf8string_val = tagname; if (dir->fh.fh4.len > 0) compound_init(&lookuppargs.la_arg, &str, 0, 3, &dir->fh.fh4); else compound_init(&lookuppargs.la_arg, &str, 0, 3, NULL); /* * lookupp */ lookuppargs.la_oplookupp = OP_LOOKUPP; /* * Setup the attr bitmap. Normally, all we need is the type and * filehandle info, but getdents might require the fileid of the * parent. */ lookuppargs.la_opgetattr = OP_GETATTR; bitmap1.word = 0; bitmap1.bm_fattr4_type = 1; bitmap1.bm_fattr4_filehandle = 1; if (fileid != NULL) bitmap1.bm_fattr4_fileid = 1; lookuppargs.la_attr_req.b_bitmap_len = 1; lookuppargs.la_attr_req.b_bitmap_val[0] = bitmap1.word; lookuppargs.la_attr_req.b_bitmap_val[1] = 0; status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_lookupp4_args, (caddr_t)&lookuppargs, xdr_lookup4_res, (caddr_t)&lookupres, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs4lookupp: RPC error. status %d\n", status); return (NULL); } if (lookupres.lr_lookup_status != NFS4_OK) { #ifdef DEBUG dprintf("nfs4lookupp: lookupp status = %d\n", lookupres.lr_lookup_status); #endif nfs4_error(lookupres.lr_lookup_status); *nstat = (int)lookupres.lr_lookup_status; return (NULL); } if (lookupres.lr_attr_status != NFS4_OK) { #ifdef DEBUG dprintf("nfs4lookupp: getattr status = %d\n", lookupres.lr_attr_status); #endif nfs4_error(lookupres.lr_attr_status); *nstat = (int)lookupres.lr_attr_status; return (NULL); } /* * We have all the information we need to update the file pointer */ bzero((caddr_t)&cd, sizeof (struct nfs_file)); cd.version = NFS_V4; cd.ftype.type4 = lookupres.lr_attrs.b_fattr4_type; cd.fh.fh4.len = lookupres.lr_attrs.b_fattr4_filehandle.len; bcopy(lookupres.lr_attrs.b_fattr4_filehandle.data, cd.fh.fh4.data, cd.fh.fh4.len); /* * Fill in the fileid if the user passed in one */ if (fileid != NULL) *fileid = lookupres.lr_attrs.b_fattr4_fileid; return (&cd); } /* * Gets symbolic link into pathname. */ int nfs4getsymlink(struct nfs_file *cfile, char **path) { enum clnt_stat status; readlink4arg_t readlinkargs; readlink4res_t readlinkres; static char symlink_path[NFS_MAXPATHLEN]; int spathlen; utf8string str; char tagname[] = "inetboot getsymlink"; int error = NFS4_OK; bzero(&readlinkres, sizeof (readlinkres)); /* * readlink */ str.utf8string_len = sizeof (tagname) - 1; str.utf8string_val = tagname; if (cfile->fh.fh4.len > 0) compound_init(&readlinkargs.rl_arg, &str, 0, 2, &cfile->fh.fh4); else compound_init(&readlinkargs.rl_arg, &str, 0, 2, NULL); readlinkargs.rl_opreadlink = OP_READLINK; status = CLNT_CALL(root_CLIENT, NFSPROC4_COMPOUND, xdr_readlink4_args, (caddr_t)&readlinkargs, xdr_readlink4_res, (caddr_t)&readlinkres, zero_timeout); if (status != RPC_SUCCESS) { dprintf("nfs4getsymlink: RPC readlink error %d\n", status); error = -1; goto out; } if (readlinkres.rl_status != NFS4_OK) { nfs4_error(readlinkres.rl_status); error = readlinkres.rl_status; goto out; } /* * Convert the utf8string to a normal character string */ spathlen = readlinkres.rl_link.utf8string_len; if (spathlen <= 0 || readlinkres.rl_link.utf8string_val == NULL) { *path = NULL; error = readlinkres.rl_status; goto out; } bcopy(readlinkres.rl_link.utf8string_val, symlink_path, spathlen); symlink_path[spathlen] = '\0'; *path = symlink_path; out: /* * Free the results */ if (readlinkres.rl_link.utf8string_val != NULL) bkmem_free(readlinkres.rl_link.utf8string_val, spathlen); return (error); } /* * Should just forget about the tag, but will leave in support for the time * being. */ void compound_init(b_compound_t *cp, utf8string *str, uint_t mvers, uint_t arglen, struct nfs_bfh4 *pfh) { if (str == NULL || str->utf8string_len == 0) { cp->ca_tag.utf8string_len = 0; cp->ca_tag.utf8string_val = NULL; } else { cp->ca_tag.utf8string_len = str->utf8string_len; cp->ca_tag.utf8string_val = str->utf8string_val; } cp->ca_minorversion = mvers; cp->ca_argarray_len = arglen; if (pfh == NULL) { cp->ca_isputrootfh = TRUE; cp->ca_opputfh.pf_opnum = OP_PUTROOTFH; } else { cp->ca_isputrootfh = FALSE; cp->ca_opputfh.pf_opnum = OP_PUTFH; cp->ca_opputfh.pf_filehandle.len = pfh->len; bcopy(pfh->data, cp->ca_opputfh.pf_filehandle.data, pfh->len); } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * nfs_inet.h contains definitions specific to inetboot's nfs implementation. */ #ifndef _NFS_INET_H #define _NFS_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include #include #include #include #include #include #include #include #include #include #include "clnt.h" #include #include #define NFSBUF_SIZE (READ_SIZE+1024) #define READ_SIZE (8192) /* NFS readsize */ #define NFS_READ_DECR (1024) /* NFS readsize decrement */ #define NFS3BUF_SIZE (READ3_SIZE+1024) #define READ3_SIZE (32 * 1024) /* NFS3 readsize */ #define NFS4BUF_SIZE (READ4_SIZE+1024) #define READ4_SIZE (32 * 1024) /* NFS4 readsize */ #define NFS4_MAX_UTF8STRING (8 * 1024) #define NFS4_MAX_BITWORDS (2) #define NFS_MAX_FERRS (3) /* MAX frame errors before decr read size */ #define NFS_REXMIT_MIN (3) /* NFS retry min in secs */ #define NFS_REXMIT_MAX (15) /* NFS retry max in secs */ extern int nfs_readsize; extern struct nfs_file roothandle; extern CLIENT *root_CLIENT; /* * Boot specific V4 fh with maximum allowed data statically allocated */ struct nfs_bfh4 { uint_t len; char data[NFS4_FHSIZE]; }; /* * Boot specific V3 fh with maximum allowed data statically allocated */ struct nfs_bfh3 { uint_t len; char data[NFS3_FHSIZE]; }; union _nfs_fh { nfs_fh fh2; struct nfs_bfh3 fh3; struct nfs_bfh4 fh4; }; union _nfs_cookie { nfscookie cookie2; cookie3 cookie3; nfs_cookie4 cookie4; }; union _nfs_ftype { ftype type2; ftype3 type3; nfs_ftype4 type4; }; /* * NFS: This structure represents the current open file. */ struct nfs_file { int version; ulong_t offset; union _nfs_ftype ftype; union _nfs_fh fh; union _nfs_cookie cookie; }; struct nfs_fid { ushort_t nf_len; ushort_t nf_pad; struct nfs_fh fh; }; #define cfile_is_dir(cf) (((cf)->version == NFS_VERSION) ? \ ((cf)->ftype.type2 == NFDIR) : \ (((cf)->version == NFS_V3) ? \ ((cf)->ftype.type3 == NF3DIR) : \ (((cf)->version == NFS_V4) ? \ ((cf)->ftype.type4 == NF4DIR) : 0))) #define cfile_is_lnk(cf) (((cf)->version == NFS_VERSION) ? \ ((cf)->ftype.type2 == NFLNK) : \ (((cf)->version == NFS_V3) ? \ ((cf)->ftype.type3 == NF3LNK) : \ (((cf)->version == NFS_V4) ? \ ((cf)->ftype.type4 == NF4LNK) : 0))) /* * Predefine an attribute bitmap that inetboot will most likely be * interested in. */ typedef union attr4_bitmap1_u { struct { unsigned int #ifdef _BIT_FIELDS_HTOL b_pad4: 11, b_fattr4_fileid: 1, b_fattr4_filehandle: 1, b_pad3: 10, b_fattr4_fsid: 1, b_pad2: 3, b_fattr4_size: 1, b_pad1: 2, b_fattr4_type: 1, b_supported_attrs: 1; #endif #ifdef _BIT_FIELDS_LTOH b_supported_attrs: 1, b_fattr4_type: 1, b_pad1: 2, b_fattr4_size: 1, b_pad2: 3, b_fattr4_fsid: 1, b_pad3: 10, b_fattr4_filehandle: 1, b_fattr4_fileid: 1, b_pad4: 11; #endif } bitmap_s; uint_t word; } attr4_bitmap1_t; #define bm_supported_attrs bitmap_s.b_supported_attrs #define bm_fattr4_type bitmap_s.b_fattr4_type #define bm_fattr4_size bitmap_s.b_fattr4_size #define bm_fattr4_fsid bitmap_s.b_fattr4_fsid #define bm_fattr4_fileid bitmap_s.b_fattr4_fileid #define bm_fattr4_filehandle bitmap_s.b_fattr4_filehandle typedef union attr4_bitmap2_u { struct { unsigned int #ifdef _BIT_FIELDS_HTOL b_pad4: 10, b_fattr4_time_modify: 1, b_fattr4_time_metadata: 1, b_pad3: 4, b_fattr4_time_access: 1, b_pad2: 13, b_fattr4_mode: 1, b_pad1: 1; #endif #ifdef _BIT_FIELDS_LTOH b_pad1: 1, b_fattr4_mode: 1, b_pad2: 13, b_fattr4_time_access: 1, b_pad3: 4, b_fattr4_time_metadata: 1, b_fattr4_time_modify: 1, b_pad4: 10; #endif } bitmap_s; uint_t word; } attr4_bitmap2_t; #define bm_fattr4_mode bitmap_s.b_fattr4_mode #define bm_fattr4_time_access bitmap_s.b_fattr4_time_access #define bm_fattr4_time_metadata bitmap_s.b_fattr4_time_metadata #define bm_fattr4_time_modify bitmap_s.b_fattr4_time_modify typedef struct b_bitmap4 { uint_t b_bitmap_len; uint_t b_bitmap_val[NFS4_MAX_BITWORDS]; } b_bitmap4_t; /* * Define a usable set of v4 atttributes for inetboot. */ typedef struct b_fattr4_s { b_bitmap4_t b_supported_attrs; nfs_ftype4 b_fattr4_type; uint64_t b_fattr4_size; fsid4 b_fattr4_fsid; struct nfs_bfh4 b_fattr4_filehandle; uint64_t b_fattr4_fileid; mode4 b_fattr4_mode; nfstime4 b_fattr4_time_access; nfstime4 b_fattr4_time_metadata; nfstime4 b_fattr4_time_modify; } b_fattr4_t; /* * common to putfh and putfhroot. */ typedef struct putfh4arg_s { uint_t pf_opnum; /* can either be putfh or putrootfh */ struct nfs_bfh4 pf_filehandle; /* only used by putfh */ } putfh4arg_t; /* * Use this struct to construct our OTW compound procedures. Layout makes for * easy XDR'ing. Include putfh. */ typedef union compound_u { struct { utf8string tag; uint_t minorversion; /* 0 */ uint_t argarray_len; /* 1 + n for putfh */ bool_t isputrootfh; /* flag */ putfh4arg_t opputfh; /* putfh args */ } compound_ua_s; struct { nfsstat4 status; /* status of last op */ utf8string tag; uint_t resarray_len; /* 1 + n for putfh */ uint_t opputfh; /* putfh opnum */ nfsstat4 putfh_status; /* putfh status */ } compound_ur_s; } b_compound_t; /* * Define some macros for easy access into the compound structrue */ #define ca_tag compound_ua_s.tag #define ca_minorversion compound_ua_s.minorversion #define ca_argarray_len compound_ua_s.argarray_len #define ca_isputrootfh compound_ua_s.isputrootfh #define ca_opputfh compound_ua_s.opputfh #define cr_status compound_ur_s.status #define cr_tag compound_ur_s.tag #define cr_resarray_len compound_ur_s.resarray_len #define cr_opputfh compound_ur_s.opputfh #define cr_putfh_status compound_ur_s.putfh_status /* * Define simple compound structs that include op specific data */ typedef struct getattrres_cmn { uint_t gc_opgetattr; /* getattr opnum */ nfsstat4 gc_attr_status; /* getattr result */ b_bitmap4_t gc_retattr; /* getattr result */ uint_t gc_attrlist_len; /* getattr result */ b_fattr4_t gc_attrs; /* getattr result */ } getattrres_cmn_t; /* * getattr: putfh/getattr */ typedef struct getattr4arg_s { b_compound_t ga_arg; /* compound + putfh */ uint_t ga_opgetattr; /* getattr opnum */ b_bitmap4_t ga_attr_req; /* getattr arg */ } getattr4arg_t; typedef struct getattr4res_s { b_compound_t gr_res; /* compound + putfh */ getattrres_cmn_t gr_cmn; } getattr4res_t; #define gr_opgetattr gr_cmn.gc_opgetattr #define gr_attr_status gr_cmn.gc_attr_status #define gr_retattr gr_cmn.gc_retattr #define gr_attrs gr_cmn.gc_attrs /* * lookup: putfh/lookup/getattr */ typedef struct lookup4arg_s { b_compound_t la_arg; /* compound + putfh */ uint_t la_oplookup; /* lookup opnum */ component4 la_pathname; /* lookup arg */ uint_t la_opgetattr; /* getattr opnum */ b_bitmap4_t la_attr_req; /* getattr arg */ } lookup4arg_t; typedef struct lookup4res_s { b_compound_t lr_res; /* compound + putfh */ uint_t lr_oplookup; /* lookup opnum */ nfsstat4 lr_lookup_status; /* lookup result */ getattrres_cmn_t lr_gcmn; /* getattr result */ } lookup4res_t; #define lr_opgetattr lr_gcmn.gc_opgetattr #define lr_attr_status lr_gcmn.gc_attr_status #define lr_retattr lr_gcmn.gc_retattr #define lr_attrs lr_gcmn.gc_attrs /* * lookupp: putfh/lookupp/getattr * * For results: use the lookup4res_t */ typedef struct lookupp4arg_s { b_compound_t la_arg; /* compound + putfh */ uint_t la_oplookupp; /* lookupp opnum */ uint_t la_opgetattr; /* lookupp arg */ b_bitmap4_t la_attr_req; /* lookupp arg */ } lookupp4arg_t; /* * read: putfh/read */ typedef struct read4arg_s { b_compound_t r_arg; /* compound + putfh */ uint_t r_opread; /* read opnum */ stateid4 r_stateid; /* read arg */ offset4 r_offset; /* read arg */ count4 r_count; /* read arg */ } read4arg_t; typedef struct read4res_s { b_compound_t r_res; /* compound + putfh */ uint_t r_opread; /* read opnum */ nfsstat4 r_status; /* read result */ bool_t r_eof; /* read result */ uint_t r_data_len; /* read result */ char *r_data_val; /* read result */ } read4res_t; typedef struct b_entry4_s { nfs_cookie4 b_cookie; utf8string b_name; uint64_t b_fileid; struct b_entry4_s *b_nextentry; } b_entry4_t; /* * readdir: putfh/readdir/getattr */ typedef struct readdir4arg_s { b_compound_t rd_arg; /* compoud + putfh */ uint_t rd_opreaddir; /* readdir opnum */ nfs_cookie4 rd_cookie; /* readdir arg */ verifier4 rd_cookieverf; /* readdir arg */ count4 rd_dircount; /* readdir arg */ count4 rd_maxcount; /* readdir arg */ b_bitmap4_t rd_attr_req; /* readdir arg */ } readdir4arg_t; typedef struct readdir4res_s { b_compound_t rd_res; /* compound + putfh */ uint_t rd_opreaddir; /* readdir opnum */ nfsstat4 rd_status; /* readdir result */ verifier4 rd_cookieverf; /* readdir result */ b_entry4_t *rd_entries; /* readdir result */ bool_t rd_eof; /* readdir result */ } readdir4res_t; /* * readlink: putfh/readlink */ typedef struct readlink4arg_s { b_compound_t rl_arg; /* compound + putfh */ uint_t rl_opreadlink; /* readlink opnum */ } readlink4arg_t; typedef struct readlink4res_s { b_compound_t rl_res; /* compound + putfh */ uint_t rl_opreadlink; /* readlink opnum */ nfsstat4 rl_status; /* readlink result */ utf8string rl_link; /* readlink result */ } readlink4res_t; /* * Generic NFS functions */ extern int boot_nfs_mountroot(char *); extern int boot_nfs_unmountroot(void); extern int lookup(char *pathname, struct nfs_file *, bool_t); extern bool_t whoami(void); extern bool_t getfile(char *, char *, struct in_addr *, char *); /* * NFS Version 2 specific functions */ extern void nfs_error(enum nfsstat); extern ssize_t nfsread(struct nfs_file *, char *, size_t); extern int nfsgetattr(struct nfs_file *, struct vattr *); extern int nfsgetdents(struct nfs_file *, struct dirent *, unsigned); extern struct nfs_file *nfslookup(struct nfs_file *, char *, int *); extern int nfsgetsymlink(struct nfs_file *cfile, char **path); /* * NFS Version 3 specific functions */ extern void nfs3_error(enum nfsstat3); extern ssize_t nfs3read(struct nfs_file *, char *, size_t); extern int nfs3getattr(struct nfs_file *, struct vattr *); extern int nfs3getdents(struct nfs_file *, struct dirent *, unsigned); extern struct nfs_file *nfs3lookup(struct nfs_file *, char *, int *); extern int nfs3getsymlink(struct nfs_file *, char **); /* * NFS Version 4 specific functions */ extern void nfs4_error(enum nfsstat4); extern ssize_t nfs4read(struct nfs_file *, char *, size_t); extern int nfs4getattr(struct nfs_file *, struct vattr *); extern int nfs4_getdents(struct nfs_file *, struct dirent *, unsigned); extern struct nfs_file *nfs4lookup(struct nfs_file *, char *, int *); extern struct nfs_file *nfs4lookupp(struct nfs_file *, int *, uint64_t *); extern int nfs4getsymlink(struct nfs_file *, char **); extern void compound_init(b_compound_t *, utf8string *, uint_t, uint_t, struct nfs_bfh4 *); /* * NFSv4 xdr ops */ extern bool_t xdr_getattr4_args(XDR *, getattr4arg_t *); extern bool_t xdr_getattr4_res(XDR *, getattr4res_t *); extern bool_t xdr_lookup4_args(XDR *, lookup4arg_t *); extern bool_t xdr_lookup4_res(XDR *, lookup4res_t *); extern bool_t xdr_lookupp4_args(XDR *, lookupp4arg_t *); extern bool_t xdr_read4_args(XDR *, read4arg_t *); extern bool_t xdr_read4_res(XDR *, read4res_t *); extern bool_t xdr_readdir4_args(XDR *, readdir4arg_t *); extern bool_t xdr_readdir4_res(XDR *, readdir4res_t *); extern bool_t xdr_readlink4_args(XDR *, readlink4arg_t *); extern bool_t xdr_readlink4_res(XDR *, readlink4res_t *); #ifdef __cplusplus } #endif #endif /* _NFS_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include /* * XDR routines for NFS ops. */ static bool_t xdr_b_nfsstat(XDR *xdrs, nfsstat *objp) { return (xdr_enum(xdrs, (enum_t *)objp)); } static bool_t xdr_b_ftype(XDR *xdrs, ftype *objp) { return (xdr_enum(xdrs, (enum_t *)objp)); } bool_t xdr_nfs_fh(XDR *xdrs, nfs_fh *objp) { return (xdr_opaque(xdrs, objp->data, NFS_FHSIZE)); } static bool_t xdr_b_nfstime(XDR *xdrs, nfstime *objp) { if (!xdr_u_int(xdrs, &objp->seconds)) { return (FALSE); } return (xdr_u_int(xdrs, &objp->useconds)); } static bool_t xdr_b_fattr(XDR *xdrs, fattr *objp) { if (!xdr_b_ftype(xdrs, &objp->type)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->mode)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->nlink)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->uid)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->gid)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->size)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->blocksize)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->rdev)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->blocks)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->fsid)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->fileid)) { return (FALSE); } if (!xdr_b_nfstime(xdrs, &objp->atime)) { return (FALSE); } if (!xdr_b_nfstime(xdrs, &objp->mtime)) { return (FALSE); } return (xdr_b_nfstime(xdrs, &objp->ctime)); } static bool_t xdr_b_filename(XDR *xdrs, filename *objp) { return (xdr_string(xdrs, objp, NFS_MAXNAMLEN)); } static bool_t xdr_b_nfspath(XDR *xdrs, nfspath *objp) { return (xdr_string(xdrs, objp, NFS_MAXPATHLEN)); } bool_t xdr_attrstat(XDR *xdrs, attrstat *objp) { if (!xdr_b_nfsstat(xdrs, &objp->status)) { return (FALSE); } if (objp->status == NFS_OK) { return (xdr_b_fattr(xdrs, &objp->attrstat_u.attributes)); } return (TRUE); } bool_t xdr_diropargs(XDR *xdrs, diropargs *objp) { if (!xdr_nfs_fh(xdrs, &objp->dir)) { return (FALSE); } return (xdr_b_filename(xdrs, &objp->name)); } static bool_t xdr_b_diropokres(XDR *xdrs, diropokres *objp) { if (!xdr_nfs_fh(xdrs, &objp->file)) { return (FALSE); } return (xdr_b_fattr(xdrs, &objp->attributes)); } bool_t xdr_diropres(XDR *xdrs, diropres *objp) { if (!xdr_b_nfsstat(xdrs, &objp->status)) { return (FALSE); } if (objp->status == NFS_OK) { return (xdr_b_diropokres(xdrs, &objp->diropres_u.diropres)); } return (TRUE); } bool_t xdr_readlinkres(XDR *xdrs, readlinkres *objp) { if (!xdr_b_nfsstat(xdrs, &objp->status)) { return (FALSE); } if (objp->status == NFS_OK) { return (xdr_b_nfspath(xdrs, &objp->readlinkres_u.data)); } return (TRUE); } bool_t xdr_readargs(XDR *xdrs, readargs *objp) { if (!xdr_nfs_fh(xdrs, &objp->file)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->offset)) { return (FALSE); } if (!xdr_u_int(xdrs, &objp->count)) { return (FALSE); } return (xdr_u_int(xdrs, &objp->totalcount)); } static bool_t xdr_b_readokres(XDR *xdrs, readokres *objp) { if (!xdr_b_fattr(xdrs, &objp->attributes)) { return (FALSE); } return (xdr_bytes(xdrs, (char **)&objp->data.data_val, (uint_t *)&objp->data.data_len, NFS_MAXDATA)); } bool_t xdr_readres(XDR *xdrs, readres *objp) { if (!xdr_b_nfsstat(xdrs, &objp->status)) { return (FALSE); } if (objp->status == NFS_OK) { return (xdr_b_readokres(xdrs, &objp->readres_u.reply)); } return (TRUE); } static bool_t xdr_b_nfscookie(XDR *xdrs, nfscookie objp) { return (xdr_opaque(xdrs, objp, NFS_COOKIESIZE)); } bool_t xdr_readdirargs(XDR *xdrs, readdirargs *objp) { if (!xdr_nfs_fh(xdrs, &objp->dir)) { return (FALSE); } if (!xdr_b_nfscookie(xdrs, objp->cookie)) { return (FALSE); } return (xdr_u_int(xdrs, &objp->count)); } static bool_t xdr_b_entry(XDR *xdrs, entry *objp) { if (!xdr_u_int(xdrs, &objp->fileid)) { return (FALSE); } if (!xdr_b_filename(xdrs, &objp->name)) { return (FALSE); } if (!xdr_b_nfscookie(xdrs, objp->cookie)) { return (FALSE); } return (xdr_pointer(xdrs, (char **)&objp->nextentry, sizeof (entry), (xdrproc_t)xdr_b_entry)); } static bool_t xdr_b_dirlist(XDR *xdrs, dirlist *objp) { if (!xdr_pointer(xdrs, (char **)&objp->entries, sizeof (entry), (xdrproc_t)xdr_b_entry)) { return (FALSE); } return (xdr_bool(xdrs, &objp->eof)); } bool_t xdr_readdirres(XDR *xdrs, readdirres *objp) { if (!xdr_b_nfsstat(xdrs, &objp->status)) { return (FALSE); } if (objp->status == NFS_OK) { return (xdr_b_dirlist(xdrs, &objp->readdirres_u.reply)); } return (TRUE); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Simple nfs ops - open, close, read, and lseek. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include "clnt.h" #include #include #include #include #include #include "nfs_inet.h" #include #include #include #include #include #include #include "brpc.h" #include #include "socket_inet.h" #include "mac.h" #include ushort_t vttoif_tab[] = { 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK, S_IFIFO, S_IFDOOR, 0, S_IFSOCK, 0 }; static int file_desc = 1; static struct nfs_files { struct nfs_file file; int desc; struct nfs_files *next; } nfs_files[1] = { {0, 0, 0}, }; #define dprintf if (boothowto & RB_DEBUG) printf static int boot_nfs_open(char *filename, int flags); static int boot_nfs_close(int fd); static ssize_t boot_nfs_read(int fd, caddr_t buf, size_t size); static off_t boot_nfs_lseek(int, off_t, int); static int boot_nfs_fstat(int fd, struct bootstat *stp); static void boot_nfs_closeall(int flag); static int boot_nfs_getdents(int fd, struct dirent *dep, unsigned size); struct boot_fs_ops boot_nfs_ops = { "nfs", boot_nfs_mountroot, boot_nfs_unmountroot, boot_nfs_open, boot_nfs_close, boot_nfs_read, boot_nfs_lseek, boot_nfs_fstat, boot_nfs_closeall, boot_nfs_getdents }; /* * bootops.c calls a closeall() function to close all open files. Since * we only permit one open file at a time (not counting the device), this * is simple to implement. */ /*ARGSUSED*/ static void boot_nfs_closeall(int flag) { struct nfs_files *filep; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_closeall(%x)\n", flag); #endif if (nfs_files->file.version == 0 && nfs_files->desc == 0 && nfs_files->next == NULL) return; /* delete any dynamically allocated entries */ while ((filep = nfs_files->next) != NULL) { nfs_files->next = filep->next; bkmem_free((caddr_t)filep, sizeof (struct nfs_files)); } /* clear the first, static file */ bzero((caddr_t)nfs_files, sizeof (struct nfs_files)); /* Close device */ release_cache(mac_get_dev()); mac_fini(); } /* * Get a file pointer given a file descriptor. Return 0 on error */ static struct nfs_files * get_filep(int fd) { struct nfs_files *filep; for (filep = nfs_files; filep; filep = filep->next) { if (fd == filep->desc) return (filep); } return (NULL); } /* * Unmount the root fs -- not supported for this fstype. */ int boot_nfs_unmountroot(void) { return (-1); } /* * open a file for reading. Note: writing is NOT supported. */ static int boot_nfs_open(char *path, int flags) { struct nfs_files *filep, *newfilep; int got_filep; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_open(%s, %x)\n", path, flags); #endif /* file can only be opened readonly. */ if (flags & ~O_RDONLY) { dprintf("boot_nfs_open: files can only be opened O_RDONLY.\n"); return (-1); } if (path == NULL || *path == '\0') { dprintf("boot_nfs_open: NULL or EMPTY pathname argument.\n"); return (-1); } /* Try and find a vacant file pointer */ filep = nfs_files; got_filep = FALSE; do { if (filep->desc == 0) { filep->desc = file_desc++; got_filep = TRUE; break; /* We've got a file pointer */ } /* Get next entry if not at end of list */ if (filep->next) filep = filep->next; } while (filep->next); /* If a a vacant file pointer cannot be found, make one */ if (!got_filep) { if ((newfilep = (struct nfs_files *) bkmem_zalloc(sizeof (struct nfs_files))) == 0) { dprintf("open: Cannot allocate file pointer\n"); return (-1); } filep->next = newfilep; filep = newfilep; filep->desc = file_desc++; } if (lookup(path, &filep->file, FALSE) != 0) { #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_open(): Cannot open '%s'.\n", path); #endif /* zero file pointer */ bzero((caddr_t)filep, sizeof (struct nfs_file)); filep->desc = 0; return (-1); } bzero(&filep->file.cookie, sizeof (filep->file.cookie)); #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_open(): '%s' successful, fd = 0x%x\n", path, filep->desc); #endif return (filep->desc); } /* * close a previously opened file. */ static int boot_nfs_close(int fd) { struct nfs_files *filep; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_close(%d)\n", fd); #endif if ((filep = get_filep(fd)) == 0) return (0); /* * zero file pointer */ bzero((caddr_t)&filep->file, sizeof (struct nfs_file)); /* * "close" the fd. */ filep->desc = 0; return (0); } /* * read from a file. */ static ssize_t boot_nfs_read(int fd, char *buf, size_t size) { struct nfs_files *filep; int count = 0; if (fd == 0) { dprintf("boot_nfs_read: Bad file number.\n"); return (-1); } if (buf == NULL) { dprintf("boot_nfs_read: Bad address.\n"); return (-1); } #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_read(%d, %x, 0x%x)\n", fd, buf, size); #endif /* initialize for read */ if ((filep = get_filep(fd)) == 0) return (-1); switch (filep->file.version) { case NFS_VERSION: count = nfsread(&filep->file, buf, size); break; case NFS_V3: count = nfs3read(&filep->file, buf, size); break; case NFS_V4: count = nfs4read(&filep->file, buf, size); break; default: printf("boot_nfs_read: NFS Version %d not supported\n", filep->file.version); count = -1; break; } #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_read(): 0x%x bytes.\n", count); #endif return (count); } /* * lseek - move read file pointer. */ static off_t boot_nfs_lseek(int fd, off_t offset, int whence) { struct nfs_files *filep; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_lseek(%d, 0x%x, %d)\n", fd, offset, whence); #endif if (fd == 0) { dprintf("boot_nfs_lseek: Bad file number.\n"); return (-1); } if ((filep = get_filep(fd)) == 0) return (-1); switch (whence) { case SEEK_SET: /* * file ptr is set to offset from beginning of file */ filep->file.offset = offset; break; case SEEK_CUR: /* * file ptr is set to offset from current position */ filep->file.offset += offset; break; case SEEK_END: /* * file ptr is set to current size of file plus offset. * But since we only support reading, this is illegal. */ default: /* * invalid offset origin */ dprintf("boot_nfs_lseek: invalid whence value.\n"); return (-1); } #ifdef notyet return (filep->file.offset); #else /* * BROKE - lseek should return the offset seeked to on a * successful seek, not zero - This must be fixed in the * kernel before It can be fixed here. */ return (0); #endif /* notyet */ } /* * This version of fstat supports mode, size, inode #, and times only. * It can be enhanced if more is required, */ static int boot_nfs_fstat(int fd, struct bootstat *stp) { struct vattr va; struct nfs_files *filep; int status; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) { printf("boot_nfs_fstat(%d, 0x%x)\n", fd, stp); } #endif if (fd == 0) { dprintf("boot_nfs_fstat(): Bad file number 0.\n"); return (-1); } if ((filep = get_filep(fd)) == 0) return (-1); bzero((char *)&va, sizeof (va)); va.va_mask = AT_TYPE | AT_SIZE | AT_MODE | AT_NODEID | AT_ATIME | AT_CTIME | AT_MTIME; switch (filep->file.version) { case NFS_VERSION: status = nfsgetattr(&filep->file, &va); break; case NFS_V3: status = nfs3getattr(&filep->file, &va); break; case NFS_V4: status = nfs4getattr(&filep->file, &va); break; default: printf("boot_nfs_fstat: NFS Version %d not supported\n", filep->file.version); status = -1; break; } if (status != 0) return (-1); if (va.va_size > (u_offset_t)MAXOFF_T) { dprintf("boot_nfs_fstat(): File too large.\n"); return (-1); } stp->st_size = (off_t)va.va_size; stp->st_mode = VTTOIF(va.va_type) | va.va_mode; stp->st_atim.tv_sec = va.va_atime.tv_sec; stp->st_atim.tv_nsec = va.va_atime.tv_nsec; stp->st_ctim.tv_sec = va.va_ctime.tv_sec; stp->st_ctim.tv_nsec = va.va_ctime.tv_nsec; stp->st_mtim.tv_sec = va.va_mtime.tv_sec; stp->st_mtim.tv_nsec = va.va_mtime.tv_nsec; stp->st_ino = (ino_t)va.va_nodeid; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_fstat(): done.\n"); #endif return (0); } static int boot_nfs_getdents(int fd, struct dirent *dep, unsigned size) { struct nfs_files *filep; int status; #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) { printf("boot_nfs_getdents(%d, 0x%x, 0x%x)\n", fd, dep, size); } #endif if (fd == 0) { dprintf("boot_nfs_getdents(): Bad file number 0.\n"); return (-1); } if ((filep = get_filep(fd)) == 0) return (-1); switch (filep->file.version) { case NFS_VERSION: status = nfsgetdents(&filep->file, dep, size); break; case NFS_V3: status = nfs3getdents(&filep->file, dep, size); break; default: printf("boot_nfs_getdents: NFS Version %d not supported\n", filep->file.version); status = -1; } #ifdef NFS_OPS_DEBUG if ((boothowto & DBFLAGS) == DBFLAGS) printf("boot_nfs_getdents(): done.\n"); #endif return (status); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ #include #include #include #include #include #include #include /* * Pathname utilities. * * In translating file names we copy each argument file * name into a pathname structure where we operate on it. * Each pathname structure can hold MAXPATHLEN characters * including a terminating null, and operations here support * fetching strings from user space, getting the next character from * a pathname, combining two pathnames (used in symbolic * link processing), and peeling off the first component * of a pathname. */ #define dprintf if (boothowto & RB_DEBUG) printf /* * Setup contents of pathname structure. Warn about missing allocations. * Structure itself is typically automatic * variable in calling routine for convenience. * * NOTE: if buf is NULL, failure occurs. */ int stpn_alloc(struct st_pathname *pnp) { if (pnp->pn_buf == NULL) return (-1); pnp->pn_path = (char *)pnp->pn_buf; pnp->pn_pathlen = 0; return (0); } /* * Pull a pathname from user user or kernel space */ int stpn_get(char *str, struct st_pathname *pnp) { if (stpn_alloc(pnp) != 0) return (-1); bcopy(str, pnp->pn_path, strlen(str)); pnp->pn_pathlen = strlen(str); /* don't count null byte */ return (0); } /* * Set pathname to argument string. */ int stpn_set(struct st_pathname *pnp, char *path) { pnp->pn_path = pnp->pn_buf; pnp->pn_pathlen = strlen(pnp->pn_path); /* don't count null byte */ bcopy(pnp->pn_path, path, pnp->pn_pathlen); return (0); } /* * Combine two argument pathnames by putting * second argument before first in first's buffer, * and freeing second argument. * This isn't very general: it is designed specifically * for symbolic link processing. */ int stpn_combine(struct st_pathname *pnp, struct st_pathname *sympnp) { if (pnp->pn_pathlen + sympnp->pn_pathlen >= MAXPATHLEN) return (ENAMETOOLONG); bcopy(pnp->pn_path, pnp->pn_buf + sympnp->pn_pathlen, (uint_t)pnp->pn_pathlen); bcopy(sympnp->pn_path, pnp->pn_buf, (uint_t)sympnp->pn_pathlen); pnp->pn_pathlen += sympnp->pn_pathlen; pnp->pn_buf[pnp->pn_pathlen] = '\0'; pnp->pn_path = pnp->pn_buf; return (0); } /* * Get next component off a pathname and leave in * buffer comoponent which should have room for * NFS_MAXNAMLEN (1024) bytes and a null terminator character. * If PEEK is set in flags, just peek at the component, * i.e., don't strip it out of pnp. */ int stpn_getcomponent(struct st_pathname *pnp, char *component, int flags) { char *cp; int l; int n; cp = pnp->pn_path; l = pnp->pn_pathlen; n = 1024; while ((l > 0) && (*cp != '/')) { if (--n < 0) return (ENAMETOOLONG); *component++ = *cp++; --l; } if (!(flags & PN_PEEK)) { pnp->pn_path = cp; pnp->pn_pathlen = l; } *component = 0; return (0); } /* * skip over consecutive slashes in the pathname */ void stpn_skipslash(struct st_pathname *pnp) { while ((pnp->pn_pathlen != 0) && (*pnp->pn_path == '/')) { pnp->pn_path++; pnp->pn_pathlen--; } } /* * free pathname resources. This is a nop - the user of these * routines is responsible for allocating and freeing their memory. */ /*ARGSUSED*/ void stpn_free(struct st_pathname *pnp) { /* nop */ dprintf("pn_free(): you shouldn't be calling pn_free()!\n"); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * This file contains the routines that maintain a linked list of known * program to udp port mappings. There are three static members initialized * by default, one for the portmapper itself (of course), one for rpcbind, * and one for nfs. If a program number is not in the list, then routines * in this file contact the portmapper on the server, and dynamically add * new members to this list. * * This file also contains bpmap_rmtcall() - which lets one get the port * number AND run the rpc call in one step. Only the server that successfully * completes the rpc call will return a result. * * NOTE: Because we will end up caching the port entries we need * before the kernel begins running, we can use dynamic allocation here. * boot_memfree() calls bpmap_memfree() to free up any dynamically * allocated entries when the boot program has finished its job. */ #include #include #include #include #include #include #include #include #include #include #include #include "clnt.h" #include #include #include #include "brpc.h" #include "pmap.h" #include "nfs_inet.h" #include #include #include #include "socket_inet.h" #include #include /* portmap structure */ #define PMAP_STATIC (3) /* last statically allocated list entry */ struct pmaplist pre_init[PMAP_STATIC + 1] = { { {PMAPPROG, PMAPVERS, IPPROTO_UDP, PMAPPORT}, &pre_init[1] }, /* SVR4 rpcbind listens to old portmapper port */ { {RPCBPROG, RPCBVERS, IPPROTO_UDP, PMAPPORT}, &pre_init[2] }, { {NFS_PROGRAM, NFS_VERSION, IPPROTO_UDP, NFS_PORT}, &pre_init[3] }, { {NFS_PROGRAM, NFS_V3, IPPROTO_UDP, NFS_PORT}, NULL } }; struct pmaplist *map_head = &pre_init[0]; struct pmaplist *map_tail = &pre_init[PMAP_STATIC]; #define dprintf if (boothowto & RB_DEBUG) printf /* * bpmap_addport: adds a new entry on to the end of the pmap cache. * Items are kept in host order. */ static void bpmap_addport(rpcprog_t prog, rpcvers_t vers, rpcport_t port) { struct pmaplist *newp; /* allocate new pmaplist */ newp = (struct pmaplist *)bkmem_alloc(sizeof (struct pmaplist)); if (newp == NULL) return; /* not fatal here, we'll just throw out the entry */ newp->pml_map.pm_prog = prog; newp->pml_map.pm_vers = vers; newp->pml_map.pm_prot = (rpcprot_t)IPPROTO_UDP; newp->pml_map.pm_port = port; map_tail->pml_next = newp; newp->pml_next = NULL; map_tail = newp; } /* * bpmap_delport: deletes an existing entry from the list. Caution - don't * call this function to delete statically allocated entries. Why would * you want to, anyway? Only IPPROTO_UDP is supported, of course. */ static void bpmap_delport(rpcprog_t prog, rpcvers_t vers) { struct pmaplist *tmp, *prev; prev = map_head; for (tmp = map_head; tmp != NULL; tmp = tmp->pml_next) { if ((tmp->pml_map.pm_prog == prog) && (tmp->pml_map.pm_vers == vers)) { if (tmp == map_head) map_head = tmp->pml_next; /* new head */ else if (tmp == map_tail) { map_tail = prev; /* new tail */ map_tail->pml_next = NULL; } else { /* internal delete */ prev->pml_next = tmp->pml_next; } #ifdef DEBUG printf("bpmap_delport: prog: %x, vers: %x\n", prog, vers); #endif /* DEBUG */ bkmem_free((caddr_t)tmp, sizeof (struct pmaplist)); break; } else prev = tmp; } } /* * Modified strtol(3). */ static int strtoi(char *str, char **ptr) { int c, val; for (val = 0, c = *str++; c >= '0' && c <= '9'; c = *str++) { val *= 10; val += c - '0'; } *ptr = str; return (val); } /* * (from dlboot_inet.c) (kernel) * Convert a port number from a sockaddr_in expressed * in universal address format. */ static int uaddr2port(char *addr) { int p1, p2; char *next; /* * A struct sockaddr_in expressed in universal address * format looks like: * * "IP.IP.IP.IP.PORT[top byte].PORT[bot. byte]" * * Where each component expresses as a charactor, * the corresponding part of the IP address * and port number. * Thus 127.0.0.1, port 2345 looks like: * * 49 50 55 46 48 46 48 46 49 46 57 46 52 49 * 1 2 7 . 0 . 0 . 1 . 9 . 4 1 * * 2345 = 929base16 = 9.32+9 = 9.41 */ (void) strtoi(addr, &next); (void) strtoi(next, &next); (void) strtoi(next, &next); (void) strtoi(next, &next); p1 = strtoi(next, &next); p2 = strtoi(next, &next); return ((p1 << 8) + p2); } /* * Xdr routines used for calling portmapper/rpcbind. */ bool_t xdr_pmap(XDR *xdrs, struct pmap *regs) { if (xdr_rpcprog(xdrs, ®s->pm_prog) && xdr_rpcvers(xdrs, ®s->pm_vers) && xdr_rpcprot(xdrs, ®s->pm_prot)) return (xdr_rpcprot(xdrs, ®s->pm_port)); return (FALSE); } bool_t xdr_rpcb(XDR *xdrs, RPCB *objp) { if (!xdr_rpcprog(xdrs, &objp->r_prog)) return (FALSE); if (!xdr_rpcvers(xdrs, &objp->r_vers)) return (FALSE); if (!xdr_string(xdrs, &objp->r_netid, ~0)) return (FALSE); if (!xdr_string(xdrs, &objp->r_addr, ~0)) return (FALSE); if (!xdr_string(xdrs, &objp->r_owner, ~0)) return (FALSE); return (TRUE); } /* * XDR remote call arguments * written for XDR_ENCODE direction only */ bool_t xdr_rmtcall_args(XDR *xdrs, struct rmtcallargs *cap) { uint_t lenposition, argposition, position; if (xdr_rpcprog(xdrs, &(cap->prog)) && xdr_rpcvers(xdrs, &(cap->vers)) && xdr_rpcproc(xdrs, &(cap->proc))) { lenposition = XDR_GETPOS(xdrs); if (!xdr_u_int(xdrs, &(cap->arglen))) return (FALSE); argposition = XDR_GETPOS(xdrs); if (!(*(cap->xdr_args))(xdrs, cap->args_ptr)) return (FALSE); position = XDR_GETPOS(xdrs); cap->arglen = position - argposition; (void) XDR_SETPOS(xdrs, lenposition); if (!xdr_u_int(xdrs, &(cap->arglen))) return (FALSE); (void) XDR_SETPOS(xdrs, position); return (TRUE); } return (FALSE); } /* * XDR remote call results * written for XDR_DECODE direction only */ bool_t xdr_rmtcallres(XDR *xdrs, struct rmtcallres *crp) { caddr_t port_ptr; port_ptr = (caddr_t)crp->port_ptr; if (xdr_reference(xdrs, &port_ptr, sizeof (uint_t), xdr_u_int) && xdr_u_int(xdrs, &crp->resultslen)) { crp->port_ptr = (rpcport_t *)port_ptr; return ((*(crp->xdr_results))(xdrs, crp->results_ptr)); } return (FALSE); } /* * XDR remote call arguments * written for XDR_ENCODE direction only */ bool_t xdr_rpcb_rmtcallargs(XDR *xdrs, struct rpcb_rmtcallargs *objp) { uint_t lenposition, argposition, position; if (!xdr_rpcprog(xdrs, &objp->prog)) return (FALSE); if (!xdr_rpcvers(xdrs, &objp->vers)) return (FALSE); if (!xdr_rpcproc(xdrs, &objp->proc)) return (FALSE); /* * All the jugglery for just getting the size of the arguments */ lenposition = XDR_GETPOS(xdrs); if (!xdr_u_int(xdrs, &(objp->arglen))) return (FALSE); argposition = XDR_GETPOS(xdrs); if (!(*(objp->xdr_args))(xdrs, objp->args_ptr)) return (FALSE); position = XDR_GETPOS(xdrs); objp->arglen = position - argposition; (void) XDR_SETPOS(xdrs, lenposition); if (!xdr_u_int(xdrs, &(objp->arglen))) return (FALSE); (void) XDR_SETPOS(xdrs, position); return (TRUE); } /* * XDR remote call results * written for XDR_DECODE direction only */ bool_t xdr_rpcb_rmtcallres(XDR *xdrs, struct rpcb_rmtcallres *objp) { if (!xdr_string(xdrs, &objp->addr_ptr, ~0)) return (FALSE); if (!xdr_u_int(xdrs, &objp->resultslen)) return (FALSE); return ((*(objp->xdr_results))(xdrs, objp->results_ptr)); } /* * bpmap_rmtcall: does PMAPPROC_CALLIT broadcasts w/ rpc_call requests. * Lets one do a PMAPGETPORT/RPC PROC call in one easy step. sockaddr_in args * are taken as network order. * * Code adapted from bpmap_rmtcall() in dlboot_inet.c (kernel) */ /*ARGSUSED*/ enum clnt_stat bpmap_rmtcall( rpcprog_t prog, /* rpc program number to call. */ rpcvers_t vers, /* rpc program version */ rpcproc_t proc, /* rpc procedure to call */ xdrproc_t in_xdr, /* routine to serialize arguments */ caddr_t args, /* arg vector for remote call */ xdrproc_t out_xdr, /* routine to deserialize results */ caddr_t ret, /* addr of buf to place results in */ int rexmit, /* retransmission interval (secs) */ int wait, /* how long (secs) to wait for a resp */ struct sockaddr_in *to, /* destination */ struct sockaddr_in *from, /* filled in w/ responder's port/addr */ uint_t auth) /* type of authentication wanted. */ { enum clnt_stat status; /* rpc_call status */ rpcport_t port = 0; /* returned port # */ struct rmtcallargs pmap_a; /* args for pmap call */ struct rmtcallres pmap_r; /* results from pmap call */ struct rpcb_rmtcallargs rpcb_a; /* args for rpcb call */ struct rpcb_rmtcallres rpcb_r; /* results from rpcb call */ char ua[UA_SIZE]; /* universal addr buffer */ /* initialize pmap */ pmap_a.prog = prog; pmap_a.vers = vers; pmap_a.proc = proc; pmap_a.args_ptr = args; pmap_a.xdr_args = in_xdr; pmap_r.port_ptr = &port; pmap_r.results_ptr = ret; pmap_r.xdr_results = out_xdr; status = brpc_call((rpcprog_t)PMAPPROG, (rpcvers_t)PMAPVERS, (rpcproc_t)PMAPPROC_CALLIT, xdr_rmtcall_args, (caddr_t)&pmap_a, xdr_rmtcallres, (caddr_t)&pmap_r, rexmit, wait, to, from, AUTH_NONE); if (status != RPC_PROGUNAVAIL) { if (status == RPC_SUCCESS) { /* delete old port mapping, if it exists */ bpmap_delport(prog, vers); /* save the new port mapping */ bpmap_addport(prog, vers, port); } return (status); } /* * PMAP is unavailable. Maybe there's a SVR4 machine, with rpcbind. */ bzero(ua, sizeof (ua)); /* initialize rpcb */ rpcb_a.prog = prog; rpcb_a.vers = vers; rpcb_a.proc = proc; rpcb_a.args_ptr = args; rpcb_a.xdr_args = in_xdr; rpcb_r.addr_ptr = ua; rpcb_r.results_ptr = ret; rpcb_r.xdr_results = out_xdr; status = brpc_call((rpcprog_t)RPCBPROG, (rpcvers_t)RPCBVERS, (rpcproc_t)RPCBPROC_CALLIT, xdr_rpcb_rmtcallargs, (caddr_t)&rpcb_a, xdr_rpcb_rmtcallres, (caddr_t)&rpcb_r, rexmit, wait, to, from, AUTH_NONE); if (status == RPC_SUCCESS) { /* delete old port mapping, if it exists */ bpmap_delport(prog, vers); /* save the new port mapping */ port = ntohs(uaddr2port(ua)); bpmap_addport(prog, vers, port); } return (status); } /* * bpmap_getport: Queries current list of cached pmap_list entries, * returns the port number of the entry found. If the port number * is not cached, then getport makes a rpc call first to the portmapper, * and then to rpcbind (SVR4) if the portmapper does not respond. The * returned port is then added to the cache, and the port number is * returned. If both portmapper and rpc bind fail to give us the necessary * port, we return 0 to signal we hit an error, and set rpc_stat to * the appropriate RPC error code. Only IPPROTO_UDP protocol is supported. * * Port and sockaddr_in arguments taken in network order. rpcport_t is returned * in host order. */ rpcport_t bpmap_getport(rpcprog_t prog, rpcvers_t vers, enum clnt_stat *rpc_stat, struct sockaddr_in *to, struct sockaddr_in *from) { struct pmaplist *walk; struct pmap pmap_send; /* portmap */ in_port_t pmap_port; rpcport_t dport; #ifdef DEBUG printf("bpmap_getport: called with: prog: %d, vers: %d\n", prog, vers); #endif /* DEBUG */ for (walk = map_head; walk != 0; walk = walk->pml_next) { if ((walk->pml_map.pm_prog == prog) && (walk->pml_map.pm_vers == vers) && (walk->pml_map.pm_prot == (rpcprot_t)IPPROTO_UDP)) { #ifdef DEBUG printf("bpmap_getport: Found in cache. returning: %d\n", walk->pml_map.pm_port); #endif /* DEBUG */ return (walk->pml_map.pm_port); } } /* * Not in the cache. First try the portmapper (SunOS server?) and * if that fails, try rpcbind (SVR4 server). */ pmap_send.pm_prog = prog; pmap_send.pm_vers = vers; pmap_send.pm_prot = (rpcprot_t)IPPROTO_UDP; pmap_send.pm_port = 0; /* what we're after */ *rpc_stat = brpc_call(PMAPPROG, PMAPVERS, PMAPPROC_GETPORT, xdr_pmap, (caddr_t)&pmap_send, xdr_u_short, (caddr_t)&pmap_port, 0, 0, to, from, AUTH_NONE); if (*rpc_stat == RPC_PROGUNAVAIL) { /* * The portmapper isn't available. Try rpcbind. * Maybe the server is a SVR4 server. */ char *ua; /* universal address */ char ua_buf[UA_SIZE]; /* and its buffer */ RPCB rpcb_send; rpcb_send.r_prog = prog; rpcb_send.r_vers = vers; rpcb_send.r_netid = NULL; rpcb_send.r_addr = NULL; rpcb_send.r_owner = NULL; bzero(ua_buf, UA_SIZE); ua = ua_buf; /* * Again, default # of retries. xdr_wrapstring() * wants a char **. */ *rpc_stat = brpc_call(RPCBPROG, RPCBVERS, RPCBPROC_GETADDR, xdr_rpcb, (caddr_t)&rpcb_send, xdr_wrapstring, (char *)&ua, 0, 0, to, from, AUTH_NONE); if (*rpc_stat == RPC_SUCCESS) { if (ua[0] != '\0') dport = ntohs(uaddr2port(ua)); else return (0); /* Address unknown */ } } else { /* * Why are rpcport_t's uint32_t? port numbers are uint16_t * for ipv4 AND ipv6.... XXXX */ dport = (rpcport_t)pmap_port; } if (*rpc_stat != RPC_SUCCESS) { dprintf("pmap_getport: Failed getting port.\n"); return (0); /* we failed. */ } #ifdef DEBUG printf("bpmap_getport: prog: %d, vers: %d; returning port: %d.\n", prog, vers, dport); #endif /* DEBUG */ bpmap_addport(prog, vers, dport); return (dport); } /* * bpmap_memfree: frees up any dynamically allocated entries. */ void bpmap_memfree(void) { struct pmaplist *current, *tmp; if (map_tail == &pre_init[PMAP_STATIC]) return; /* no dynamic entries */ /* free from head of the list to the tail. */ current = pre_init[PMAP_STATIC].pml_next; while (current != NULL) { tmp = current->pml_next; bkmem_free((caddr_t)current, sizeof (struct pmaplist)); current = tmp; } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _PMAP_H #define _PMAP_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define UA_SIZE (128) /* max space needed for an universal addr */ extern enum clnt_stat bpmap_rmtcall(rpcprog_t, rpcvers_t, rpcproc_t, xdrproc_t, caddr_t, xdrproc_t, caddr_t, int, int, struct sockaddr_in *, struct sockaddr_in *, uint_t); extern rpcport_t bpmap_getport(rpcprog_t, rpcvers_t, enum clnt_stat *, struct sockaddr_in *, struct sockaddr_in *); extern void bpmap_memfree(void); #ifdef __cplusplus } #endif #endif /* _PMAP_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * This file contains a simple implementation of RPC. Standard XDR is * used. */ #include #include #include #include #include #include "socket_inet.h" #include "ipv4.h" #include #include #include #include #include #include #include "clnt.h" #include #include "brpc.h" #include "auth_inet.h" #include "pmap.h" #include #include "nfs_inet.h" #include #include #include #include "mac.h" #include #define dprintf if (boothowto & RB_DEBUG) printf static struct in_addr cached_destination; void rpc_disperr(struct rpc_err *stat) { if (boothowto & RB_DEBUG) { switch (stat->re_status) { case RPC_CANTENCODEARGS: printf("RPC: Can't encode arguments.\n"); break; case RPC_CANTDECODERES: printf("RPC: Can't decode result.\n"); break; case RPC_CANTSEND: printf("RPC: Unable to send (%s).\n", strerror(errno)); break; case RPC_CANTRECV: printf("RPC: Unable to receive (%s).\n", strerror(errno)); break; case RPC_TIMEDOUT: printf("RPC: Timed out.\n"); break; case RPC_VERSMISMATCH: printf("RPC: Incompatible versions of RPC.\n"); break; case RPC_AUTHERROR: printf("RPC: Authentication error:\n"); switch (stat->re_why) { case AUTH_BADCRED: printf("remote: bogus credentials " "(seal broken).\n"); break; case AUTH_REJECTEDCRED: printf("remote: client should begin new " "session.\n"); break; case AUTH_BADVERF: printf("remote: bogus verifier " "(seal broken).\n"); break; case AUTH_REJECTEDVERF: printf("remote: verifier expired or was " "replayed.\n"); break; case AUTH_TOOWEAK: printf("remote: rejected due to security " "reasons.\n"); break; case AUTH_INVALIDRESP: printf("local: bogus response verifier.\n"); break; case AUTH_FAILED: /* FALLTHRU */ default: printf("local: unknown error.\n"); break; } break; case RPC_PROGUNAVAIL: printf("RPC: Program unavailable.\n"); break; case RPC_PROGVERSMISMATCH: printf("RPC: Program/version mismatch.\n"); break; case RPC_PROCUNAVAIL: printf("RPC: Procedure unavailable.\n"); break; case RPC_CANTDECODEARGS: printf("RPC: Server can't decode arguments.\n"); break; case RPC_SYSTEMERROR: printf("RPC: Remote system error.\n"); break; case RPC_UNKNOWNHOST: printf("RPC: Unknown host.\n"); break; case RPC_UNKNOWNPROTO: printf("RPC: Unknown protocol.\n"); break; case RPC_PMAPFAILURE: printf("RPC: Port mapper failure.\n"); break; case RPC_PROGNOTREGISTERED: printf("RPC: Program not registered.\n"); break; case RPC_FAILED: printf("RPC: Failed (unspecified error).\n"); break; default: printf("RPC: (unknown error code).\n"); break; } } } /* * rpc_hdr: sets the fields in the rpc msg header. * * Returns: TRUE on success, FALSE if failure. */ /*ARGSUSED*/ static bool_t rpc_hdr(XDR *xdrs, uint_t xid, rpcprog_t prog, rpcvers_t vers, rpcproc_t proc) { struct rpc_msg call_msg; /* setup header */ call_msg.rm_xid = xid; call_msg.rm_direction = CALL; call_msg.rm_call.cb_rpcvers = (rpcvers_t)RPC_MSG_VERSION; call_msg.rm_call.cb_prog = prog; call_msg.rm_call.cb_vers = vers; /* xdr the header. */ if (xdr_callhdr(xdrs, &call_msg) == FALSE) return (FALSE); else return (TRUE); } /* * our version of brpc_call(). We cache in portnumber in to->sin_port for * your convenience. to and from addresses are taken and received in network * order. */ enum clnt_stat brpc_call( rpcprog_t prog, /* rpc program number to call. */ rpcvers_t vers, /* rpc program version */ rpcproc_t proc, /* rpc procedure to call */ xdrproc_t in_xdr, /* routine to serialize arguments */ caddr_t args, /* arg vector for remote call */ xdrproc_t out_xdr, /* routine to deserialize results */ caddr_t ret, /* addr of buf to place results in */ int rexmit, /* retransmission interval (secs) */ int wait_time, /* how long (secs) to wait (resp) */ struct sockaddr_in *to, /* destination */ struct sockaddr_in *from_who, /* responder's port/address */ uint_t auth) /* type of auth wanted. */ { int s; char hostname[MAXHOSTNAMELEN]; struct sockaddr_in from; /* us. */ socklen_t from_len; XDR xmit_xdrs, rcv_xdrs; /* xdr memory */ AUTH *xmit_auth; /* our chosen auth cookie */ gid_t fake_gids = 1; /* fake gids list for auth_unix */ caddr_t trm_msg, rcv_msg; /* outgoing/incoming rpc mesgs */ struct rpc_msg reply; /* our reply msg header */ int trm_len, rcv_len; struct rpc_err rpc_error; /* to store RPC errors in on rcv. */ static uint_t xid; /* current xid */ uint_t xmit_len; /* How much of the buffer we used */ int nrefreshes = 2; /* # of times to refresh cred */ int flags = 0; /* send flags */ uint_t xdelay; int errors, preserve_errno; uint32_t timeout; socklen_t optlen; xmit_auth = NULL; trm_len = mac_get_mtu(); trm_msg = bkmem_alloc(trm_len); rcv_msg = bkmem_alloc(NFSBUF_SIZE); if (trm_msg == NULL || rcv_msg == NULL) { errno = ENOMEM; rpc_error.re_status = RPC_CANTSEND; goto gt_error; } if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { rpc_error.re_status = RPC_CANTSEND; goto gt_error; } if (dontroute) { (void) setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (const void *)&dontroute, sizeof (dontroute)); } if (to->sin_addr.s_addr == cached_destination.s_addr) { optlen = sizeof (timeout); (void) getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout, &optlen); } else { cached_destination.s_addr = htonl(INADDR_ANY); } /* Bind our endpoint. */ from.sin_family = AF_INET; ipv4_getipaddr(&from.sin_addr); from.sin_addr.s_addr = htonl(from.sin_addr.s_addr); from.sin_port = get_source_port(B_TRUE); if (bind(s, (struct sockaddr *)&from, sizeof (from)) < 0) { rpc_error.re_status = RPC_CANTSEND; goto gt_error; } bzero((caddr_t)&rpc_error, sizeof (struct rpc_err)); /* initialize reply's rpc_msg struct, so we can decode later. */ reply.acpted_rply.ar_verf = _null_auth; /* struct copy */ reply.acpted_rply.ar_results.where = ret; reply.acpted_rply.ar_results.proc = out_xdr; if (ntohs(to->sin_port) == 0) { /* snag the udp port we need. */ if ((to->sin_port = (in_port_t)bpmap_getport(prog, vers, &(rpc_error.re_status), to, NULL)) == 0) goto gt_error; to->sin_port = htons(to->sin_port); } /* generate xid - increment */ if (xid == 0) xid = (uint_t)(prom_gettime() / 1000) + 1; else xid++; /* set up outgoing pkt as xdr modified. */ xdrmem_create(&xmit_xdrs, trm_msg, trm_len, XDR_ENCODE); /* setup rpc header */ if (rpc_hdr(&xmit_xdrs, xid, prog, vers, proc) != TRUE) { dprintf("brpc_call: cannot setup rpc header.\n"); rpc_error.re_status = RPC_FAILED; goto gt_error; } /* setup authentication */ switch (auth) { case AUTH_NONE: xmit_auth = authnone_create(); break; case AUTH_UNIX: /* * Assumes we've configured the stack and thus know our * IP address/hostname, either by using DHCP or rarp/bootparams. */ (void) gethostname(hostname, sizeof (hostname)); xmit_auth = authunix_create(hostname, 0, 1, 1, &fake_gids); break; default: dprintf("brpc_call: Unsupported authentication type: %d\n", auth); rpc_error.re_status = RPC_AUTHERROR; goto gt_error; /*NOTREACHED*/ } /* * rpc_hdr puts everything in the xmit buffer for the header * EXCEPT the proc. Put it, and our authentication info into * it now, serializing as we go. We will be at the place where * we left off. */ xmit_xdrs.x_op = XDR_ENCODE; if ((XDR_PUTINT32(&xmit_xdrs, (int32_t *)&proc) == FALSE) || (AUTH_MARSHALL(xmit_auth, &xmit_xdrs, NULL) == FALSE) || ((*in_xdr)(&xmit_xdrs, args) == FALSE)) { rpc_error.re_status = RPC_CANTENCODEARGS; goto gt_error; } else xmit_len = (int)XDR_GETPOS(&xmit_xdrs); /* for sendto */ /* * Right now the outgoing packet should be all serialized and * ready to go... Set up timers. */ xdelay = (rexmit == 0) ? RPC_REXMIT_MSEC : (rexmit * 1000); (void) setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (void *)&xdelay, sizeof (xdelay)); wait_time = (wait_time == 0) ? RPC_RCVWAIT_MSEC : (wait_time * 1000); wait_time += prom_gettime(); /* * send out the request. The first item in the receive buffer will * be the xid. Check if it is correct. */ errors = 0; rpc_error.re_status = RPC_TIMEDOUT; do { if (sendto(s, trm_msg, xmit_len, flags, (struct sockaddr *)to, sizeof (struct sockaddr_in)) < 0) { /* * If errno is set to ETIMEDOUT, return * with RPC status as RPC_TIMEDOUT. Calling * funciton will take care of this error by * retrying the RPC call. */ if (errno == ETIMEDOUT) { rpc_error.re_status = RPC_TIMEDOUT; } else { rpc_error.re_status = RPC_CANTSEND; } goto gt_error; } from_len = sizeof (struct sockaddr_in); while ((rcv_len = recvfrom(s, rcv_msg, NFSBUF_SIZE, MSG_DONTWAIT, (struct sockaddr *)from_who, &from_len)) > 0 || errors < RPC_ALLOWABLE_ERRORS) { if (rcv_len < 0) { if (errno == EWOULDBLOCK || errno == ETIMEDOUT) { break; /* timeout */ } rpc_error.re_status = RPC_CANTRECV; goto gt_error; } if (ntohl(*((uint32_t *)(rcv_msg))) != xid) { dprintf("brpc_call: xid: 0x%x != 0x%x\n", *(uint32_t *)(rcv_msg), xid); continue; } /* * Let's deserialize the data into our 'ret' buffer. */ xdrmem_create(&rcv_xdrs, rcv_msg, rcv_len, XDR_DECODE); if (xdr_replymsg(&rcv_xdrs, &reply) == FALSE) { rpc_error.re_status = RPC_CANTDECODERES; goto gt_error; } _seterr_reply(&reply, &rpc_error); switch (rpc_error.re_status) { case RPC_SUCCESS: /* * XXX - validate for unix and none * always return true. */ if (AUTH_VALIDATE(xmit_auth, &reply.acpted_rply.ar_verf) == FALSE) { rpc_error.re_status = RPC_AUTHERROR; rpc_error.re_why = AUTH_INVALIDRESP; errors++; } if (reply.acpted_rply.ar_verf.oa_base != 0) { xmit_xdrs.x_op = XDR_FREE; (void) xdr_opaque_auth( &xmit_xdrs, &reply.acpted_rply.ar_verf); } break; case RPC_AUTHERROR: /* * Let's see if our credentials need * refreshing */ if (nrefreshes > 0 && AUTH_REFRESH(xmit_auth, NULL, NULL)) { nrefreshes--; } errors++; break; case RPC_PROCUNAVAIL: /* * Might be a silly portmapper implementation * erroneously responding to our rpc broadcast * indirect portmapper call. For this * particular case, we don't increment the * error counter because we want to keep * sifting for successful replies... */ if (to->sin_addr.s_addr != ntohl(INADDR_BROADCAST)) errors++; break; case RPC_PROGVERSMISMATCH: /* * Successfully talked to server, but they * don't speak our lingo. */ goto gt_error; default: /* Just keep trying till there's no data... */ errors++; break; } if (rpc_error.re_status != RPC_SUCCESS) { dprintf("brpc_call: from: %s, error: ", inet_ntoa(from_who->sin_addr)); rpc_disperr(&rpc_error); } else break; } /* * If we're having trouble reassembling datagrams, let the * application know ASAP so that it can take the appropriate * actions. */ } while (rpc_error.re_status != RPC_SUCCESS && errno != ETIMEDOUT && prom_gettime() < wait_time); gt_error: if (xmit_auth != NULL) AUTH_DESTROY(xmit_auth); if (trm_msg != NULL) bkmem_free(trm_msg, trm_len); if (rcv_msg != NULL) bkmem_free(rcv_msg, NFSBUF_SIZE); if (rpc_error.re_status != RPC_SUCCESS) rpc_disperr(&rpc_error); /* * socket calls reset errno. Since we want to hold onto the errno * value if it is ETIMEDOUT to communicate to our caller that this * RPC_TIMEDOUT situation is due to a stack problem (we're getting * a reply, but the stack simply can't assemble it.), we need to * preserve errno's value over the socket_close(). */ preserve_errno = (errno == ETIMEDOUT) ? errno : 0; (void) socket_close(s); errno = preserve_errno; return (rpc_error.re_status); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _ST_PATHNAME_H #define _ST_PATHNAME_H #ifdef __cplusplus extern "C" { #endif /* * Pathname structure. * System calls which operate on path names gather the * pathname from system call into this structure and reduce * it by peeling off translated components. If a symbolic * link is encountered the new pathname to be translated * is also assembled in this structure. */ struct st_pathname { char *pn_buf; /* underlying storage */ char *pn_path; /* remaining pathname */ uint_t pn_pathlen; /* remaining length */ }; #define PN_STRIP 0x00 /* Strip next component off pn */ #define PN_PEEK 0x01 /* Only peek at next pn component */ #define stpn_peekcomponent(PNP, COMP) stpn_getcomponent(PNP, COMP, PN_PEEK) #define stpn_stripcomponent(PNP, COMP) stpn_getcomponent(PNP, COMP, PN_STRIP) #define stpn_peekchar(PNP) (((PNP)->pn_pathlen != 0) ? \ *((PNP)->pn_path) : (char)0) #define stpn_pathleft(PNP) ((PNP)->pn_pathlen) #define stpn_getpath(PNP) ((PNP)->pn_path) #define stpn_copy(PNP1, PNP2) (stpn_set(PNP2, stpn_getpath(PNP1))) extern int stpn_alloc(); /* allocate buffer for pathname */ extern int stpn_get(); /* allocate buf and copy path into it */ extern int stpn_set(); /* set pathname to string */ extern int stpn_combine(); /* combine to pathnames (for symlink) */ extern int stpn_getcomponent(); /* get next component of pathname */ extern void stpn_skipslash(); /* skip over slashes */ extern void stpn_free(); /* free pathname buffer */ #ifdef __cplusplus } #endif #endif /* _ST_PATHNAME_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ #pragma ident "%Z%%M% %I% %E% SMI" /* * xdr_rec.c, Implements TCP/IP based XDR streams with a "record marking" * layer above tcp (for rpc's use). * * These routines interface XDRSTREAMS to a tcp/ip connection. * There is a record marking layer between the xdr stream * and the tcp transport level. A record is composed on one or more * record fragments. A record fragment is a thirty-two bit header followed * by n bytes of data, where n is contained in the header. The header * is represented as a htonl(u_long). The high order bit encodes * whether or not the fragment is the last fragment of the record * (1 => fragment is last, 0 => more fragments to follow. * The other 31 bits encode the byte length of the fragment. */ #include #include #include #include #include #include #define dprintf if (boothowto & RB_DEBUG) printf extern long lseek(); static bool_t xdrrec_getint32(); static bool_t xdrrec_putint32(); static bool_t xdrrec_getbytes(); static bool_t xdrrec_putbytes(); static uint_t xdrrec_getpos(); static bool_t xdrrec_setpos(); static int32_t *xdrrec_inline(); static void xdrrec_destroy(); static struct xdr_ops *xdrrec_ops(); static bool_t flush_out(); static bool_t fill_input_buf(); static bool_t get_input_bytes(); static bool_t set_input_fragment(); static bool_t skip_input_bytes(); static uint_t fix_buf_size(); /* * A record is composed of one or more record fragments. * A record fragment is a four-byte header followed by zero to * 2**32-1 bytes. The header is treated as a long unsigned and is * encode/decoded to the network via htonl/ntohl. The low order 31 bits * are a byte count of the fragment. The highest order bit is a boolean: * 1 => this fragment is the last fragment of the record, * 0 => this fragment is followed by more fragment(s). * * The fragment/record machinery is not general; it is constructed to * meet the needs of xdr and rpc based on tcp. */ #define LAST_FRAG 0x80000000 typedef struct rec_strm { caddr_t tcp_handle; caddr_t the_buffer; /* * out-goung bits */ int (*writeit)(); caddr_t out_base; /* output buffer (points to frag header) */ caddr_t out_finger; /* next output position */ caddr_t out_boundry; /* data cannot up to this address */ uint32_t *frag_header; /* beginning of current fragment */ bool_t frag_sent; /* true if buffer sent in middle of record */ /* * in-coming bits */ int (*readit)(); uint32_t in_size; /* fixed size of the input buffer */ caddr_t in_base; caddr_t in_finger; /* location of next byte to be had */ caddr_t in_boundry; /* can read up to this location */ int fbtbc; /* fragment bytes to be consumed */ bool_t last_frag; uint_t sendsize; uint_t recvsize; } RECSTREAM; /* * Create an xdr handle for xdrrec * xdrrec_create fills in xdrs. Sendsize and recvsize are * send and recv buffer sizes (0 => use default). * tcp_handle is an opaque handle that is passed as the first parameter to * the procedures readit and writeit. Readit and writeit are read and * write respectively. They are like the system * calls expect that they take an opaque handle rather than an fd. */ void xdrrec_create(XDR *xdrs, uint_t sendsize, uint_t recvsize, caddr_t tcp_handle, int (*readit)(), int (*writeit)()) { RECSTREAM *rstrm = (RECSTREAM *)mem_alloc(sizeof (RECSTREAM)); if (rstrm == NULL) { dprintf("xdrrec_create: out of memory\n"); /* * This is bad. Should rework xdrrec_create to * return a handle, and in this case return NULL */ return; } /* * adjust sizes and allocate buffer quad byte aligned */ rstrm->sendsize = sendsize = fix_buf_size(sendsize); rstrm->recvsize = recvsize = fix_buf_size(recvsize); rstrm->the_buffer = mem_alloc(sendsize + recvsize + BYTES_PER_XDR_UNIT); if (rstrm->the_buffer == NULL) { dprintf("xdrrec_create: out of memory\n"); return; } for (rstrm->out_base = rstrm->the_buffer; (uintptr_t)rstrm->out_base % BYTES_PER_XDR_UNIT != 0; rstrm->out_base++); rstrm->in_base = rstrm->out_base + sendsize; /* * now the rest ... */ xdrs->x_ops = xdrrec_ops(); xdrs->x_private = (caddr_t)rstrm; rstrm->tcp_handle = tcp_handle; rstrm->readit = readit; rstrm->writeit = writeit; rstrm->out_finger = rstrm->out_boundry = rstrm->out_base; rstrm->frag_header = (uint32_t *)rstrm->out_base; rstrm->out_finger += sizeof (uint_t); rstrm->out_boundry += sendsize; rstrm->frag_sent = FALSE; rstrm->in_size = recvsize; rstrm->in_boundry = rstrm->in_base; rstrm->in_finger = (rstrm->in_boundry += recvsize); rstrm->fbtbc = 0; rstrm->last_frag = TRUE; } /* * The routines defined below are the xdr ops which will go into the * xdr handle filled in by xdrrec_create. */ static bool_t xdrrec_getint32(XDR *xdrs, int32_t *ip) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); int32_t *bufip = (int32_t *)(rstrm->in_finger); int32_t myint; /* first try the inline, fast case */ if ((rstrm->fbtbc >= sizeof (int32_t)) && (((ptrdiff_t)rstrm->in_boundry - (ptrdiff_t)bufip) >= sizeof (int32_t))) { *ip = (int32_t)ntohl((uint32_t)(*bufip)); rstrm->fbtbc -= sizeof (int32_t); rstrm->in_finger += sizeof (int32_t); } else { if (!xdrrec_getbytes(xdrs, (caddr_t)&myint, sizeof (int32_t))) return (FALSE); *ip = (int32_t)ntohl((uint32_t)myint); } return (TRUE); } static bool_t xdrrec_putint32(XDR *xdrs, int32_t *ip) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); int32_t *dest_ip = ((int32_t *)(rstrm->out_finger)); if ((rstrm->out_finger += sizeof (int32_t)) > rstrm->out_boundry) { /* * this case should almost never happen so the code is * inefficient */ rstrm->out_finger -= sizeof (int32_t); rstrm->frag_sent = TRUE; if (! flush_out(rstrm, FALSE)) return (FALSE); dest_ip = ((int32_t *)(rstrm->out_finger)); rstrm->out_finger += sizeof (int32_t); } *dest_ip = (int32_t)htonl((uint32_t)(*ip)); return (TRUE); } /* * We need to be a little smarter here because we don't want to induce any * pathological behavior in inetboot's networking stack. The algorithm we * pursue is to try to consume the entire fragment exactly instead of * blindly requesting the max to fill the input buffer. */ static bool_t /* must manage buffers, fragments, and records */ xdrrec_getbytes(XDR *xdrs, caddr_t addr, int32_t len) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); int current; int frag_len; while (len > 0) { current = frag_len = rstrm->fbtbc; if (current == 0) { if (rstrm->last_frag) return (FALSE); if (!set_input_fragment(rstrm)) return (FALSE); continue; } current = (len < current) ? len : current; if (!get_input_bytes(rstrm, addr, frag_len, current)) return (FALSE); addr += current; rstrm->fbtbc -= current; len -= current; } return (TRUE); } static bool_t xdrrec_putbytes(XDR *xdrs, caddr_t addr, int32_t len) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); ptrdiff_t current; while (len > 0) { current = rstrm->out_boundry - rstrm->out_finger; current = (len < current) ? len : current; bcopy(addr, rstrm->out_finger, current); rstrm->out_finger += current; addr += current; len -= current; if (rstrm->out_finger == rstrm->out_boundry) { rstrm->frag_sent = TRUE; if (! flush_out(rstrm, FALSE)) return (FALSE); } } return (TRUE); } static uint_t xdrrec_getpos(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private; int32_t pos; pos = lseek((int)(intptr_t)rstrm->tcp_handle, 0, 1); if (pos != -1) switch (xdrs->x_op) { case XDR_ENCODE: pos += rstrm->out_finger - rstrm->out_base; break; case XDR_DECODE: pos -= rstrm->in_boundry - rstrm->in_finger; break; default: pos = (uint_t)-1; break; } return ((uint_t)pos); } static bool_t xdrrec_setpos(XDR *xdrs, uint_t pos) { RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private; uint_t currpos = xdrrec_getpos(xdrs); int delta = currpos - pos; caddr_t newpos; if ((int)currpos != -1) switch (xdrs->x_op) { case XDR_ENCODE: newpos = rstrm->out_finger - delta; if ((newpos > (caddr_t)(rstrm->frag_header)) && (newpos < rstrm->out_boundry)) { rstrm->out_finger = newpos; return (TRUE); } break; case XDR_DECODE: newpos = rstrm->in_finger - delta; if ((delta < (int)(rstrm->fbtbc)) && (newpos <= rstrm->in_boundry) && (newpos >= rstrm->in_base)) { rstrm->in_finger = newpos; rstrm->fbtbc -= delta; return (TRUE); } break; } return (FALSE); } static int32_t * xdrrec_inline(XDR *xdrs, int len) { RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private; int32_t *buf = NULL; switch (xdrs->x_op) { case XDR_ENCODE: if ((rstrm->out_finger + len) <= rstrm->out_boundry) { buf = (int32_t *)rstrm->out_finger; rstrm->out_finger += len; } break; case XDR_DECODE: if ((len <= rstrm->fbtbc) && ((rstrm->in_finger + len) <= rstrm->in_boundry)) { buf = (int32_t *)rstrm->in_finger; rstrm->fbtbc -= len; rstrm->in_finger += len; } break; } return (buf); } static void xdrrec_destroy(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *)xdrs->x_private; mem_free(rstrm->the_buffer, rstrm->sendsize + rstrm->recvsize + BYTES_PER_XDR_UNIT); mem_free((caddr_t)rstrm, sizeof (RECSTREAM)); } /* * Exported routines to manage xdr records */ /* * Before reading (deserializing from the stream, one should always call * this procedure to guarantee proper record alignment. */ bool_t xdrrec_skiprecord(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); while (rstrm->fbtbc > 0 || (! rstrm->last_frag)) { if (! skip_input_bytes(rstrm, rstrm->fbtbc)) return (FALSE); rstrm->fbtbc = 0; if ((! rstrm->last_frag) && (! set_input_fragment(rstrm))) return (FALSE); } rstrm->last_frag = FALSE; return (TRUE); } #ifdef notneeded /* * Look ahead fuction. * Returns TRUE iff there is no more input in the buffer * after consuming the rest of the current record. */ bool_t xdrrec_eof(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); while (rstrm->fbtbc > 0 || (! rstrm->last_frag)) { if (! skip_input_bytes(rstrm, rstrm->fbtbc)) return (TRUE); rstrm->fbtbc = 0; if ((! rstrm->last_frag) && (! set_input_fragment(rstrm))) return (TRUE); } if (rstrm->in_finger == rstrm->in_boundry) return (TRUE); return (FALSE); } #endif /* notneeded */ /* * The client must tell the package when an end-of-record has occurred. * The second paraemters tells whether the record should be flushed to the * (output) tcp stream. (This let's the package support batched or * pipelined procedure calls.) TRUE => immmediate flush to tcp connection. */ bool_t xdrrec_endofrecord(XDR *xdrs, bool_t sendnow) { RECSTREAM *rstrm = (RECSTREAM *)(xdrs->x_private); ptrdiff_t len; /* fragment length */ if (sendnow || rstrm->frag_sent || ((ptrdiff_t)rstrm->out_finger + sizeof (uint32_t) >= (ptrdiff_t)rstrm->out_boundry)) { rstrm->frag_sent = FALSE; return (flush_out(rstrm, TRUE)); } len = (ptrdiff_t)rstrm->out_finger - (ptrdiff_t)rstrm->frag_header; len -= sizeof (uint32_t); *(rstrm->frag_header) = htonl((uint32_t)len | LAST_FRAG); rstrm->frag_header = (uint32_t *)rstrm->out_finger; rstrm->out_finger += sizeof (uint32_t); return (TRUE); } /* * Internal useful routines */ static bool_t flush_out(RECSTREAM *rstrm, bool_t eor) { uint32_t eormask = (eor == TRUE) ? LAST_FRAG : 0; ptrdiff_t len; len = (ptrdiff_t)rstrm->out_finger - (ptrdiff_t)rstrm->frag_header; len -= sizeof (uint32_t); *(rstrm->frag_header) = htonl(len | eormask); len = rstrm->out_finger - rstrm->out_base; if ((*(rstrm->writeit))(rstrm->tcp_handle, rstrm->out_base, (int)len) != (int)len) return (FALSE); rstrm->frag_header = (uint32_t *)rstrm->out_base; rstrm->out_finger = (caddr_t)rstrm->out_base + sizeof (uint32_t); return (TRUE); } static bool_t /* knows nothing about records! Only about input buffers */ fill_input_buf(RECSTREAM *rstrm, int frag_len) { caddr_t where; uintptr_t i; int len; where = rstrm->in_base; i = (uintptr_t)rstrm->in_boundry % BYTES_PER_XDR_UNIT; where += i; len = (frag_len < (rstrm->in_size - i)) ? frag_len : rstrm->in_size - i; #ifdef DEBUG printf("fill_input_buf: len = %d\n", len); #endif if ((len = (*(rstrm->readit))(rstrm->tcp_handle, where, len)) == -1) return (FALSE); rstrm->in_finger = where; where += len; rstrm->in_boundry = where; return (TRUE); } static bool_t get_input_bytes(RECSTREAM *rstrm, caddr_t addr, int frag_len, int len) { ptrdiff_t current; while (len > 0) { current = rstrm->in_boundry - rstrm->in_finger; #ifdef DEBUG printf("get_input_bytes: len = %d, frag_len = %d, current %d\n", len, frag_len, current); #endif /* * set_input_bytes doesn't know how large the fragment is, we * need to get the header so just grab a header's size worth */ if (frag_len == 0) frag_len = len; if (current == 0) { if (! fill_input_buf(rstrm, frag_len)) return (FALSE); continue; } current = (len < current) ? len : current; bcopy(rstrm->in_finger, addr, current); rstrm->in_finger += current; addr += current; len -= current; } return (TRUE); } static bool_t /* next four bytes of the input stream are treated as a header */ set_input_fragment(RECSTREAM *rstrm) { uint32_t header; if (! get_input_bytes(rstrm, (caddr_t)&header, 0, sizeof (header))) return (FALSE); header = (uint32_t)ntohl(header); rstrm->last_frag = ((header & LAST_FRAG) == 0) ? FALSE : TRUE; rstrm->fbtbc = header & (~LAST_FRAG); #ifdef DEBUG printf("set_input_fragment: frag_len = %d, last frag = %s\n", rstrm->fbtbc, rstrm->last_frag ? "TRUE" : "FALSE"); #endif return (TRUE); } static bool_t /* consumes input bytes; knows nothing about records! */ skip_input_bytes(RECSTREAM *rstrm, int32_t cnt) { ptrdiff_t current; #ifdef DEBUG printf("skip_input_fragment: cnt = %d\n", cnt); #endif while (cnt > 0) { current = rstrm->in_boundry - rstrm->in_finger; if (current == 0) { if (! fill_input_buf(rstrm, cnt)) return (FALSE); continue; } current = (cnt < current) ? cnt : current; rstrm->in_finger += current; cnt -= current; } return (TRUE); } static uint_t fix_buf_size(uint_t s) { if (s < 100) s = 4000; return (RNDUP(s)); } static struct xdr_ops * xdrrec_ops() { static struct xdr_ops ops; if (ops.x_getint32 == NULL) { ops.x_getint32 = xdrrec_getint32; ops.x_putint32 = xdrrec_putint32; ops.x_getbytes = xdrrec_getbytes; ops.x_putbytes = xdrrec_putbytes; ops.x_getpostn = xdrrec_getpos; ops.x_setpostn = xdrrec_setpos; ops.x_inline = xdrrec_inline; ops.x_destroy = xdrrec_destroy; } return (&ops); } #!/bin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" echo_file usr/src/stand/lib/fs/Makefile.com # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2004 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # LIBRARY = libufs.a OBJECTS = ufsops.o lufsboot.o include ../Makefile.com include ../../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * Big theory statement on how ufsboot makes use of the log * in case the filesystem wasn't shut down cleanly. * * The structure of the ufs on-disk log looks like this: * * +-----------------+ * | SUPERBLOCK | * | ... | * | fs_logbno +--> +-----------------------+ * | ... | | EXTENT BLOCK | * +-----------------+ | ... | * | nextents | * +----------------------+ extents[0].pbno | * | | { extents[1].pbno } +------------+ * | | ... +--> ... | * | +-----------------------+ | * v | * +-----------------------------+ \ | * | ON-DISK LOG HEADER | | | * | ... | | | * | od_head_lof +--+ | | * | ... | | | | * +-----------------------------+ <|---|- od_bol_lof | * | sector (may contain deltas) | | | (logical offset) | * | +-------------------------+ | | | * | | trailer (some ident#) | | > extents[0].nbno | * +---+-------------------------+ | | blocks ("sectors") | * . . | | | * . . | | | * +-----------------------------+<-+ | | * | delta1 delta2 delta3 | | | * | d +-------------------------+ | | * | e | ident#: od_head_ident | | | * +---+-------------------------+ / | * | * +-----------------------------+ <---------------------------+ * | lta4 delta5 delta6 de | * | l +-------------------------+ * | t | ident#: od_head_ident+1 | * +---+-------------------------+ * . . * +-----------------------------+ * | sector (may contain deltas) | * | +------------------+ * | | trailer (ident#) | * +----------+------------------+ <-- od_eol_lof (logical offset) * * The ufs on-disk log has the following properties: * * 1. The log is made up from at least one extent. "fs_logbno" in * the superblock points to where this is found. * 2. Extents describe the logical layout. * - Logical offset 0 is the on-disk log header. It's also * at the beginning of the first physical block. * - If there's more than one extent, the equation holds: * extent[i+1].lbno == extent[i].lbno + extent[i].nbno * i.e. logical offsets form a contiguous sequence. Yet on disk, * two logically-adjacent offsets may be located in two * physically disjoint extents, so logical offsets need to be * translated into physical disk block addresses for access. * - Various fields in the on-disk log header structure refer * to such logical log offsets. * 3. The actual logical logspace begins after the log header, at * the logical offset indicated by "od_bol_lof". Every 512 Bytes * (a "sector" in terms of ufs logging) is a sector trailer which * contains a sequence number, the sector ident. * 4. Deltas are packed tight in the remaining space, i.e. a delta * may be part of more than one sector. Reads from the logspace * must be split at sector boundaries, since the trailer is never * part of a delta. Delta sizes vary. * 5. The field "od_head_lof" points to the start of the dirty part * of the log, i.e. to the first delta header. Likewise, "od_head_ident" * is the sequence number where the valid part of the log starts; if * the sector pointed to by "od_head_lof" has a sector ident different * from "od_head_ident", the log is empty. * 6. The valid part of the log extends for as many sectors as their ident * numbers form a contiguous sequence. When reaching the logical end of * the log, "od_bol_lof", logical offsets wrap around to "od_bol_lof", * i.e. the log forms a circular buffer. * * For the strategy how to handle accessing the log, item 4. is the * most important one - its consequence is that the log can only be * read in one direction - forward, starting at the head. * * The task of identifying whether a given metadata block is * actually in the log therefore requires reading the entire * log. Doing so is memory-efficient but kills speed if re-done * at every metadata read (64MB log size vs. 512 byte metadata * block size: 128 times as much I/O, possibly only to find out * that this block was not in the log ...). * * First thought to speed this up is to let ufsboot roll the log. * But this is not possible because: * - ufsboot currently does not implement any write functionality, * the boot-time ufs implementation is read-only. * - firmware write interfaces may or may not be available, in any * case, they're rarely used and untested for such a purpose. * - that would duplicate a lot of code, since at the moment only * kernel ufs logging implements log rolling. * - the boot environment cannot be considered high-performance; * rolling the log there would be slow. * - boot device and root device could well be different, creating * inconsistencies e.g. with a mirrored root if the log is rolled. * * Therefore, caching the log structural information (boot-relevant * deltas and their logical log offset) is required for fast access * to the data in the log. This code builds a logmap for that purpose. * * As a simple optimization, if we find the log is empty, we will not * use it - log reader support for ufsboot has no noticeable overhead * for clean logs, or for root filesystems that aren't logging. */ #define LB_HASHSHIFT 13 #define LB_HASHSIZE (1 << LB_HASHSHIFT) #define LB_HASHFUNC(mof) (((mof) >> LB_HASHSHIFT) & (LB_HASHSIZE - 1)) #define LOGBUF_MAXSIZE (8*1024*1024) #define LOGBUF_MINSIZE (256*1024) #define LOG_IS_EMPTY 0 #define LOG_IS_OK 1 #define LOG_IS_ERRORED 2 /* * We build a hashed logmap of those while scanning the log. * sizeof(lb_map_t) is 40 on 64bit, 32 on 32bit; the max sized * resalloc'ed buffer can accomodate around ~500k of those; * this is approximately the maximum amount of deltas we'll * see if a 64MB ufs log is completely filled. We'll make no * attempt to free and reallocate the resalloc'ed buffer if * we overflow, as conservative sizing should make that an * impossibility. A future enhancement may allocate memory * here as needed - once the boot time memory allocator * supports that. */ typedef struct lb_mapentry { struct lb_mapentry *l_next; /* hash chaining */ struct lb_mapentry *l_prev; /* hash chaining */ int64_t l_mof; /* disk addr this delta is against */ int16_t l_nb; /* size of delta */ int16_t l_flags; int32_t l_lof; /* log offset for delta header */ int32_t l_tid; /* transaction this delta is part of */ delta_t l_typ; /* see */ } lb_me_t; #define LB_ISCANCELLED 1 #define inslist(lh, l) if ((*(lh))) { \ (*(lh))->l_prev->l_next = (l); \ (l)->l_next = (*(lh)); \ (l)->l_prev = (*(lh))->l_prev; \ (*(lh))->l_prev = (l); \ } else { \ (l)->l_next = (l); \ (l)->l_prev = (l); \ (*(lh)) = l; \ } #define remlist(lh, l) \ if ((l)->l_next == (l)) { \ if (*(lh) != (l) || (l)->l_prev != (l)) \ dprintf("Logmap hash inconsistency.\n"); \ *(lh) = (lb_me_t *)NULL; \ } else { \ if (*(lh) == (l)) \ *(lh) = (l)->l_next; \ (l)->l_prev->l_next = (l)->l_next; \ (l)->l_next->l_prev = (l)->l_prev; \ } #define lufs_alloc_me() \ (lb_me_t *)lufs_alloc_from_logbuf(sizeof (lb_me_t)) extern int boothowto; static int ufs_is_lufs = 0; static fileid_t *logfp = (fileid_t *)NULL; static extent_block_t *eb = (extent_block_t *)NULL; static ml_odunit_t odi; static char logbuffer_min[LOGBUF_MINSIZE]; static caddr_t logbuffer = (caddr_t)NULL; static caddr_t elogbuffer = (caddr_t)NULL; static caddr_t logbuf_curptr; static lb_me_t **loghash = (lb_me_t **)NULL; static lb_me_t *lfreelist; static uint32_t curtid; int lufs_support = 1; void lufs_boot_init(fileid_t *); void lufs_closeall(void); void lufs_merge_deltas(fileid_t *); static int lufs_logscan(void); extern int diskread(fileid_t *filep); extern caddr_t resalloc(enum RESOURCES, size_t, caddr_t, int); #if defined(__sparcv9) #define LOGBUF_BASEADDR ((caddr_t)(SYSBASE - LOGBUF_MAXSIZE)) #endif static int lufs_alloc_logbuf(void) { /* * Allocate memory for caching the log. Since the logbuffer can * potentially exceed the boot scratch memory limit, we use resalloc * directly, passing the allocation to the low-level boot-time * backend allocator. The chosen VA range is the top end of * the kernel's segmap segment, so we're not interfering * with the kernel because segmap is created at a time when * the 2nd-stage boot has already been unloaded and this VA * range was given back. * * On sparc platforms, the kernel cannot recover the memory * obtained from resalloc because the page structs are allocated * before the call to BOP_QUIESCE. To avoid leaking this * memory, the logbuffer is allocated from a small bss array * that should hold the logmap except in the most extreme cases. * If the bss array is too small, the logbuffer is extended * from resalloc 1 page at a time. */ logbuffer = logbuffer_min; elogbuffer = logbuffer+LOGBUF_MINSIZE; logbuf_curptr = logbuffer; lfreelist = (lb_me_t *)NULL; if (logbuffer == (caddr_t)NULL) return (0); dprintf("Buffer for boot loader logging support: 0x%p, size 0x%x\n", logbuffer, elogbuffer-logbuffer); return (1); } static void lufs_free_logbuf() { /* * Solaris/x86 has no prom_free() routine at this time. * Reclaiming the VA range below KERNEL_TEXT on Solaris/x86 * is done by the kernel startup itself, in hat_unload_prom() * after the bootloader has been quiesced. * * Solaris on sparc has a prom_free() routine that will update * the memlist properties to reflect the freeing of the * logbuffer. However, the sparc kernel cannot recover * the memory freed after the call to BOP_QUIESCE as the * page struct have already been allocated. We call * prom_free anyway so that the kernel can reclaim this * memory in the future. */ if (logbuffer == LOGBUF_BASEADDR) prom_free(logbuffer, elogbuffer-logbuffer); logbuffer = (caddr_t)NULL; } static caddr_t lufs_alloc_from_logbuf(size_t sz) { caddr_t tmpaddr; lb_me_t *l; /* * Satisfy lb_me_t allocations from the freelist * first if possible. */ if ((sz == sizeof (lb_me_t)) && lfreelist) { l = lfreelist; lfreelist = lfreelist->l_next; return ((caddr_t)l); } if (elogbuffer < logbuf_curptr + sz) { caddr_t np; size_t nsz; /* * Out of space in current chunk - try to add another. */ if (logbuffer == logbuffer_min) { np = LOGBUF_BASEADDR; } else { np = elogbuffer; } nsz = roundup(sz, PAGESIZE); if (np + nsz > LOGBUF_BASEADDR + LOGBUF_MAXSIZE) { return ((caddr_t)NULL); } np = resalloc(RES_CHILDVIRT, nsz, np, 0UL); if (np == (caddr_t)NULL) { return ((caddr_t)NULL); } if (logbuffer == logbuffer_min) logbuffer = LOGBUF_BASEADDR; logbuf_curptr = np; elogbuffer = logbuf_curptr + nsz; } tmpaddr = logbuf_curptr; logbuf_curptr += sz; bzero(tmpaddr, sz); return (tmpaddr); } static int32_t lufs_read_log(int32_t addr, caddr_t va, int nb) { int i, fastpath = 0; daddr_t pblk, lblk; sect_trailer_t *st; uint32_t ident; /* * Fast path for skipping the read if no target buffer * is specified. Don't do this for the initial scan. */ if (ufs_is_lufs && (va == (caddr_t)NULL)) fastpath = 1; while (nb) { /* log wraparound check */ if (addr == odi.od_eol_lof) addr = odi.od_bol_lof; if (fastpath) goto read_done; /* * Translate logically-contiguous log offsets into physical * block numbers. For a log consisting of a single extent: * pbno = btodb(addr) - extents[0].lbno; * Otherwise, search for the extent which contains addr. */ pblk = 0; lblk = btodb(addr); for (i = 0; i < eb->nextents; i++) { if (lblk >= eb->extents[i].lbno && lblk < eb->extents[i].lbno + eb->extents[i].nbno) { pblk = lblk - eb->extents[i].lbno + eb->extents[i].pbno; break; } } if (pblk == 0) { /* * block #0 can never be in a log extent since this * block always contains the primary superblock copy. */ dprintf("No log extent found for log offset 0x%llx.\n", addr); return (0); } /* * Check whether the block we want is cached from the last * read. If not, read it in now. */ if (logfp->fi_blocknum != pblk) { logfp->fi_blocknum = pblk; logfp->fi_memp = logfp->fi_buf; logfp->fi_count = DEV_BSIZE; logfp->fi_offset = 0; if (diskread(logfp)) { dprintf("I/O error reading the ufs log" \ " at block 0x%x.\n", logfp->fi_blocknum); return (0); } /* * Log structure verification. The block which we just * read has an ident number that must match its offset * in blocks from the head of the log. Since the log * can wrap around, we have to check for that to get the * ident right. Out-of-sequence idents can happen after * power failures, panics during a partial transaction, * media errors, ... - in any case, they mark the end of * the valid part of the log. */ st = (sect_trailer_t *)(logfp->fi_memp + LDL_USABLE_BSIZE); /* od_head_ident is where the sequence starts */ ident = odi.od_head_ident; if (lblk >= lbtodb(odi.od_head_lof)) { /* no wraparound */ ident += (lblk - lbtodb(odi.od_head_lof)); } else { /* log wrapped around the end */ ident += (lbtodb(odi.od_eol_lof) - lbtodb(odi.od_head_lof)); ident += (lblk - lbtodb(odi.od_bol_lof)); } if (ident != st->st_ident) return (0); } read_done: /* * Copy the delta contents to the destination buffer if * one was specified. Otherwise, just skip the contents. */ i = MIN(NB_LEFT_IN_SECTOR(addr), nb); if (va != NULL) { bcopy(logfp->fi_buf + (addr - ldbtob(lbtodb(addr))), va, i); va += i; } nb -= i; addr += i; /* * Skip sector trailer if necessary. */ if (NB_LEFT_IN_SECTOR(addr) == 0) addr += sizeof (sect_trailer_t); } return (addr); } void lufs_boot_init(fileid_t *filep) { struct fs *sb = (struct fs *)filep->fi_memp; int err = 0; /* * boot_ufs_mountroot() should have called us with a * filep pointing to the superblock. Verify that this * is so first. * Then check whether this filesystem has a dirty log. * Also return if lufs support was disabled on request. */ if (!lufs_support || sb != (struct fs *)&filep->fi_devp->un_fs.di_fs || sb->fs_clean != FSLOG || sb->fs_logbno == 0) { return; } if (boothowto & RB_VERBOSE) printf("The boot filesystem is logging.\n"); /* * The filesystem is logging, there is a log area * allocated for it. Check the log state and determine * whether it'll be possible to use this log. */ /* * Allocate a private fileid_t for use when reading * from the log. */ eb = (extent_block_t *)bkmem_zalloc(sb->fs_bsize); logfp = (fileid_t *)bkmem_zalloc(sizeof (fileid_t)); logfp->fi_memp = logfp->fi_buf; logfp->fi_devp = filep->fi_devp; /* * Read the extent block and verify that what we * find there are actually lufs extents. * Make it simple: the extent block including all * extents cannot be larger than a filesystem block. * So read a whole filesystem block, to make sure * we have read all extents in the same operation. */ logfp->fi_blocknum = sb->fs_logbno; logfp->fi_count = sb->fs_bsize; logfp->fi_memp = (caddr_t)eb; logfp->fi_offset = 0; if (diskread(logfp) || eb->type != LUFS_EXTENTS) { dprintf("Failed to read log extent block.\n"); err = LOG_IS_ERRORED; goto out; } /* * Read the on disk log header. If that fails, * try the backup copy on the adjacent block. */ logfp->fi_blocknum = eb->extents[0].pbno; logfp->fi_count = sizeof (ml_odunit_t); logfp->fi_memp = (caddr_t)&odi; logfp->fi_offset = 0; if (diskread(logfp)) { logfp->fi_blocknum = eb->extents[0].pbno + 1; logfp->fi_count = sizeof (ml_odunit_t); logfp->fi_memp = (caddr_t)&odi; logfp->fi_offset = 0; if (diskread(logfp)) { dprintf("Failed to read on-disk log header.\n"); err = LOG_IS_ERRORED; goto out; } } /* * Verify that we understand this log, and * that the log isn't bad or empty. */ if (odi.od_version != LUFS_VERSION_LATEST) { dprintf("On-disk log format v%d != supported format v%d.\n", odi.od_version, LUFS_VERSION_LATEST); err = LOG_IS_ERRORED; } else if (odi.od_badlog) { dprintf("On-disk log is marked bad.\n"); err = LOG_IS_ERRORED; } else if (odi.od_chksum != odi.od_head_ident + odi.od_tail_ident) { dprintf("On-disk log checksum %d != ident sum %d.\n", odi.od_chksum, odi.od_head_ident + odi.od_tail_ident); err = LOG_IS_ERRORED; } else { /* * All consistency checks ok. Scan the log, build the * log hash. If this succeeds we'll be using the log * when reading from this filesystem. */ err = lufs_logscan(); } out: ufs_is_lufs = 1; switch (err) { case LOG_IS_EMPTY: if (boothowto & RB_VERBOSE) printf("The ufs log is empty and will not be used.\n"); lufs_closeall(); break; case LOG_IS_OK: if (boothowto & RB_VERBOSE) printf("Using the ufs log.\n"); break; case LOG_IS_ERRORED: if (boothowto & RB_VERBOSE) printf("Couldn't build log hash. Can't use ufs log.\n"); lufs_closeall(); break; default: dprintf("Invalid error %d while scanning the ufs log.\n", err); break; } } static int lufs_logscan_read(int32_t *addr, struct delta *d) { *addr = lufs_read_log(*addr, (caddr_t)d, sizeof (struct delta)); if (*addr == 0 || (int)d->d_typ < DT_NONE || d->d_typ > DT_MAX || d->d_nb >= odi.od_logsize) return (0); return (1); } static int lufs_logscan_skip(int32_t *addr, struct delta *d) { switch (d->d_typ) { case DT_COMMIT: /* * A DT_COMMIT delta has no size as such, but will * always "fill up" the sector that contains it. * The next delta header is found at the beginning * of the next 512-Bytes sector, adjust "addr" to * reflect that. */ *addr += ((*addr & (DEV_BSIZE - 1))) ? NB_LEFT_IN_SECTOR(*addr) + sizeof (sect_trailer_t) : 0; return (1); case DT_CANCEL: case DT_ABZERO: /* * These types of deltas occupy no space in the log */ return (1); default: /* * Skip over the delta contents. */ *addr = lufs_read_log(*addr, NULL, d->d_nb); } return (*addr != 0); } static void lufs_logscan_freecancel(void) { lb_me_t **lh, *l, *lnext; int i; /* * Walk the entire log hash and put cancelled entries * onto the freelist. Corner cases: * a) empty hash chain (*lh == NULL) * b) only one entry in chain, and that is cancelled. * If for every cancelled delta another one would've * been added, this situation couldn't occur, but a * DT_CANCEL delta can lead to this as it is never * added. */ for (i = 0; i < LB_HASHSIZE; i++) { lh = &loghash[i]; l = *lh; do { if (*lh == (lb_me_t *)NULL) break; lnext = l->l_next; if (l->l_flags & LB_ISCANCELLED) { remlist(lh, l); bzero((caddr_t)l, sizeof (lb_me_t)); l->l_next = lfreelist; lfreelist = l; /* * Just removed the hash head. In order not * to terminate the while loop, respin chain * walk for this hash chain. */ if (lnext == *lh) { i--; break; } } l = lnext; } while (l != *lh); } } static int lufs_logscan_addmap(int32_t *addr, struct delta *d) { lb_me_t **lh, *l; switch (d->d_typ) { case DT_COMMIT: /* * Handling DT_COMMIT deltas is special. We need to: * 1. increase the transaction ID * 2. remove cancelled entries. */ lufs_logscan_freecancel(); curtid++; break; case DT_INODE: /* * Deltas against parts of on-disk inodes are * assumed to be timestamps. Ignore those. */ if (d->d_nb != sizeof (struct dinode)) break; /* FALLTHROUGH */ case DT_CANCEL: case DT_ABZERO: case DT_AB: case DT_DIR: case DT_FBI: /* * These types of deltas contain and/or modify structural * information that is needed for booting the system: * - where to find a file (DT_DIR, DT_FBI) * - the file itself (DT_INODE) * - data blocks associated with a file (DT_AB, DT_ABZERO) * * Building the hash chains becomes complicated because there * may exist an older (== previously added) entry that overlaps * with the one we want to add. * Four cases must be distinguished: * 1. The new delta is an exact match for an existing one, * or is a superset of an existing one, and both * belong to the same transaction. * The new delta completely supersedes the old one, so * remove that and reuse the structure for the new. * Then add the new delta to the head of the hashchain. * 2. The new delta is an exact match for an existing one, * or is a superset of an existing one, but the two * belong to different transactions (i.e. the old one is * committed). * The existing one is marked to be cancelled when the * next DT_COMMIT record is found, and the hash chain * walk is continued as there may be more existing entries * found which overlap the new delta (happens if that is * a superset of those in the log). * Once no more overlaps are found, goto 4. * 3. An existing entry completely covers the new one. * The new delta is then added directly before this * existing one. * 4. No (more) overlaps with existing entries are found. * Unless this is a DT_CANCEL delta, whose only purpose * is already handled by marking overlapping entries for * cancellation, add the new delta at the hash chain head. * * This strategy makes sure that the hash chains are properly * ordered. lufs_merge_deltas() walks the hash chain backward, * which then ensures that delta merging is done in the same * order as those deltas occur in the log - remember, the * log can only be read in one direction. * */ lh = &loghash[LB_HASHFUNC(d->d_mof)]; l = *lh; do { if (l == (lb_me_t *)NULL) break; /* * This covers the first two cases above. * If this is a perfect match from the same transaction, * and it isn't already cancelled, we simply replace it * with its newer incarnation. * Otherwise, mark it for cancellation. Handling of * DT_COMMIT is going to remove it, then. */ if (WITHIN(l->l_mof, l->l_nb, d->d_mof, d->d_nb)) { if (!(l->l_flags & LB_ISCANCELLED)) { if (l->l_tid == curtid && d->d_typ != DT_CANCEL) { remlist(lh, l); l->l_mof = d->d_mof; l->l_lof = *addr; l->l_nb = d->d_nb; l->l_typ = d->d_typ; l->l_flags = 0; l->l_tid = curtid; inslist(lh, l); return (1); } else { /* * 2nd case - cancel only. */ l->l_flags |= LB_ISCANCELLED; } } } else if (WITHIN(d->d_mof, d->d_nb, l->l_mof, l->l_nb)) { /* * This is the third case above. * With deltas DT_ABZERO/DT_AB and DT_FBI/DT_DIR * this may happen - an existing previous delta * is larger than the current one we're planning * to add - DT_ABZERO deltas are supersets of * DT_AB deltas, and likewise DT_FBI/DT_DIR. * In order to do merging correctly, such deltas * put up a barrier for new ones that overlap, * and we have to add the new delta immediately * before (!) the existing one. */ lb_me_t *newl; newl = lufs_alloc_me(); if (newl == (lb_me_t *)NULL) { /* * No memory. Throw away everything * and try booting without logging * support. */ curtid = 0; return (0); } newl->l_mof = d->d_mof; newl->l_lof = *addr; /* "payload" address */ newl->l_nb = d->d_nb; newl->l_typ = d->d_typ; newl->l_tid = curtid; newl->l_prev = l->l_prev; newl->l_next = l; l->l_prev->l_next = newl; l->l_prev = newl; if (*lh == l) *lh = newl; return (1); } l = l->l_next; } while (l != *lh); /* * This is case 4., add a new delta at the head of the chain. * * If the new delta is a DT_CANCEL entry, we handled it by * marking everything it covered for cancellation. We can * get by without actually adding the delta itself to the * hash, as it'd need to be removed by the commit code anyway. */ if (d->d_typ == DT_CANCEL) break; l = lufs_alloc_me(); if (l == (lb_me_t *)NULL) { /* * No memory. Throw away everything * and try booting without logging * support. */ curtid = 0; return (0); } l->l_mof = d->d_mof; l->l_lof = *addr; /* this is the "payload" address */ l->l_nb = d->d_nb; l->l_typ = d->d_typ; l->l_tid = curtid; inslist(lh, l); break; default: break; } return (1); } static int lufs_logscan_prescan(void) { /* * Simulate a full log by setting the tail to be one sector * behind the head. This will make the logscan read all * of the log until an out-of-sequence sector ident is * found. */ odi.od_tail_lof = dbtob(btodb(odi.od_head_lof)) - DEV_BSIZE; if (odi.od_tail_lof < odi.od_bol_lof) odi.od_tail_lof = odi.od_eol_lof - DEV_BSIZE; if (odi.od_tail_lof >= odi.od_eol_lof) odi.od_tail_lof = odi.od_bol_lof; /* * While sector trailers maintain TID values, od_head_tid * is not being updated by the kernel ufs logging support * at this time. We therefore count transactions ourselves * starting at zero - as does the kernel ufs logscan code. */ curtid = 0; if (!lufs_alloc_logbuf()) { dprintf("Failed to allocate log buffer.\n"); return (0); } loghash = (lb_me_t **)lufs_alloc_from_logbuf( LB_HASHSIZE * sizeof (lb_me_t *)); if (loghash == (lb_me_t **)NULL) { dprintf("Can't allocate loghash[] array."); return (0); } return (1); } /* * This function must remove all uncommitted entries (l->l_tid == curtid) * from the log hash. Doing this, we implicitly delete pending cancellations * as well. * It uses the same hash walk algorithm as lufs_logscan_freecancel(). Only * the check for entries that need to be removed is different. */ static void lufs_logscan_postscan(void) { lb_me_t **lh, *l, *lnext; int i; for (i = 0; i < LB_HASHSIZE; i++) { lh = &loghash[i]; l = *lh; do { if (l == (lb_me_t *)NULL) break; lnext = l->l_next; if (l->l_tid == curtid) { remlist(lh, l); bzero((caddr_t)l, sizeof (lb_me_t)); l->l_next = lfreelist; lfreelist = l; if (*lh == (lb_me_t *)NULL) break; /* * Just removed the hash head. In order not * to terminate the while loop, respin chain * walk for this hash chain. */ if (lnext == *lh) { i--; break; } } else { l->l_flags &= ~(LB_ISCANCELLED); } l = lnext; } while (l != *lh); } } /* * This function builds the log hash. It performs the same sequence * of actions at logscan as the kernel ufs logging support: * - Prepare the log for scanning by simulating a full log. * - As long as sectors read from the log have contiguous idents, do: * read the delta header * add the delta to the logmap * skip over the contents to the start of the next delta header * - After terminating the scan, remove uncommitted entries. * * This function cannot fail except if mapping the logbuffer area * during lufs_logscan_prescan() fails. If there is a structural * integrity problem and the on-disk log cannot be read, we'll * treat this as the same situation as an uncommitted transaction * at the end of the log (or, corner case of that, an empty log * with no committed transactions in it at all). * */ static int lufs_logscan(void) { int32_t addr; struct delta d; if (!lufs_logscan_prescan()) return (LOG_IS_ERRORED); addr = odi.od_head_lof; /* * Note that addr == od_tail_lof means a completely filled * log. This almost never happens, so the common exit path * from this loop is via one of the 'break's. */ while (addr != odi.od_tail_lof) { if (!lufs_logscan_read(&addr, &d)) break; if (!lufs_logscan_addmap(&addr, &d)) return (LOG_IS_ERRORED); if (!lufs_logscan_skip(&addr, &d)) break; } lufs_logscan_postscan(); /* * Check whether the log contains data, and if so whether * it contains committed data. */ if (addr == odi.od_head_lof || curtid == 0) { return (LOG_IS_EMPTY); } return (LOG_IS_OK); } /* * A metadata block was read from disk. Check whether the logmap * has a delta against this byte range, and if so read it in, since * the data in the log is more recent than what was read from other * places on the disk. */ void lufs_merge_deltas(fileid_t *fp) { int nb; int64_t bof; lb_me_t **lh, *l; int32_t skip; /* * No logmap: Empty log. Nothing to do here. */ if (!ufs_is_lufs || logbuffer == (caddr_t)NULL) return; bof = ldbtob(fp->fi_blocknum); nb = fp->fi_count; /* * Search the log hash. * Merge deltas if an overlap is found. */ lh = &loghash[LB_HASHFUNC(bof)]; if (*lh == (lb_me_t *)NULL) return; l = *lh; do { l = l->l_prev; if (OVERLAP(l->l_mof, l->l_nb, bof, nb)) { /* * Found a delta in the log hash which overlaps * with the current metadata block. Read the * actual delta payload from the on-disk log * directly into the file buffer. */ if (l->l_typ != DT_ABZERO) { /* * We have to actually read this part of the * log as it could contain a sector trailer, or * wrap around the end of the log. * If it did, the second offset generation would * be incorrect if we'd started at l->l_lof. */ if (!(skip = lufs_read_log(l->l_lof, NULL, MAX(bof - l->l_mof, 0)))) dprintf("scan/merge error, pre-skip\n"); if (!(skip = lufs_read_log(skip, fp->fi_memp + MAX(l->l_mof - bof, 0), MIN(l->l_mof + l->l_nb, bof + nb) - MAX(l->l_mof, bof)))) dprintf("scan/merge error, merge\n"); } else { /* * DT_ABZERO requires no disk access, just * clear the byte range which overlaps with * the delta. */ bzero(fp->fi_memp + MAX(l->l_mof - bof, 0), MIN(l->l_mof + l->l_nb, bof + nb) - MAX(l->l_mof, bof)); } } } while (l->l_prev != (*lh)->l_prev); printf("*\b"); } void lufs_closeall(void) { if (ufs_is_lufs) { bkmem_free((char *)eb, logfp->fi_devp->un_fs.di_fs.fs_bsize); bkmem_free((char *)logfp, sizeof (fileid_t)); eb = (extent_block_t *)NULL; bzero((caddr_t)&odi, sizeof (ml_odunit_t)); logfp = (fileid_t *)NULL; lufs_free_logbuf(); ufs_is_lufs = 0; } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * Copyright (c) 2016 by Delphix. All rights reserved. */ #include #include #include #include #include #include #include #include #include #include #include #include int print_cache_stats = 0; /* * This fd is used when talking to the device file itself. */ static fileid_t *head; /* * hooks into ufs logging support */ extern void lufs_boot_init(fileid_t *); extern void lufs_closeall(void); extern void lufs_merge_deltas(fileid_t *); /* Only got one of these...ergo, only 1 fs open at once */ /* static */ devid_t *ufs_devp; struct dirinfo { int loc; fileid_t *fi; }; /* * Function prototypes */ static int boot_ufs_mountroot(char *str); static int boot_ufs_unmountroot(void); static int boot_ufs_open(char *filename, int flags); static int boot_ufs_close(int fd); static ssize_t boot_ufs_read(int fd, caddr_t buf, size_t size); static off_t boot_ufs_lseek(int, off_t, int); static int boot_ufs_fstat(int fd, struct bootstat *stp); static void boot_ufs_closeall(int flag); static int boot_ufs_getdents(int fd, struct dirent *dep, unsigned size); struct boot_fs_ops boot_ufs_ops = { "ufs", boot_ufs_mountroot, boot_ufs_unmountroot, boot_ufs_open, boot_ufs_close, boot_ufs_read, boot_ufs_lseek, boot_ufs_fstat, boot_ufs_closeall, boot_ufs_getdents }; static ino_t find(fileid_t *filep, char *path); static ino_t dlook(fileid_t *filep, char *path); static daddr32_t sbmap(fileid_t *filep, daddr32_t bn); static struct direct *readdir(struct dirinfo *dstuff); /* These are the pools of buffers, etc. */ #define NBUFS (NIADDR+1) /* Compilers like to play with alignment, so force the issue here */ static union { char *blk[NBUFS]; daddr32_t *dummy; } b; daddr32_t blknos[NBUFS]; /* * There is only 1 open (mounted) device at any given time. * So we can keep a single, global devp file descriptor to * use to index into the di[] array. This is not true for the * fi[] array. We can have more than one file open at once, * so there is no global fd for the fi[]. * The user program must save the fd passed back from open() * and use it to do subsequent read()'s. */ static int openi(fileid_t *filep, ino_t inode) { int retval; struct dinode *dp; devid_t *devp = filep->fi_devp; /* Try the inode cache first */ if ((filep->fi_inode = get_icache(devp->di_dcookie, inode)) != NULL) return (0); /* Nope, not there so lets read it off the disk. */ filep->fi_offset = 0; filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs, itod(&devp->un_fs.di_fs, inode)); /* never more than 1 disk block */ filep->fi_count = devp->un_fs.di_fs.fs_bsize; filep->fi_memp = filep->fi_buf; /* Maybe the block is in the disk block cache */ if ((filep->fi_memp = get_bcache(filep)) == NULL) { /* Not in the block cache so read it from disk */ if (retval = set_bcache(filep)) return (retval); lufs_merge_deltas(filep); } dp = (struct dinode *)filep->fi_memp; filep->fi_inode = (struct inode *) bkmem_alloc(sizeof (struct inode)); bzero((char *)filep->fi_inode, sizeof (struct inode)); filep->fi_inode->i_ic = dp[itoo(&devp->un_fs.di_fs, inode)].di_un.di_icom; filep->fi_inode->i_number = inode; if (set_ricache(devp->di_dcookie, inode, (void *)filep->fi_inode, sizeof (struct inode))) filep->fi_inode->i_flag = FI_NOCACHE; return (0); } static fileid_t * find_fp(int fd) { fileid_t *filep = head; if (fd >= 0) { while ((filep = filep->fi_forw) != head) if (fd == filep->fi_filedes) return (filep->fi_taken ? filep : 0); } return (0); } static ino_t find(fileid_t *filep, char *path) { char *q; char c; ino_t inode; char lpath[MAXPATHLEN]; char *lpathp = lpath; int len, r; devid_t *devp; if (path == NULL || *path == '\0') { printf("null path\n"); return ((ino_t)0); } bzero(lpath, sizeof (lpath)); bcopy(path, lpath, strlen(path)); devp = filep->fi_devp; while (*lpathp) { /* if at the beginning of pathname get root inode */ r = (lpathp == lpath); if (r && openi(filep, (ino_t)UFSROOTINO)) return ((ino_t)0); while (*lpathp == '/') lpathp++; /* skip leading slashes */ q = lpathp; while (*q != '/' && *q != '\0') q++; /* find end of component */ c = *q; *q = '\0'; /* terminate component */ /* Bail out early if opening root */ if (r && (*lpathp == '\0')) return ((ino_t)UFSROOTINO); if ((inode = dlook(filep, lpathp)) != 0) { if (openi(filep, inode)) return ((ino_t)0); if ((filep->fi_inode->i_smode & IFMT) == IFLNK) { filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs, filep->fi_inode->i_db[0]); filep->fi_count = DEV_BSIZE; /* check the block cache */ if ((filep->fi_memp = get_bcache(filep)) == NULL) { if (set_bcache(filep)) return ((ino_t)0); lufs_merge_deltas(filep); } len = strlen(filep->fi_memp); if (filep->fi_memp[0] == '/') /* absolute link */ lpathp = lpath; /* copy rest of unprocessed path up */ bcopy(q, lpathp + len, strlen(q + 1) + 2); /* point to unprocessed path */ *(lpathp + len) = c; /* prepend link in before unprocessed path */ bcopy(filep->fi_memp, lpathp, len); lpathp = lpath; continue; } else *q = c; if (c == '\0') break; lpathp = q; continue; } else { return ((ino_t)0); } } return (inode); } /* * Map into a file system block number. * Reads indirect blocks as needed to find the block. Returns zero when * block isn't there; returns negative fsbn when block is uninitialized. */ static daddr32_t sbmap(fileid_t *filep, daddr32_t bn) { struct inode *inodep; int i, j, sh; daddr32_t nb, *bap; daddr32_t *db; devid_t *devp; devp = filep->fi_devp; inodep = filep->fi_inode; db = inodep->i_db; /* * blocks 0..NDADDR are direct blocks */ if (bn < NDADDR) { nb = db[bn]; return (nb); } /* * addresses NIADDR have single and double indirect blocks. * the first step is to determine how many levels of indirection. */ sh = 1; bn -= NDADDR; for (j = NIADDR; j > 0; j--) { sh *= NINDIR(&devp->un_fs.di_fs); if (bn < sh) break; bn -= sh; } if (j == 0) { return ((daddr32_t)0); } /* * fetch the first indirect block address from the inode */ nb = inodep->i_ib[NIADDR - j]; if (nb == 0) { return ((daddr32_t)0); } /* * fetch through the indirect blocks */ for (; j <= NIADDR; j++) { if (blknos[j] != nb) { filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs, nb); filep->fi_count = devp->un_fs.di_fs.fs_bsize; /* First look through the disk block cache */ if ((filep->fi_memp = get_bcache(filep)) == NULL) { if (set_bcache(filep)) /* Gotta do I/O */ return (0); lufs_merge_deltas(filep); } b.blk[j] = filep->fi_memp; blknos[j] = nb; } bap = (daddr32_t *)b.blk[j]; sh /= NINDIR(&devp->un_fs.di_fs); i = (bn / sh) % NINDIR(&devp->un_fs.di_fs); nb = bap[i]; if (nb == 0) { return ((daddr32_t)0); } } return (nb); } static ino_t dlook(fileid_t *filep, char *path) { devid_t *devp = filep->fi_devp; struct direct *dp; struct inode *ip; struct dirinfo dirp; int len; ino_t in; #ifdef DEBUG static int warned = 0; #endif ip = filep->fi_inode; if (path == NULL || *path == '\0') return (0); if ((ip->i_smode & IFMT) != IFDIR) return (0); if (ip->i_size == 0) return (0); len = strlen(path); /* * First look through the directory entry cache */ if ((in = get_dcache(devp->di_dcookie, path, ip->i_number)) != 0) return (in); /* * If the entire directory is cached, return failure */ if (ip->i_flag & FI_CACHED) return (0); /* * Otherwise, read the entire directory into the cache */ in = 0; dirp.loc = 0; dirp.fi = filep; if (!(ip->i_flag & FI_NOCACHE)) ip->i_flag |= FI_CACHED; for (dp = readdir(&dirp); dp != NULL; dp = readdir(&dirp)) { if (dp->d_ino == 0) continue; if (dp->d_namlen == len && strcmp(path, dp->d_name) == 0) in = dp->d_ino; /* * Allow "*" to print all names at that level, w/out match */ if (strcmp(path, "*") == 0) printf("%s\n", dp->d_name); if (ip->i_flag & FI_NOCACHE) continue; /* * Put this entry into the cache. If the entry has been * partially cached, check before inserting. This should be * rare if sized correctly */ if ((ip->i_flag & FI_PARTIAL_CACHE) && (get_dcache(devp->di_dcookie, dp->d_name, dp->d_ino) != 0)) continue; if (set_rdcache(devp->di_dcookie, dp->d_name, ip->i_number, dp->d_ino)) { ip->i_flag &= ~FI_CACHED; ip->i_flag |= FI_PARTIAL_CACHE; #ifdef DEBUG if (!warned) { printf("ufsboot: directory cache too small\n"); warned++; } #endif } } return (in); } /* * get next entry in a directory. */ struct direct * readdir(struct dirinfo *dstuff) { struct direct *dp; fileid_t *filep; daddr32_t lbn, d; int off; devid_t *devp; filep = dstuff->fi; devp = filep->fi_devp; for (;;) { if (dstuff->loc >= filep->fi_inode->i_size) { return (NULL); } off = blkoff(&devp->un_fs.di_fs, dstuff->loc); if (off == 0) { lbn = lblkno(&devp->un_fs.di_fs, dstuff->loc); d = sbmap(filep, lbn); if (d <= 0) return (NULL); filep->fi_blocknum = fsbtodb(&devp->un_fs.di_fs, d); filep->fi_count = blksize(&devp->un_fs.di_fs, filep->fi_inode, lbn); /* check the block cache */ if ((filep->fi_memp = get_bcache(filep)) == NULL) { if (set_bcache(filep)) return (NULL); lufs_merge_deltas(filep); } } dp = (struct direct *)(filep->fi_memp + off); dstuff->loc += dp->d_reclen; if (dp->d_ino == 0) continue; return (dp); } } /* * Get the next block of data from the file. If possible, dma right into * user's buffer */ static int getblock(fileid_t *filep, caddr_t buf, int count, int *rcount) { struct fs *fs; caddr_t p; int off, size, diff, zeroize; daddr32_t lbn, fsbn; devid_t *devp; static int pos; static char ind[] = "|/-\\"; /* that's entertainment? */ static int blks_read; devp = filep->fi_devp; p = filep->fi_memp; if ((signed)filep->fi_count <= 0) { /* find the amt left to be read in the file */ diff = filep->fi_inode->i_size - filep->fi_offset; if (diff <= 0) { printf("Short read\n"); return (-1); } fs = &devp->un_fs.di_fs; /* which block (or frag) in the file do we read? */ lbn = lblkno(fs, filep->fi_offset); /* which physical block on the device do we read? */ fsbn = sbmap(filep, lbn); /* * zero fsbn -> unallocated hole. * negative fsbn -> allocated but uninitialized. * since we only read from the fs, treat both the same. */ zeroize = (fsbn <= 0); filep->fi_blocknum = fsbtodb(fs, fsbn); off = blkoff(fs, filep->fi_offset); /* either blksize or fragsize */ size = blksize(fs, filep->fi_inode, lbn); filep->fi_count = size; filep->fi_memp = filep->fi_buf; /* * optimization if we are reading large blocks of data then * we can go directly to user's buffer */ *rcount = 0; if (off == 0 && count >= size) { filep->fi_memp = buf; if (zeroize) { bzero(buf, size); } else if (diskread(filep)) { return (-1); } *rcount = size; filep->fi_count = 0; read_opt++; if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); return (0); } else { if (zeroize) { bzero(filep->fi_memp, size); } else if (diskread(filep)) return (-1); } /* * round and round she goes (though not on every block.. * - OBP's take a fair bit of time to actually print stuff) * On x86, the screen oriented bootconf program doesn't * want this noise... */ if ((blks_read++ & 0x3) == 0) printf("%c\b", ind[pos++ & 3]); if (filep->fi_offset - off + size >= filep->fi_inode->i_size) filep->fi_count = diff + off; filep->fi_count -= off; p = &filep->fi_memp[off]; } filep->fi_memp = p; return (0); } /* * This is the high-level read function. It works like this. * We assume that our IO device buffers up some amount of * data and that we can get a ptr to it. Thus we need * to actually call the device func about filesize/blocksize times * and this greatly increases our IO speed. When we already * have data in the buffer, we just return that data (with bcopy() ). */ static ssize_t boot_ufs_read(int fd, caddr_t buf, size_t count) { size_t i, j; caddr_t n; int rcount; fileid_t *filep; if (!(filep = find_fp(fd))) { return (-1); } if (filep->fi_offset + count > filep->fi_inode->i_size) count = filep->fi_inode->i_size - filep->fi_offset; /* that was easy */ if ((i = count) == 0) return (0); n = buf; while (i > 0) { /* If we need to reload the buffer, do so */ if ((j = filep->fi_count) == 0) { (void) getblock(filep, buf, i, &rcount); i -= rcount; buf += rcount; filep->fi_offset += rcount; } else { /* else just bcopy from our buffer */ j = MIN(i, j); bcopy(filep->fi_memp, buf, (unsigned)j); buf += j; filep->fi_memp += j; filep->fi_offset += j; filep->fi_count -= j; i -= j; } } return (buf - n); } /* * This routine will open a device as it is known by the V2 OBP. * Interface Defn: * err = boot_ufs_mountroot(string); * err = 0 on success * err = -1 on failure * string: char string describing the properties of the device. * We must not dork with any fi[]'s here. Save that for later. */ static int boot_ufs_mountroot(char *str) { int h; /* * Open the device and setup the read of the ufs superblock * only the first time mountroot is called. Subsequent calls * to mountroot succeed immediatly */ if (ufs_devp == NULL) { /* * Encode the knowledge that we normally boot from the 'a' * slice of the leaf device on the OBP path; we also permit * a 'nolabel' device, i.e. the entire device. Since v2path * points to 'str' as well, changing str should have the * desired result. */ if (strchr(str, ':') == NULL) { (void) strcat(str, ":a"); } h = prom_open(str); if (h == 0) { printf("Cannot open %s\n", str); return (-1); } ufs_devp = (devid_t *)bkmem_alloc(sizeof (devid_t)); ufs_devp->di_taken = 1; ufs_devp->di_dcookie = h; ufs_devp->di_desc = (char *)bkmem_alloc(strlen(str) + 1); (void) strcpy(ufs_devp->di_desc, str); bzero(ufs_devp->un_fs.dummy, SBSIZE); head = (fileid_t *)bkmem_alloc(sizeof (fileid_t)); head->fi_back = head->fi_forw = head; head->fi_filedes = 0; head->fi_taken = 0; /* Setup read of the superblock */ head->fi_devp = ufs_devp; head->fi_blocknum = SBLOCK; head->fi_count = (uint_t)SBSIZE; head->fi_memp = (caddr_t)&(ufs_devp->un_fs.di_fs); head->fi_offset = 0; if (diskread(head) || ufs_devp->un_fs.di_fs.fs_magic != FS_MAGIC) { boot_ufs_closeall(1); return (-1); } lufs_boot_init(head); } return (0); } /* * Unmount the currently mounted root fs. In practice, this means * closing all open files and releasing resources. All of this * is done by boot_ufs_closeall(). */ int boot_ufs_unmountroot(void) { if (ufs_devp == NULL) return (-1); boot_ufs_closeall(1); return (0); } /* * We allocate an fd here for use when talking * to the file itself. */ /*ARGSUSED*/ static int boot_ufs_open(char *filename, int flags) { fileid_t *filep; ino_t inode; static int filedes = 1; /* build and link a new file descriptor */ filep = (fileid_t *)bkmem_alloc(sizeof (fileid_t)); filep->fi_back = head->fi_back; filep->fi_forw = head; head->fi_back->fi_forw = filep; head->fi_back = filep; filep->fi_filedes = filedes++; filep->fi_taken = 1; filep->fi_path = (char *)bkmem_alloc(strlen(filename) + 1); (void) strcpy(filep->fi_path, filename); filep->fi_devp = ufs_devp; /* dev is already "mounted" */ filep->fi_inode = NULL; bzero(filep->fi_buf, MAXBSIZE); inode = find(filep, filename); if (inode == (ino_t)0) { (void) boot_ufs_close(filep->fi_filedes); return (-1); } if (openi(filep, inode)) { (void) boot_ufs_close(filep->fi_filedes); return (-1); } filep->fi_offset = filep->fi_count = 0; return (filep->fi_filedes); } /* * We don't do any IO here. * We just play games with the device pointers. */ static off_t boot_ufs_lseek(int fd, off_t addr, int whence) { fileid_t *filep; /* Make sure user knows what file they're talking to */ if (!(filep = find_fp(fd))) return (-1); switch (whence) { case SEEK_CUR: filep->fi_offset += addr; break; case SEEK_SET: filep->fi_offset = addr; break; default: case SEEK_END: printf("ufs_lseek(): invalid whence value %d\n", whence); break; } filep->fi_blocknum = addr / DEV_BSIZE; filep->fi_count = 0; return (0); } /* * ufs_fstat() only supports size, mode, and times at present time. */ static int boot_ufs_fstat(int fd, struct bootstat *stp) { fileid_t *filep; struct inode *ip; if (!(filep = find_fp(fd))) return (-1); ip = filep->fi_inode; stp->st_mode = 0; stp->st_size = 0; if (ip == NULL) return (0); switch (ip->i_smode & IFMT) { case IFDIR: stp->st_mode = S_IFDIR; break; case IFLNK: stp->st_mode = S_IFLNK; break; case IFREG: stp->st_mode = S_IFREG; break; default: break; } stp->st_size = ip->i_size; stp->st_atim.tv_sec = ip->i_atime.tv_sec; stp->st_atim.tv_nsec = ip->i_atime.tv_usec * 1000; stp->st_mtim.tv_sec = ip->i_mtime.tv_sec; stp->st_mtim.tv_nsec = ip->i_mtime.tv_usec * 1000; stp->st_ctim.tv_sec = ip->i_ctime.tv_sec; stp->st_ctim.tv_nsec = ip->i_ctime.tv_usec * 1000; return (0); } static int boot_ufs_close(int fd) { fileid_t *filep; /* Make sure user knows what file they're talking to */ if (!(filep = find_fp(fd))) return (-1); if (filep->fi_taken && (filep != head)) { /* Clear the ranks */ bkmem_free(filep->fi_path, strlen(filep->fi_path)+1); filep->fi_blocknum = filep->fi_count = filep->fi_offset = 0; filep->fi_memp = (caddr_t)0; filep->fi_devp = 0; filep->fi_taken = 0; /* unlink and deallocate node */ filep->fi_forw->fi_back = filep->fi_back; filep->fi_back->fi_forw = filep->fi_forw; bkmem_free((char *)filep, sizeof (fileid_t)); return (0); } else { /* Big problem */ printf("\nFile descrip %d not allocated!", fd); return (-1); } } /* closeall is now idempotent */ /*ARGSUSED*/ static void boot_ufs_closeall(int flag) { fileid_t *filep = head; if (ufs_devp == NULL) { if (head) prom_panic("boot_ufs_closeall: head != NULL.\n"); return; } while ((filep = filep->fi_forw) != head) if (filep->fi_taken) if (boot_ufs_close(filep->fi_filedes)) prom_panic("Filesystem may be inconsistent.\n"); release_cache(ufs_devp->di_dcookie); (void) prom_close(ufs_devp->di_dcookie); ufs_devp->di_taken = 0; if (verbosemode & print_cache_stats) print_cache_data(); lufs_closeall(); bkmem_free((char *)ufs_devp, sizeof (devid_t)); bkmem_free((char *)head, sizeof (fileid_t)); ufs_devp = (devid_t *)NULL; head = (fileid_t *)NULL; } static int boot_ufs_getdents(int fd, struct dirent *dep, unsigned size) { /* * Read directory entries from the file open on "fd" into the * "size"-byte buffer at "dep" until the buffer is exhausted * or we reach EOF on the directory. Returns the number of * entries read. */ int n; fileid_t *fp; unsigned long oldoff, oldblok; #define SLOP (sizeof (struct dirent) - offsetof(struct dirent, d_name[1])) if (fp = find_fp(fd)) { /* * File is open, check type to make sure it's a directory. */ while ((fp->fi_inode->i_smode & IFMT) == IFLNK) { /* * If file is a symbolic link, we'll follow * it JIC it points to a directory! */ fileid_t fx; char pn[MAXPATHLEN]; fp->fi_count = DEV_BSIZE; fp->fi_blocknum = fsbtodb(&fp->fi_devp->un_fs.di_fs, fp->fi_inode->i_db[0]); /* * Return failure if: * (a) we get an I/O error reading the path name. * (b) the path name points to a non-existant file, * (c) we get an I/O error reading the target inode. */ if ((fp->fi_memp = get_bcache(fp)) == NULL) { if (set_bcache(fp)) return (-1); lufs_merge_deltas(fp); } if (!(n = find(&fx, strcpy(pn, fp->fi_memp))) || openi(fp = &fx, n)) { return (-1); } } if ((fp->fi_inode->i_smode & IFMT) == IFDIR) { /* * If target file is a directory, go ahead * and read it. This consists of making * repeated calls to readdir() until we reach * end-of-file or run out of buffer space. */ int cnt = 0; struct direct *dp; struct dirinfo dir; dir.fi = fp; oldblok = fp->fi_blocknum; dir.loc = oldoff = fp->fi_offset; for (dp = readdir(&dir); dp; dp = readdir(&dir)) { /* * Read all directory entries in the file ... */ if (dp->d_ino) { /* * Next entry is valid. * Compute name length and * break loop if there's not * enough space in the output * buffer for the next entry. * * NOTE: "SLOP" is the number * of bytes inserted into the * dirent struct's "d_name" * field by the compiler to * preserve alignment. */ dep->d_ino = dp->d_ino; n = strlen(dp->d_name); n = roundup((sizeof (struct dirent) + ((n > SLOP) ? n : 0)), sizeof (off_t)); if (n > size) break; /* user buffer is full */ oldblok = fp->fi_blocknum; oldoff = dir.loc; size -= n; cnt += 1; (void) strlcpy(dep->d_name, dp->d_name, strlen(dp->d_name) + 1); dep->d_off = dir.loc; dep->d_reclen = (ushort_t)n; dep = (struct dirent *) ((char *)dep + n); } } /* * Remember where we left off for next time */ fp->fi_blocknum = oldblok; fp->fi_offset = oldoff; return (cnt); } } #undef SLOP return (-1); } # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # LIBRARY = libinet.a LOCOBJS = ipv4.o icmp4.o udp.o mac.o ethernet.o dhcpv4.o ibd.o CMNOBJS = ipv4_sum.o udp_sum.o octet.o scan.o dhcpinfo.o OBJECTS = $(LOCOBJS) $(CMNOBJS) include ../Makefile.com CMNDIR = $(CMNNETDIR)/dhcp SRCS = $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(CMNOBJS:%.o=$(CMNDIR)/%.c) LDLIBS += -lsock CPPFLAGS += $(SOCKCPPFLAGS) -I$(TOPDIR)/psm/stand CERRWARN += -Wno-char-subscripts CERRWARN += $(CNOWARN_UNINIT) include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1999, Sun Microsystems, Inc. * * ATM implementation-specific definitions */ #ifndef _ATM_INET_H #define _ATM_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define ATMSIZE (4500) /* Default ATM MTU size */ #define ATM_ARP_TIMEOUT (300000) /* in milliseconds */ #define ATM_IN_TIMEOUT (4) /* milliseconds wait for IP input */ #ifdef __cplusplus } #endif #endif /* _ATM_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Standalone dhcp client. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ipv4.h" #include "mac.h" #include #include "dhcpv4.h" static char *s_n = "INIT"; static enum DHCPSTATE dhcp_state = INIT; static PKT *dhcp_snd_bufp, *dhcp_rcv_bufp; static int dhcp_buf_size; static const uint8_t magic[] = BOOTMAGIC; /* RFC1048 */ static uint8_t opt_discover[] = { CD_DHCP_TYPE, 1, DISCOVER }; static uint8_t opt_request[] = { CD_DHCP_TYPE, 1, REQUEST }; static uint8_t opt_decline[] = { CD_DHCP_TYPE, 1, DECLINE }; static uint8_t dhcp_classid[DHCP_MAX_OPT_SIZE + 3]; static uint8_t dhcp_clientid[DHCP_MAX_CID_LEN]; static uint8_t dhcp_clientid_len = 0; static uint32_t dhcp_start_time; /* start time (msecs */ static time_t dhcp_secs; static uint32_t timeout; /* timeout in milliseconds */ static int pkt_counter; PKT_LIST *list_tl, *list_hd; PKT_LIST *state_pl = NULL; #define PROM_BOOT_CACHED "bootp-response" extern char *bootp_response; /* bootprop.c */ extern int pagesize; /* * Do whatever reset actions/initialization actions are generic for every * DHCP/bootp message. Set the message type. * * Returns: the updated options ptr. */ static uint8_t * init_msg(PKT *pkt, uint8_t *pkttype) { static uint32_t xid; bzero(pkt, dhcp_buf_size); bcopy(magic, pkt->cookie, sizeof (pkt->cookie)); pkt->op = BOOTREQUEST; if (xid == 0) bcopy(mac_get_addr_buf()+2, &xid, 4); else xid++; pkt->xid = xid; bcopy(pkttype, pkt->options, 3); return ((uint8_t *)(pkt->options + 3)); } /* * Parameter request list. */ static void parameter_request_list(uint8_t **opt) { /* * This parameter request list is used in the normal 4-packet * DHCPDISCOVER/OFFER/REQUEST/ACK exchange; it must not contain * CD_REQUESTED_IP_ADDR or CD_LEASE_TIME. */ static uint8_t prlist[] = { CD_REQUEST_LIST, /* parameter request list option number */ 4, /* number of options requested */ CD_SUBNETMASK, CD_ROUTER, CD_HOSTNAME, CD_VENDOR_SPEC }; if (opt && *opt) { bcopy(prlist, *opt, sizeof (prlist)); *opt += sizeof (prlist); } } /* * Set hardware specific fields */ static void set_hw_spec_data(PKT *p, uint8_t **opt, uint8_t *pkttype) { char mfg[DHCP_MAX_OPT_SIZE + 1], cbuf[DHCP_MAX_OPT_SIZE + 1]; uint8_t *tp, *dp; int adjust_len, len, i; p->htype = mac_arp_type(mac_get_type()); len = (uchar_t)mac_get_addr_len(); if (len <= sizeof (p->chaddr)) { p->hlen = len; bcopy(mac_get_addr_buf(), p->chaddr, len); } else { uint8_t type = *(pkttype + 2); /* * The mac address does not fit in the chaddr * field, thus it can not be sent to the server, * thus server can not unicast the reply. Per * RFC 2131 4.4.1, client can set this bit in * DISCOVER/REQUEST. */ if ((type == DISCOVER) || (type == REQUEST)) p->flags = htons(BCAST_MASK); } if (opt && *opt) { if (dhcp_classid[0] == '\0') { /* * Classids based on mfg name: Commas (,) are * converted to periods (.), and spaces ( ) are removed. */ dhcp_classid[0] = CD_CLASS_ID; (void) strncpy(mfg, get_mfg_name(), sizeof (mfg)); if (strncmp(mfg, "SUNW", strlen("SUNW")) != 0) { len = strlen("SUNW."); (void) strcpy(cbuf, "SUNW."); } else { len = 0; cbuf[0] = '\0'; } len += strlen(mfg); if ((len + 2) < DHCP_MAX_OPT_SIZE) { tp = (uint8_t *)strcat(cbuf, mfg); dp = &dhcp_classid[2]; adjust_len = 0; for (i = 0; i < len; i++, tp++) { if (*tp == ',') { *dp++ = '.'; } else if (*tp == ' ') { adjust_len++; } else { *dp++ = *tp; } } len -= adjust_len; dhcp_classid[1] = (uint8_t)len; } else prom_panic("Not enough space for class id"); #ifdef DHCP_DEBUG printf("%s: Classid: %s\n", s_n, &dhcp_classid[2]); #endif /* DHCP_DEBUG */ } bcopy(dhcp_classid, *opt, dhcp_classid[1] + 2); *opt += dhcp_classid[1] + 2; } } static void flush_list(void) { PKT_LIST *wk, *tmp; wk = list_hd; while (wk != NULL) { tmp = wk; wk = wk->next; bkmem_free((char *)tmp->pkt, tmp->len); bkmem_free((char *)tmp, sizeof (PKT_LIST)); } list_hd = list_tl = NULL; pkt_counter = 0; } static void remove_list(PKT_LIST *pl, int flag) { if (list_hd == NULL) return; if (list_hd == list_tl) { list_hd = list_tl = NULL; } else if (list_hd == pl) { list_hd = pl->next; list_hd->prev = NULL; } else if (list_tl == pl) { list_tl = list_tl->prev; list_tl->next = NULL; } else { pl->prev->next = pl->next; pl->next->prev = pl->prev; } pkt_counter--; if (flag) { bkmem_free((char *)pl->pkt, pl->len); bkmem_free((char *)pl, sizeof (PKT_LIST)); } } /* * Collects BOOTP responses. Length has to be right, it has to be * a BOOTP reply pkt, with the same XID and HW address as ours. Adds * them to the pkt list. * * Returns 0 if no error processing packet, 1 if an error occurred and/or * collection of replies should stop. Used in inet() calls. */ static int bootp_collect(int len) { PKT *s = (PKT *)dhcp_snd_bufp; PKT *r = (PKT *)dhcp_rcv_bufp; PKT_LIST *pl; if (len < sizeof (PKT)) { dprintf("%s: BOOTP reply too small: %d\n", s_n, len); return (1); } if (r->op == BOOTREPLY && r->xid == s->xid && bcmp((caddr_t)s->chaddr, (caddr_t)r->chaddr, s->hlen) == 0) { /* Add a packet to the pkt list */ if (pkt_counter > (MAX_PKT_LIST - 1)) return (1); /* got enough packets already */ if (((pl = (PKT_LIST *)bkmem_zalloc(sizeof (PKT_LIST))) == NULL) || ((pl->pkt = (PKT *)bkmem_zalloc(len)) == NULL)) { errno = ENOMEM; if (pl != NULL) bkmem_free((char *)pl, sizeof (PKT_LIST)); return (1); } bcopy(dhcp_rcv_bufp, pl->pkt, len); pl->len = len; if (list_hd == NULL) { list_hd = list_tl = pl; pl->prev = NULL; } else { list_tl->next = pl; pl->prev = list_tl; list_tl = pl; } pkt_counter++; pl->next = NULL; } return (0); } /* * Checks if BOOTP exchange(s) were successful. Returns 1 if they * were, 0 otherwise. Used in inet() calls. */ static int bootp_success(void) { PKT *s = (PKT *)dhcp_snd_bufp; if (list_hd != NULL) { /* remember the secs - we may need them later */ dhcp_secs = ntohs(s->secs); return (1); } s->secs = htons((uint16_t)((prom_gettime() - dhcp_start_time)/1000)); return (0); } /* * This function accesses the network. Opens a connection, and binds to * it if a client binding doesn't already exist. If 'tries' is 0, then * no reply is expected/returned. If 'tries' is non-zero, then 'tries' * attempts are made to get a valid response. If 'tol' is not zero, * then this function will wait for 'tol' milliseconds for more than one * response to a transmit. * * Returns 0 for success, errno otherwise. */ static int inet(uint32_t size, struct in_addr *src, struct in_addr *dest, uint32_t tries, uint32_t tol) { int done = B_FALSE, flags, len; uint32_t attempts = 0; int sd; uint32_t wait_time; /* Max time collect replies */ uint32_t init_timeout; /* Max time wait ANY reply */ uint32_t now; struct sockaddr_in saddr, daddr; if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { dprintf("%s: Can't open a socket.\n", s_n); return (errno); } flags = 0; bzero(&saddr, sizeof (struct sockaddr_in)); saddr.sin_family = AF_INET; saddr.sin_port = htons(IPPORT_BOOTPC); saddr.sin_addr.s_addr = htonl(src->s_addr); if (bind(sd, (struct sockaddr *)&saddr, sizeof (saddr)) < 0) { dprintf("%s: Cannot bind to port %d, errno: %d\n", s_n, IPPORT_BOOTPC, errno); (void) socket_close(sd); return (errno); } if (ntohl(dest->s_addr) == INADDR_BROADCAST) { int dontroute = B_TRUE; (void) setsockopt(sd, SOL_SOCKET, SO_DONTROUTE, (const void *)&dontroute, sizeof (dontroute)); } bzero(&daddr, sizeof (struct sockaddr_in)); daddr.sin_family = AF_INET; daddr.sin_port = htons(IPPORT_BOOTPS); daddr.sin_addr.s_addr = htonl(dest->s_addr); wait_time = prom_gettime() + tol; do { if (sendto(sd, (char *)dhcp_snd_bufp, size, flags, (struct sockaddr *)&daddr, sizeof (daddr)) < 0) { dprintf("%s: sendto failed with errno: %d\n", s_n, errno); (void) socket_close(sd); return (errno); } if (!tries) break; /* don't bother to check for reply */ now = prom_gettime(); if (timeout == 0) timeout = 4000; else { timeout <<= 1; if (timeout > 64000) timeout = 64000; } init_timeout = now + timeout; wait_time = now + tol; do { if ((len = recvfrom(sd, (char *)dhcp_rcv_bufp, (int)dhcp_buf_size, MSG_DONTWAIT, NULL, NULL)) < 0) { if (errno == EWOULDBLOCK) continue; /* DONT WAIT */ (void) socket_close(sd); flush_list(); return (errno); } if (bootp_collect(len)) break; /* Stop collecting */ if (tol != 0) { if (wait_time < prom_gettime()) break; /* collection timeout */ } } while (prom_gettime() < init_timeout); if (bootp_success()) { done = B_TRUE; break; /* got the goods */ } } while (++attempts < tries); (void) socket_close(sd); return (done ? 0 : DHCP_NO_DATA); } /* * Print the message from the server. */ static void prt_server_msg(DHCP_OPT *p) { int len = p->len; char scratch[DHCP_MAX_OPT_SIZE + 1]; if (len > DHCP_MAX_OPT_SIZE) len = DHCP_MAX_OPT_SIZE; bcopy(p->value, scratch, len); scratch[len] = '\0'; printf("%s: Message from server: '%s'\n", s_n, scratch); } /* * This function scans the list of OFFERS, and returns the "best" offer. * The criteria used for determining this is: * * The best: * DHCP OFFER (not BOOTP), same client_id as ours, same class_id, * Longest lease, all the options we need. * * Not quite as good: * DHCP OFFER, no class_id, short lease, only some of the options we need. * * We're really reach'in * BOOTP reply. * * DON'T select an offer from a server that gave us a configuration we * couldn't use. Take this server off the "bad" list when this is done. * Next time, we could potentially retry this server's configuration. * * NOTE: perhaps this bad server should have a counter associated with it. */ static PKT_LIST * select_best(void) { PKT_LIST *wk, *tk, *best; int err = 0; /* Pass one. Scan for options, set appropriate opt field. */ wk = list_hd; while (wk != NULL) { if ((err = dhcp_options_scan(wk, B_TRUE)) != 0) { /* Garbled Options. Nuke this pkt. */ if (boothowto & RB_DEBUG) { switch (err) { case DHCP_WRONG_MSG_TYPE: printf("%s: Unexpected DHCP message.\n", s_n); break; case DHCP_GARBLED_MSG_TYPE: printf( "%s: Garbled DHCP message type.\n", s_n); break; case DHCP_BAD_OPT_OVLD: printf("%s: Bad option overload.\n", s_n); break; } } tk = wk; wk = wk->next; remove_list(tk, B_TRUE); continue; } wk = wk->next; } /* * Pass two. Pick out the best offer. Point system. * What's important? * 0) DHCP * 1) No option overload * 2) Encapsulated vendor option * 3) Non-null sname and siaddr fields * 4) Non-null file field * 5) Hostname * 6) Subnetmask * 7) Router */ best = NULL; for (wk = list_hd; wk != NULL; wk = wk->next) { wk->offset = 0; if (wk->opts[CD_DHCP_TYPE] && wk->opts[CD_DHCP_TYPE]->len == 1) { if (*wk->opts[CD_DHCP_TYPE]->value != OFFER) { dprintf("%s: Unexpected DHCP message." " Expected OFFER message.\n", s_n); continue; } if (!wk->opts[CD_LEASE_TIME]) { dprintf("%s: DHCP OFFER message without lease " "time parameter.\n", s_n); continue; } else { if (wk->opts[CD_LEASE_TIME]->len != 4) { dprintf("%s: Lease expiration time is " "garbled.\n", s_n); continue; } } if (!wk->opts[CD_SERVER_ID]) { dprintf("%s: DHCP OFFER message without server " "id parameter.\n", s_n); continue; } else { if (wk->opts[CD_SERVER_ID]->len != 4) { dprintf("%s: Server identifier " "parameter is garbled.\n", s_n); continue; } } /* Valid DHCP OFFER. See if we got our parameters. */ dprintf("%s: Found valid DHCP OFFER message.\n", s_n); wk->offset += 30; /* * Also could be faked, though more difficult * because the encapsulation is hard to encode * on a BOOTP server; plus there's not as much * real estate in the packet for options, so * it's likely this option would get dropped. */ if (wk->opts[CD_VENDOR_SPEC]) wk->offset += 80; } else dprintf("%s: Found valid BOOTP reply.\n", s_n); /* * RFC1048 BOOTP? */ if (bcmp((caddr_t)wk->pkt->cookie, (caddr_t)magic, sizeof (magic)) == 0) { wk->offset += 5; if (wk->opts[CD_SUBNETMASK]) wk->offset++; if (wk->opts[CD_ROUTER]) wk->offset++; if (wk->opts[CD_HOSTNAME]) wk->offset += 5; /* * Prefer options that have diskless boot significance */ if (ntohl(wk->pkt->siaddr.s_addr) != INADDR_ANY) wk->offset += 10; /* server ip */ if (wk->opts[CD_OPTION_OVERLOAD] == NULL) { if (wk->pkt->sname[0] != '\0') wk->offset += 10; /* server name */ if (wk->pkt->file[0] != '\0') wk->offset += 5; /* File to load */ } } #ifdef DHCP_DEBUG printf("%s: This server configuration has '%d' points.\n", s_n, wk->offset); #endif /* DHCP_DEBUG */ if (!best) best = wk; else { if (best->offset < wk->offset) best = wk; } } if (best) { #ifdef DHCP_DEBUG printf("%s: Found best: points: %d\n", s_n, best->offset); #endif /* DHCP_DEBUG */ remove_list(best, B_FALSE); } else { dprintf("%s: No valid BOOTP reply or DHCP OFFER was found.\n", s_n); } flush_list(); /* toss the remaining list */ return (best); } /* * Send a decline message to the generator of the DHCPACK. */ static void dhcp_decline(char *msg, PKT_LIST *pl) { PKT *pkt; uint8_t *opt, ulen; int pkt_size; struct in_addr nets, ours, t_server, t_yiaddr; if (pl != NULL) { if (pl->opts[CD_SERVER_ID] != NULL && pl->opts[CD_SERVER_ID]->len == sizeof (struct in_addr)) { bcopy(pl->opts[CD_SERVER_ID]->value, &t_server, pl->opts[CD_SERVER_ID]->len); } else t_server.s_addr = htonl(INADDR_BROADCAST); t_yiaddr.s_addr = pl->pkt->yiaddr.s_addr; } pkt = (PKT *)dhcp_snd_bufp; opt = init_msg(pkt, opt_decline); set_hw_spec_data(pkt, &opt, opt_decline); *opt++ = CD_SERVER_ID; *opt++ = sizeof (struct in_addr); bcopy(&t_server, opt, sizeof (struct in_addr)); opt += sizeof (struct in_addr); nets.s_addr = htonl(INADDR_BROADCAST); /* * Use the given yiaddr in our ciaddr field so server can identify us. */ pkt->ciaddr.s_addr = t_yiaddr.s_addr; ipv4_getipaddr(&ours); /* Could be 0, could be yiaddr */ ours.s_addr = htonl(ours.s_addr); ulen = (uint8_t)strlen(msg); *opt++ = CD_MESSAGE; *opt++ = ulen; bcopy(msg, opt, ulen); opt += ulen; *opt++ = CD_END; pkt_size = (uint8_t *)opt - (uint8_t *)pkt; if (pkt_size < sizeof (PKT)) pkt_size = sizeof (PKT); timeout = 0; /* reset timeout */ (void) inet(pkt_size, &ours, &nets, 0, 0L); } /* * Implementings SELECTING state of DHCP client state machine. */ static int dhcp_selecting(void) { int pkt_size; PKT *pkt; uint8_t *opt; uint16_t size; uint32_t lease; struct in_addr nets, ours; pkt = (PKT *)dhcp_snd_bufp; opt = init_msg(pkt, opt_discover); pkt->secs = htons((uint16_t)((prom_gettime() - dhcp_start_time)/1000)); *opt++ = CD_MAX_DHCP_SIZE; *opt++ = sizeof (size); size = (uint16_t)(dhcp_buf_size - sizeof (struct ip) - sizeof (struct udphdr)); size = htons(size); bcopy(&size, opt, sizeof (size)); opt += sizeof (size); set_hw_spec_data(pkt, &opt, opt_discover); *opt++ = CD_LEASE_TIME; *opt++ = sizeof (lease); lease = htonl(DHCP_PERM); /* ask for a permanent lease */ bcopy(&lease, opt, sizeof (lease)); opt += sizeof (lease); /* * If a clientid was set using dhcp_set_client_id(), add this * to the options. */ if (dhcp_clientid_len > 0) { *opt++ = CD_CLIENT_ID; *opt++ = dhcp_clientid_len; bcopy(dhcp_clientid, opt, dhcp_clientid_len); opt += dhcp_clientid_len; } parameter_request_list(&opt); *opt++ = CD_END; pkt_size = (uint8_t *)opt - (uint8_t *)pkt; if (pkt_size < sizeof (PKT)) pkt_size = sizeof (PKT); nets.s_addr = INADDR_BROADCAST; ours.s_addr = INADDR_ANY; timeout = 0; /* reset timeout */ return (inet(pkt_size, &ours, &nets, DHCP_RETRIES, DHCP_WAIT)); } /* * implements the REQUESTING state of the DHCP client state machine. */ static int dhcp_requesting(void) { PKT_LIST *pl, *wk; PKT *pkt, *pl_pkt; uint8_t *opt; int pkt_size, err; uint32_t t_time; struct in_addr nets, ours; DHCP_OPT *doptp; uint16_t size; /* here we scan the list of OFFERS, select the best one. */ state_pl = NULL; if ((pl = select_best()) == NULL) { dprintf("%s: No valid BOOTP reply or DHCP OFFER was found.\n", s_n); return (1); } pl_pkt = pl->pkt; /* * Check to see if we got an OFFER pkt(s). If not, then We only got * a response from a BOOTP server. We'll go to the bound state and * try to use that configuration. */ if (pl->opts[CD_DHCP_TYPE] == NULL) { if (mac_call_arp(&pl_pkt->yiaddr, NULL, DHCP_ARP_TIMEOUT)) { /* Someone responded! go back to SELECTING state. */ printf("%s: Some host already using BOOTP %s.\n", s_n, inet_ntoa(pl_pkt->yiaddr)); bkmem_free((char *)pl->pkt, pl->len); bkmem_free((char *)pl, sizeof (PKT_LIST)); return (1); } state_pl = pl; return (0); } /* * if we got a message from the server, display it. */ if (pl->opts[CD_MESSAGE]) prt_server_msg(pl->opts[CD_MESSAGE]); /* * Assemble a DHCPREQUEST, with the ciaddr field set to 0, since we * got here from DISCOVER state. Keep secs field the same for relay * agents. We start with the DHCPOFFER packet we got, and the * options contained in it to make a requested option list. */ pkt = (PKT *)dhcp_snd_bufp; opt = init_msg(pkt, opt_request); /* Time from Successful DISCOVER message. */ pkt->secs = htons((uint16_t)dhcp_secs); size = (uint16_t)(dhcp_buf_size - sizeof (struct ip) - sizeof (struct udphdr)); size = htons(size); *opt++ = CD_MAX_DHCP_SIZE; *opt++ = sizeof (size); bcopy(&size, opt, sizeof (size)); opt += sizeof (size); set_hw_spec_data(pkt, &opt, opt_request); *opt++ = CD_SERVER_ID; *opt++ = pl->opts[CD_SERVER_ID]->len; bcopy(pl->opts[CD_SERVER_ID]->value, opt, pl->opts[CD_SERVER_ID]->len); opt += pl->opts[CD_SERVER_ID]->len; /* our offered lease minus boot time */ *opt++ = CD_LEASE_TIME; *opt++ = 4; bcopy(pl->opts[CD_LEASE_TIME]->value, &t_time, sizeof (t_time)); t_time = ntohl(t_time); if ((uint32_t)t_time != DHCP_PERM) t_time -= (uint32_t)dhcp_secs; t_time = htonl(t_time); bcopy(&t_time, opt, sizeof (t_time)); opt += sizeof (t_time); /* our offered IP address, as required. */ *opt++ = CD_REQUESTED_IP_ADDR; *opt++ = sizeof (struct in_addr); bcopy(&pl_pkt->yiaddr, opt, sizeof (struct in_addr)); opt += sizeof (struct in_addr); /* * If a clientid was set using dhcp_set_client_id(), add this * to the options. */ if (dhcp_clientid_len > 0) { *opt++ = CD_CLIENT_ID; *opt++ = dhcp_clientid_len; bcopy(dhcp_clientid, opt, dhcp_clientid_len); opt += dhcp_clientid_len; } parameter_request_list(&opt); *opt++ = CD_END; /* Done with the OFFER pkt. */ bkmem_free((char *)pl->pkt, pl->len); bkmem_free((char *)pl, sizeof (PKT_LIST)); /* * We make 4 attempts here. We wait for 2 seconds to accumulate * requests, just in case a BOOTP server is too fast! */ pkt_size = (uint8_t *)opt - (uint8_t *)pkt; if (pkt_size < sizeof (PKT)) pkt_size = sizeof (PKT); nets.s_addr = INADDR_BROADCAST; ours.s_addr = INADDR_ANY; timeout = 0; /* reset timeout */ if ((err = inet(pkt_size, &ours, &nets, 4, (time_t)2L)) != 0) return (err); for (wk = list_hd; wk != NULL && state_pl == NULL; wk = wk->next) { if (dhcp_options_scan(wk, B_TRUE) != 0 || !wk->opts[CD_DHCP_TYPE]) continue; /* garbled options */ switch (*wk->opts[CD_DHCP_TYPE]->value) { case ACK: remove_list(wk, B_FALSE); state_pl = wk; break; case NAK: printf("%s: rejected by DHCP server: %s\n", s_n, inet_ntoa(*((struct in_addr *)wk-> opts[CD_SERVER_ID]->value))); if (wk->opts[CD_MESSAGE]) prt_server_msg(wk->opts[CD_MESSAGE]); break; default: dprintf("%s: Unexpected DHCP message type.\n", s_n); break; } } flush_list(); if (state_pl != NULL) { if (state_pl->opts[CD_MESSAGE]) prt_server_msg(state_pl->opts[CD_MESSAGE]); pl_pkt = state_pl->pkt; /* arp our new address, just to make sure */ if (!mac_call_arp(&pl_pkt->yiaddr, NULL, DHCP_ARP_TIMEOUT)) { /* * No response. Check if lease is ok. */ doptp = state_pl->opts[CD_LEASE_TIME]; if (state_pl->opts[CD_DHCP_TYPE] && (!doptp || (doptp->len % 4) != 0)) { dhcp_decline("Missing or corrupted lease time", state_pl); err++; } } else { dhcp_decline("IP Address already being used!", state_pl); err++; } if (err) { bkmem_free((char *)state_pl->pkt, state_pl->len); bkmem_free((char *)state_pl, sizeof (PKT_LIST)); state_pl = NULL; } else return (0); /* passes the tests! */ } dprintf("%s: No valid DHCP acknowledge messages received.\n", s_n); return (1); } /* * Implements BOUND state of DHCP client state machine. */ static int dhcp_bound(void) { PKT *pl_pkt = state_pl->pkt; DHCP_OPT *doptp; uint8_t *tp, *hp; int items, i, fnd, k; char hostname[MAXHOSTNAMELEN+1]; struct in_addr subnet, defr, savr, *ipp, xip; #ifdef DHCP_DEBUG if (dhcp_classid[0] != 0) { char scratch[DHCP_MAX_OPT_SIZE + 1]; bcopy(&dhcp_classid[2], scratch, dhcp_classid[1]); scratch[dhcp_classid[1]] = '\0'; printf("Your machine is of the class: '%s'.\n", scratch); } #endif /* DHCP_DEBUG */ /* First, set the bare essentials. (IP layer parameters) */ ipv4_getipaddr(&xip); if (xip.s_addr != INADDR_ANY) ipp = &xip; else { ipp = &pl_pkt->yiaddr; ipp->s_addr = ntohl(ipp->s_addr); ipv4_setipaddr(ipp); } ipp->s_addr = htonl(ipp->s_addr); if (boothowto & RB_VERBOSE) printf("%s: IP address is: %s\n", s_n, inet_ntoa(*ipp)); /* * Ensure that the Boot NFS READ size, if given, is an int16_t. */ if (state_pl->vs[VS_BOOT_NFS_READSIZE] != NULL) { doptp = state_pl->vs[VS_BOOT_NFS_READSIZE]; if (doptp->len != sizeof (int16_t)) state_pl->vs[VS_BOOT_NFS_READSIZE] = NULL; } /* * Set subnetmask. Nice, but not required. */ if (state_pl->opts[CD_SUBNETMASK] != NULL) { doptp = state_pl->opts[CD_SUBNETMASK]; if (doptp->len != 4) state_pl->opts[CD_SUBNETMASK] = NULL; else { bcopy(doptp->value, &subnet, sizeof (struct in_addr)); dprintf("%s: Setting netmask to: %s\n", s_n, inet_ntoa(subnet)); subnet.s_addr = ntohl(subnet.s_addr); ipv4_setnetmask(&subnet); } } /* * Set default IP TTL. Nice, but not required. */ if (state_pl->opts[CD_IPTTL] != NULL) { doptp = state_pl->opts[CD_IPTTL]; if (doptp->len > 1) state_pl->opts[CD_IPTTL] = NULL; else { doptp = state_pl->opts[CD_IPTTL]; ipv4_setmaxttl(*(uint8_t *)doptp->value); dprintf("%s: Setting IP TTL to: %d\n", s_n, *(uint8_t *)doptp->value); } } /* * Set default router. Not required, although we'll know soon * enough... */ if (state_pl->opts[CD_ROUTER] != NULL) { doptp = state_pl->opts[CD_ROUTER]; if ((doptp->len % 4) != 0) { state_pl->opts[CD_ROUTER] = NULL; } else { if ((hp = (uint8_t *)bkmem_alloc( mac_get_hdr_len())) == NULL) { errno = ENOMEM; return (-1); } items = doptp->len / sizeof (struct in_addr); tp = doptp->value; bcopy(tp, &savr, sizeof (struct in_addr)); for (i = 0, fnd = 0; i < items; i++) { bcopy(tp, &defr, sizeof (struct in_addr)); for (k = 0, fnd = 0; k < 2 && fnd == 0; k++) { fnd = mac_get_arp(&defr, hp, mac_get_hdr_len(), mac_get_arp_timeout()); } if (fnd) break; dprintf( "%s: Warning: Router %s is unreachable.\n", s_n, inet_ntoa(defr)); tp += sizeof (struct in_addr); } bkmem_free((char *)hp, mac_get_hdr_len()); /* * If fnd is 0, we didn't find a working router. We'll * still try to use first default router. If we got * a bad router address (like not on the same net), * we're hosed anyway. */ if (!fnd) { dprintf( "%s: Warning: Using default router: %s\n", s_n, inet_ntoa(savr)); defr.s_addr = savr.s_addr; } /* ipv4_route expects network order IP addresses */ (void) ipv4_route(IPV4_ADD_ROUTE, RT_DEFAULT, NULL, &defr); } } /* * Set hostname. Not required. */ if (state_pl->opts[CD_HOSTNAME] != NULL) { doptp = state_pl->opts[CD_HOSTNAME]; i = doptp->len; if (i > MAXHOSTNAMELEN) i = MAXHOSTNAMELEN; bcopy(doptp->value, hostname, i); hostname[i] = '\0'; (void) sethostname(hostname, i); if (boothowto & RB_VERBOSE) printf("%s: Hostname is %s\n", s_n, hostname); } /* * We don't care about the lease time.... We can't enforce it anyway. */ return (0); } /* * Convert the DHCPACK into a pure ASCII boot property for use by the kernel * later in the boot process. */ static void create_bootpresponse_bprop(PKT_LIST *pl) { uint_t buflen; if (pl == NULL || bootp_response != NULL) return; buflen = (pl->len * 2) + 1; /* extra space for null (1) */ if ((bootp_response = bkmem_alloc(buflen)) == NULL) return; if (octet_to_hexascii((uint8_t *)pl->pkt, pl->len, bootp_response, &buflen) != 0) { bkmem_free(bootp_response, (pl->len * 2) + 1); bootp_response = NULL; } #if defined(__sparc) prom_create_encoded_prop("bootp-response", pl->pkt, pl->len, ENCODE_BYTES); #endif /* __sparc */ } /* * Examines /chosen node for "bootp-response" property. If it exists, this * property is the DHCPACK cached there by the PROM's DHCP implementation. * * If cache_present is B_TRUE, we simply return B_TRUE if the property exists * w/o decoding it. If cache_present is B_FALSE, we decode the packet and * use it as our state packet for the jump to BOUND mode. Note that it's good * enough that the cache exists w/o validation for determining if that's what * the user intended. * * We'll short-circuit the DHCP exchange by accepting this packet. We build a * PKT_LIST structure, and copy the bootp-response property value into a * PKT buffer we allocated. We then scan the PKT for options, and then * set state_pl to point to it. * * Returns B_TRUE if a packet was cached (and was processed correctly), false * otherwise. The caller needs to make the state change from SELECTING to * BOUND upon a B_TRUE return from this function. */ int prom_cached_reply(int cache_present) { PKT_LIST *pl; int len; pnode_t chosen; char *prop = PROM_BOOT_CACHED; chosen = prom_finddevice("/chosen"); if (chosen == OBP_NONODE || chosen == OBP_BADNODE) chosen = prom_nextnode((pnode_t)0); /* root node */ if ((len = prom_getproplen(chosen, prop)) <= 0) return (B_FALSE); if (cache_present) return (B_TRUE); if (((pl = (PKT_LIST *)bkmem_zalloc(sizeof (PKT_LIST))) == NULL) || ((pl->pkt = (PKT *)bkmem_zalloc(len)) == NULL)) { errno = ENOMEM; if (pl != NULL) bkmem_free((char *)pl, sizeof (PKT_LIST)); return (B_FALSE); } (void) prom_getprop(chosen, prop, (caddr_t)pl->pkt); pl->len = len; if (dhcp_options_scan(pl, B_TRUE) != 0) { /* garbled packet */ bkmem_free((char *)pl->pkt, pl->len); bkmem_free((char *)pl, sizeof (PKT_LIST)); return (B_FALSE); } state_pl = pl; return (B_TRUE); } /* * Perform DHCP to acquire what we used to get using rarp/bootparams. * Returns 0 for success, nonzero otherwise. * * DHCP client state machine. */ int dhcp(void) { int err = 0; int done = B_FALSE; dhcp_buf_size = mac_get_mtu(); dhcp_snd_bufp = (PKT *)bkmem_alloc(dhcp_buf_size); dhcp_rcv_bufp = (PKT *)bkmem_alloc(dhcp_buf_size); if (dhcp_snd_bufp == NULL || dhcp_rcv_bufp == NULL) { if (dhcp_snd_bufp != NULL) bkmem_free((char *)dhcp_snd_bufp, dhcp_buf_size); if (dhcp_rcv_bufp != NULL) bkmem_free((char *)dhcp_rcv_bufp, dhcp_buf_size); errno = ENOMEM; return (-1); } while (err == 0 && !done) { switch (dhcp_state) { case INIT: s_n = "INIT"; if (prom_cached_reply(B_FALSE)) { dprintf("%s: Using PROM cached BOOT reply...\n", s_n); dhcp_state = BOUND; } else { dhcp_state = SELECTING; dhcp_start_time = prom_gettime(); } break; case SELECTING: s_n = "SELECTING"; err = dhcp_selecting(); switch (err) { case 0: dhcp_state = REQUESTING; break; case DHCP_NO_DATA: dprintf( "%s: No DHCP response after %d tries.\n", s_n, DHCP_RETRIES); break; default: /* major network problems */ dprintf("%s: Network transaction failed: %d\n", s_n, err); break; } break; case REQUESTING: s_n = "REQUESTING"; err = dhcp_requesting(); switch (err) { case 0: dhcp_state = BOUND; break; case DHCP_NO_DATA: dprintf("%s: Request timed out.\n", s_n); dhcp_state = SELECTING; err = 0; (void) sleep(10); break; default: /* major network problems */ dprintf("%s: Network transaction failed: %d\n", s_n, err); break; } break; case BOUND: /* * We just "give up" if bound state fails. */ s_n = "BOUND"; if ((err = dhcp_bound()) == 0) { dhcp_state = CONFIGURED; } break; case CONFIGURED: s_n = "CONFIGURED"; create_bootpresponse_bprop(state_pl); done = B_TRUE; break; } } bkmem_free((char *)dhcp_snd_bufp, dhcp_buf_size); bkmem_free((char *)dhcp_rcv_bufp, dhcp_buf_size); return (err); } /* * Returns a copy of the DHCP-supplied value of the parameter requested * by code. */ boolean_t dhcp_getinfo(uchar_t optcat, uint16_t code, uint16_t optsize, void *value, size_t *vallenp) { size_t len = *vallenp; if (dhcp_getinfo_pl(state_pl, optcat, code, optsize, value, &len)) { if (len <= *vallenp) { *vallenp = len; return (B_TRUE); } } return (B_FALSE); } /* * Sets the clientid option. */ void dhcp_set_client_id(uint8_t *clientid, uint8_t clientid_len) { bcopy(clientid, dhcp_clientid, clientid_len); dhcp_clientid_len = clientid_len; } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _DHCPV4_H #define _DHCPV4_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define DHCP_NO_DATA 1 /* no data */ #define DHCP_ARP_TIMEOUT 1000 /* Wait one sec for response */ #define DHCP_RETRIES 0xffffffff /* Forever */ #define DHCP_WAIT 4 /* first wait - 4 seconds */ enum DHCPSTATE { INIT, SELECTING, REQUESTING, BOUND, CONFIGURED }; extern PKT_LIST *state_pl; extern int dhcp(void); extern boolean_t dhcp_getinfo(uchar_t, uint16_t, uint16_t, void *, size_t *); extern void dhcp_set_client_id(uint8_t *, uint8_t); #ifdef __cplusplus } #endif #endif /* _DHCPV4_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" /* * Ethernet routines. Includes ARP and Reverse ARP. Used for ethernet-like * media also - so be sure NOT to use ETHERMTU as a mtu limit. macinit() * will set this appropriately. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ipv4.h" #include "ipv4_impl.h" #include "mac.h" #include "mac_impl.h" #include "ethernet_inet.h" ether_addr_t etherbroadcastaddr = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; struct arp_packet { struct ether_header arp_eh; struct ether_arp arp_ea; #define USED_SIZE (sizeof (struct ether_header) + sizeof (struct ether_arp)) char filler[ETHERMIN - sizeof (struct ether_arp)]; }; static char * ether_print(ether_addr_t ea) { static char eprintbuf[20]; (void) sprintf(eprintbuf, "%x:%x:%x:%x:%x:%x", ea[0], ea[1], ea[2], ea[3], ea[4], ea[5]); return (eprintbuf); } /* * Common ARP code. Broadcast the packet and wait for the right response. * * If rarp is called for, caller expects an IPv4 address in the target * protocol address (tpa) field of the "out" argument. * * If arp is called for, caller expects a hardware address in the * source hardware address (sha) field of the "out" argument. * * Returns TRUE if transaction succeeded, FALSE otherwise. * * The timeout argument is the number of milliseconds to wait for a * response. An infinite timeout can be specified as 0xffffffff. */ static int ether_comarp(struct arp_packet *out, uint32_t timeout) { struct arp_packet *in = (struct arp_packet *)mac_state.mac_buf; int count, time, feedback, len, delay = 2; char *ind = "-\\|/"; struct in_addr tmp_ia; uint32_t wait_time; bcopy((caddr_t)etherbroadcastaddr, (caddr_t)&out->arp_eh.ether_dhost, sizeof (ether_addr_t)); bcopy((caddr_t)mac_state.mac_addr_buf, (caddr_t)&out->arp_eh.ether_shost, sizeof (ether_addr_t)); out->arp_ea.arp_hrd = htons(ARPHRD_ETHER); out->arp_ea.arp_pro = htons(ETHERTYPE_IP); out->arp_ea.arp_hln = sizeof (ether_addr_t); out->arp_ea.arp_pln = sizeof (struct in_addr); bcopy(mac_state.mac_addr_buf, (caddr_t)&out->arp_ea.arp_sha, sizeof (ether_addr_t)); ipv4_getipaddr(&tmp_ia); tmp_ia.s_addr = htonl(tmp_ia.s_addr); bcopy((caddr_t)&tmp_ia, (caddr_t)out->arp_ea.arp_spa, sizeof (struct in_addr)); feedback = 0; wait_time = prom_gettime() + timeout; for (count = 0; timeout == ~0U || prom_gettime() < wait_time; count++) { if (count == ETHER_WAITCNT) { if (out->arp_ea.arp_op == ARPOP_REQUEST) { bcopy((caddr_t)out->arp_ea.arp_tpa, (caddr_t)&tmp_ia, sizeof (struct in_addr)); printf( "\nRequesting Ethernet address for: %s\n", inet_ntoa(tmp_ia)); } else { printf("\nRequesting Internet address for %s\n", ether_print(out->arp_ea.arp_tha)); } } (void) prom_write(mac_state.mac_dev, (caddr_t)out, sizeof (*out), 0, NETWORK); if (count >= ETHER_WAITCNT) printf("%c\b", ind[feedback++ % 4]); /* activity */ time = prom_gettime() + (delay * 1000); /* broadcast delay */ while (prom_gettime() <= time) { len = prom_read(mac_state.mac_dev, mac_state.mac_buf, mac_state.mac_mtu, 0, NETWORK); if (len < USED_SIZE) continue; if (in->arp_ea.arp_pro != ntohs(ETHERTYPE_IP)) continue; if (out->arp_ea.arp_op == ntohs(ARPOP_REQUEST)) { if (in->arp_eh.ether_type != ntohs(ETHERTYPE_ARP)) continue; if (in->arp_ea.arp_op != ntohs(ARPOP_REPLY)) continue; if (bcmp((caddr_t)in->arp_ea.arp_spa, (caddr_t)out->arp_ea.arp_tpa, sizeof (struct in_addr)) != 0) continue; if (boothowto & RB_VERBOSE) { bcopy((caddr_t)in->arp_ea.arp_spa, (caddr_t)&tmp_ia, sizeof (struct in_addr)); printf("Found %s @ %s\n", inet_ntoa(tmp_ia), ether_print(in->arp_ea.arp_sha)); } /* copy hardware addr into "out" for caller */ bcopy((caddr_t)&in->arp_ea.arp_sha, (caddr_t)&out->arp_ea.arp_sha, sizeof (ether_addr_t)); return (TRUE); } else { /* Reverse ARP */ if (in->arp_eh.ether_type != ntohs(ETHERTYPE_REVARP)) continue; if (in->arp_ea.arp_op != ntohs(REVARP_REPLY)) continue; if (bcmp((caddr_t)in->arp_ea.arp_tha, (caddr_t)out->arp_ea.arp_tha, sizeof (ether_addr_t)) != 0) continue; if (boothowto & RB_VERBOSE) { bcopy((caddr_t)in->arp_ea.arp_tpa, (caddr_t)&tmp_ia, sizeof (struct in_addr)); printf("Internet address is: %s\n", inet_ntoa(tmp_ia)); } /* copy IP address into "out" for caller */ bcopy((caddr_t)in->arp_ea.arp_tpa, (caddr_t)out->arp_ea.arp_tpa, sizeof (struct in_addr)); return (TRUE); } } delay = delay * 2; /* Double the request delay */ if (delay > 64) /* maximum delay is 64 seconds */ delay = 64; } return (FALSE); } /* * ARP client side * Broadcasts to determine MAC address given network order IP address. * See RFC 826 * * Returns TRUE if successful, FALSE otherwise. */ int ether_arp(struct in_addr *ip, void *hap, uint32_t timeout) { ether_addr_t *ep = (ether_addr_t *)hap; struct arp_packet out; int result; if (!initialized) prom_panic("Ethernet device is not initialized."); bzero((char *)&out, sizeof (struct arp_packet)); out.arp_eh.ether_type = htons(ETHERTYPE_ARP); out.arp_ea.arp_op = htons(ARPOP_REQUEST); bcopy((caddr_t)etherbroadcastaddr, (caddr_t)&out.arp_ea.arp_tha, sizeof (ether_addr_t)); bcopy((caddr_t)ip, (caddr_t)out.arp_ea.arp_tpa, sizeof (struct in_addr)); result = ether_comarp(&out, timeout); if (result && (ep != NULL)) { bcopy((caddr_t)&out.arp_ea.arp_sha, (caddr_t)ep, sizeof (ether_addr_t)); } return (result); } /* * Reverse ARP client side * Determine our Internet address given our MAC address * See RFC 903 */ void ether_revarp(void) { struct in_addr ip; struct arp_packet out; if (!initialized) prom_panic("Ethernet device is not initialized."); bzero((char *)&out, sizeof (struct arp_packet)); out.arp_eh.ether_type = htons(ETHERTYPE_REVARP); out.arp_ea.arp_op = htons(REVARP_REQUEST); bcopy(mac_state.mac_addr_buf, (caddr_t)&out.arp_ea.arp_tha, sizeof (ether_addr_t)); /* Wait forever */ (void) ether_comarp(&out, 0xffffffff); bcopy((caddr_t)&out.arp_ea.arp_tpa, (caddr_t)&ip, sizeof (struct in_addr)); ip.s_addr = ntohl(ip.s_addr); ipv4_setipaddr(&ip); } /* ARGSUSED */ int ether_header_len(struct inetgram *igm) { return (sizeof (struct ether_header)); } /* * Handle a IP datagram addressed to our ethernet address or to the * ethernet broadcast address. Also respond to ARP requests. Generates * inetgrams as long as there's data and the mac level IP timeout timer * hasn't expired. As soon as there is no data, we try for * ETHER_INPUT_ATTEMPTS for more, then exit the loop, even if there is time * left, since we expect to have data waiting for us when we're called, we just * don't know how much. * * We workaround slow proms (some proms have hard sleeps for as much as 3msec) * even though there are is data waiting. * * Returns the total number of MEDIA_LVL frames placed on the socket. * Caller is expected to free up the inetgram resources. */ int ether_input(int index) { struct inetgram *inp; struct ether_header *eh; int frames = 0; /* successful frames */ int attempts = 0; /* failed attempts after success */ int16_t len = 0, data_len; uint32_t timeout, reltime; uint32_t pre_pr, post_pr; /* prom_read interval */ #ifdef DEBUG int failures = 0; /* total failures */ int total_attempts = 0; /* total prom_read */ int no_data = 0; /* no data in prom */ int arps = 0; /* arp requests processed */ uint32_t tot_pr = 0; /* prom_read time */ uint32_t tot_pc = 0; /* inetgram creation time */ uint32_t pre_pc; uint32_t now; #endif /* DEBUG */ if (!initialized) prom_panic("Ethernet device is not initialized."); if ((reltime = sockets[index].in_timeout) == 0) reltime = mac_state.mac_in_timeout; timeout = prom_gettime() + reltime; do { if (frames > ETHER_MAX_FRAMES) { /* someone is trying a denial of service attack */ break; } /* * The following is a workaround for a calvin prom (V2) bug * where prom_read() returns a nonzero length, even when it's * not read a packet. So we zero out the header to compensate. */ bzero(mac_state.mac_buf, sizeof (struct ether_header)); /* * Prom_read() will return 0 or -2 if no data is present. A * return value of -1 means an error has occurred. We adjust * the timeout by calling the time spent in prom_read() "free". * prom_read() returns the number of bytes actually read, but * will only copy "len" bytes into our buffer. Adjust in * case the MTU is wrong. */ pre_pr = prom_gettime(); len = prom_read(mac_state.mac_dev, mac_state.mac_buf, mac_state.mac_mtu, 0, NETWORK); post_pr = prom_gettime(); timeout += (post_pr - pre_pr); #ifdef DEBUG tot_pr += (post_pr - pre_pr); total_attempts++; #endif /* DEBUG */ if (len > mac_state.mac_mtu) { dprintf("ether_input: adjusting MTU %d -> %d\n", mac_state.mac_mtu, len); bkmem_free(mac_state.mac_buf, mac_state.mac_mtu); mac_state.mac_mtu = len; mac_state.mac_buf = bkmem_alloc(mac_state.mac_mtu); if (mac_state.mac_buf == NULL) { prom_panic("ether_input: Cannot reallocate " "netbuf memory."); } len = 0; /* pretend there was no data */ } if (len == -1) { #ifdef DEBUG failures++; #endif /* DEBUG */ break; } if (len == 0 || len == -2) { if (frames != 0) attempts++; #ifdef DEBUG no_data++; #endif /* DEBUG */ continue; } eh = (struct ether_header *)mac_state.mac_buf; if (eh->ether_type == ntohs(ETHERTYPE_IP) && len >= (sizeof (struct ether_header) + sizeof (struct ip))) { int offset; #ifdef DEBUG pre_pc = prom_gettime(); #endif /* DEBUG */ inp = (struct inetgram *)bkmem_zalloc( sizeof (struct inetgram)); if (inp == NULL) { errno = ENOMEM; return (frames == 0 ? -1 : frames); } offset = sizeof (struct ether_header); data_len = len - offset; inp->igm_mp = allocb(data_len, 0); if (inp->igm_mp == NULL) { errno = ENOMEM; bkmem_free((caddr_t)inp, sizeof (struct inetgram)); return (frames == 0 ? -1 : frames); } bcopy((caddr_t)(mac_state.mac_buf + offset), inp->igm_mp->b_rptr, data_len); inp->igm_mp->b_wptr += data_len; inp->igm_level = NETWORK_LVL; add_grams(&sockets[index].inq, inp); frames++; attempts = 0; #ifdef DEBUG tot_pc += prom_gettime() - pre_pc; #endif /* DEBUG */ continue; } if (eh->ether_type == ntohs(ETHERTYPE_ARP) && len >= (sizeof (struct ether_header) + sizeof (struct ether_arp))) { struct in_addr ip; struct ether_arp *ea; #ifdef DEBUG printf("ether_input: ARP message received\n"); arps++; #endif /* DEBUG */ ea = (struct ether_arp *)(mac_state.mac_buf + sizeof (struct ether_header)); if (ea->arp_pro != ntohs(ETHERTYPE_IP)) continue; ipv4_getipaddr(&ip); ip.s_addr = ntohl(ip.s_addr); if (ea->arp_op == ntohs(ARPOP_REQUEST) && ip.s_addr != INADDR_ANY && (bcmp((caddr_t)ea->arp_tpa, (caddr_t)&ip, sizeof (struct in_addr)) == 0)) { ea->arp_op = htons(ARPOP_REPLY); bcopy((caddr_t)ea->arp_sha, (caddr_t)&eh->ether_dhost, sizeof (ether_addr_t)); bcopy(mac_state.mac_addr_buf, (caddr_t)&eh->ether_shost, mac_state.mac_addr_len); bcopy((caddr_t)ea->arp_sha, (caddr_t)ea->arp_tha, sizeof (ether_addr_t)); bcopy((caddr_t)ea->arp_spa, (caddr_t)ea->arp_tpa, sizeof (struct in_addr)); bcopy(mac_state.mac_addr_buf, (caddr_t)ea->arp_sha, mac_state.mac_addr_len); bcopy((caddr_t)&ip, (caddr_t)ea->arp_spa, sizeof (struct in_addr)); (void) prom_write(mac_state.mac_dev, mac_state.mac_buf, sizeof (struct arp_packet), 0, NETWORK); /* don't charge for ARP replies */ timeout += reltime; } } } while (attempts < ETHER_INPUT_ATTEMPTS && #ifdef DEBUG (now = prom_gettime()) < timeout); #else prom_gettime() < timeout); #endif /* DEBUG */ #ifdef DEBUG printf("ether_input(%d): T/S/N/A/F/P/M: %d/%d/%d/%d/%d/%d/%d " "T/O: %d < %d = %s\n", index, total_attempts, frames, no_data, arps, failures, tot_pr, tot_pc, now, timeout, (now < timeout) ? "TRUE" : "FALSE"); #endif /* DEBUG */ return (frames); } /* * Send out an ethernet datagram. We expect a IP frame appropriately fragmented * at this level. * * Errno is set and -1 is returned if an error occurs. Number of bytes sent * is returned on success. */ /* ARGSUSED */ int ether_output(int index, struct inetgram *ogp) { int header_len, result; struct ether_header eh; struct ip *ip; struct in_addr tmpip, ipdst, netid; int broadcast = FALSE; int size; mblk_t *mp; #ifdef DEBUG printf("ether_output (%d): size %d\n", index, ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr); #endif if (!initialized) prom_panic("Ethernet device is not initialized."); if (ogp->igm_level != MEDIA_LVL) { dprintf("ether_output: frame type wrong: socket: %d\n", index * SOCKETTYPE); errno = EINVAL; return (-1); } header_len = sizeof (struct ether_header); mp = ogp->igm_mp; size = mp->b_wptr - mp->b_rptr; if (size > mac_state.mac_mtu) { dprintf("ether_output: frame size too big: %d\n", size); errno = E2BIG; return (-1); } size += header_len; ip = (struct ip *)(mp->b_rptr); eh.ether_type = htons(ETHERTYPE_IP); bcopy(mac_state.mac_addr_buf, (caddr_t)&eh.ether_shost, mac_state.mac_addr_len); bcopy((caddr_t)&ip->ip_dst, (caddr_t)&ipdst, sizeof (ipdst)); if (ipdst.s_addr == htonl(INADDR_BROADCAST)) broadcast = TRUE; /* limited broadcast */ if (!broadcast) { struct in_addr mask; ipv4_getnetid(&netid); ipv4_getnetmask(&mask); mask.s_addr = htonl(mask.s_addr); netid.s_addr = htonl(netid.s_addr); /* * check for all-hosts directed broadcast for * to its own subnet. */ if (mask.s_addr != htonl(INADDR_BROADCAST) && (ipdst.s_addr & ~mask.s_addr) == 0 && (ipdst.s_addr & mask.s_addr) == netid.s_addr) { broadcast = TRUE; /* directed broadcast */ } else { if (ogp->igm_router.s_addr != htonl(INADDR_ANY)) tmpip.s_addr = ogp->igm_router.s_addr; else tmpip.s_addr = ipdst.s_addr; result = mac_get_arp(&tmpip, (void *)&eh.ether_dhost, sizeof (ether_addr_t), mac_state.mac_arp_timeout); if (!result) { errno = ETIMEDOUT; dprintf("ether_output: ARP request for %s " "timed out.\n", inet_ntoa(tmpip)); return (-1); } } } if (broadcast) { bcopy((caddr_t)etherbroadcastaddr, (caddr_t)&eh.ether_dhost, sizeof (ether_addr_t)); } /* add the ethernet header */ mp->b_rptr -= sizeof (eh); bcopy((caddr_t)&eh, mp->b_rptr, sizeof (eh)); #ifdef DEBUG printf("ether_output(%d): level(%d) frame(0x%x) len(%d)\n", index, ogp->igm_level, mp->b_rptr, size); #if DEBUG > 1 printf("Dump ethernet (%d): \n", size); hexdump((char *)mp->b_rptr, size); printf("\n"); #endif /* DEBUG > 1 */ #endif /* DEBUG */ return (prom_write(mac_state.mac_dev, (char *)mp->b_rptr, size, 0, NETWORK)); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1990-1999, 2001-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Ethernet implementation-specific definitions */ #ifndef _ETHERNET_INET_H #define _ETHERNET_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define ETHERSIZE (ETHERMTU + 50) /* Usually a little bigger than 1500 */ #define ETHER_ARP_TIMEOUT (300000) /* in milliseconds */ #define ETHER_IN_TIMEOUT (5) /* msecond wait for IP frames */ #define ETHER_MAX_FRAMES (200) /* Maximum of consecutive frames */ #define ETHER_INPUT_ATTEMPTS (8) /* Number of consecutive attempts */ #define ETHER_WAITCNT (2) /* Activity interval */ extern int ether_header_len(struct inetgram *); extern int ether_arp(struct in_addr *, void *, uint32_t); extern void ether_revarp(void); extern int ether_input(int); extern int ether_output(int, struct inetgram *); #ifdef __cplusplus } #endif #endif /* _ETHERNET_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1990-1999, Sun Microsystems, Inc. * * FDDI implementation-specific definitions */ #ifndef _FDDI_INET_H #define _FDDI_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define FDDISIZE (4500) /* Default FDDI MTU size */ #define FDDI_ARP_TIMEOUT (300000) /* in milliseconds */ #define FDDI_IN_TIMEOUT (4) /* milliseconds wait for IP input */ #ifdef __cplusplus } #endif #endif /* _FDDI_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ipv4.h" #include "dhcpv4.h" #include "ipv4_impl.h" #include "mac.h" #include "mac_impl.h" #include "ibd_inet.h" struct ibd_arp { struct arphdr ea_hdr; /* fixed-size header */ ipoib_mac_t arp_sha; /* sender hardware address */ uchar_t arp_spa[4]; /* sender protocol address */ ipoib_mac_t arp_tha; /* target hardware address */ uchar_t arp_tpa[4]; /* target protocol address */ }; extern int errno; ipoib_mac_t ibdbroadcastaddr; /* * Assumptions about OBP behavior (refer FWARC 2002/702, 2003/251): * 1. prom_write() accepts the 20 byte destination address as the * first component in the send buffer. The buffer pointer points * to the start of this 20 byte address. The length parameter is * the IPoIB datagram size with the 20 byte of destination * address. * 2. OBP will not provide max-frame-size, since obp can only * determine that by querying the IBA mcg, and thus the property * has to be /chosen:ipib-frame-size. This will refer to the IPoIB * link MTU as per section 4.0 of ietf i/d, ie, the 4 byte IPoIB * header plus the IP payload mtu. Plus the 20 bytes of addressing * information. * 3. OBP will not provide mac-address property for IPoIB since there * are built in assumptions about 6 byte address with that. Instead, * /chosen:ipib-address will provide the local address. * 4. prom_read() returns 20 byte 0'ed filler followed by 4 byte * IPoIB header followed by IP payload. The return value is -2, * -1, 0, or the length of the received IPoIB datagram alongwith * the 20 bytes MBZ. The buffer pointer points to the start of * the 20 MBZ bytes. The length parameter reflects the max data * size that should be copied into the buffer including the 20 * MBZ bytes. * 5. OBP will not provide chosen-network-type, only * network-interface-type = ipib. On an Infiniband device, this * however does not guarantee that it is a network device. * 6. OBP will provide the DHCP client id in /chosen:client-id. * 7. /chosen:ipib-broadcast will provide the broadcast address. * 8. OBP will validate that RARP is not being used before * allowing boot to proceed to inetboot. */ struct arp_packet { ipoib_ptxhdr_t arp_eh; struct ibd_arp arp_ea; }; #define dprintf if (boothowto & RB_DEBUG) printf static char * ibd_print(ipoib_mac_t *ea) { unsigned char *macaddr = (unsigned char *)ea; static char pbuf[(3 * IPOIB_ADDRL) + 1]; int i; char *ptr = pbuf; ptr = pbuf + sprintf(pbuf, "%x", *macaddr++); for (i = 0; i < (IPOIB_ADDRL - 1); i++) ptr += sprintf(ptr, ":%x", *macaddr++); return (pbuf); } /* * Common ARP code. Broadcast the packet and wait for the right response. * * If arp is called for, caller expects a hardware address in the * source hardware address (sha) field of the "out" argument. * * IPoIB does not support RARP (see ibd_revarp()). * * Returns TRUE if transaction succeeded, FALSE otherwise. * * The timeout argument is the number of milliseconds to wait for a * response. An infinite timeout can be specified as 0xffffffff. */ static int ibd_comarp(struct arp_packet *out, uint32_t timeout) { struct arp_packet *in = (struct arp_packet *)mac_state.mac_buf; int count, time, feedback, len, delay = 2; char *ind = "-\\|/"; struct in_addr tmp_ia; uint32_t wait_time; bcopy((caddr_t)&ibdbroadcastaddr, (caddr_t)&out->arp_eh.ipoib_dest, IPOIB_ADDRL); out->arp_ea.arp_hrd = htons(ARPHRD_IB); out->arp_ea.arp_pro = htons(ETHERTYPE_IP); out->arp_ea.arp_hln = IPOIB_ADDRL; out->arp_ea.arp_pln = sizeof (struct in_addr); bcopy(mac_state.mac_addr_buf, (caddr_t)&out->arp_ea.arp_sha, IPOIB_ADDRL); ipv4_getipaddr(&tmp_ia); tmp_ia.s_addr = htonl(tmp_ia.s_addr); bcopy((caddr_t)&tmp_ia, (caddr_t)out->arp_ea.arp_spa, sizeof (struct in_addr)); feedback = 0; wait_time = prom_gettime() + timeout; for (count = 0; timeout == ~0U || prom_gettime() < wait_time; count++) { if (count == IBD_WAITCNT) { /* * Since IPoIB does not support RARP (see ibd_revarp), * we know that out->arp_ea.arp_op == ARPOP_REQUEST. */ bcopy((caddr_t)out->arp_ea.arp_tpa, (caddr_t)&tmp_ia, sizeof (struct in_addr)); printf("\nRequesting MAC address for: %s\n", inet_ntoa(tmp_ia)); } (void) prom_write(mac_state.mac_dev, (caddr_t)out, sizeof (*out), 0, NETWORK); if (count >= IBD_WAITCNT) printf("%c\b", ind[feedback++ % 4]); /* activity */ time = prom_gettime() + (delay * 1000); /* broadcast delay */ while (prom_gettime() <= time) { len = prom_read(mac_state.mac_dev, mac_state.mac_buf, mac_state.mac_mtu, 0, NETWORK); if (len < sizeof (struct arp_packet)) continue; if (in->arp_ea.arp_pro != ntohs(ETHERTYPE_IP)) continue; /* * Since IPoIB does not support RARP (see ibd_revarp), * we know that out->arp_ea.arp_op == ARPOP_REQUEST. */ if (in->arp_eh.ipoib_rhdr.ipoib_type != ntohs(ETHERTYPE_ARP)) continue; if (in->arp_ea.arp_op != ntohs(ARPOP_REPLY)) continue; if (bcmp((caddr_t)in->arp_ea.arp_spa, (caddr_t)out->arp_ea.arp_tpa, sizeof (struct in_addr)) != 0) continue; if (boothowto & RB_VERBOSE) { bcopy((caddr_t)in->arp_ea.arp_spa, (caddr_t)&tmp_ia, sizeof (struct in_addr)); printf("Found %s @ %s\n", inet_ntoa(tmp_ia), ibd_print(&in->arp_ea.arp_sha)); } /* copy hardware addr into "out" for caller */ bcopy((caddr_t)&in->arp_ea.arp_sha, (caddr_t)&out->arp_ea.arp_sha, IPOIB_ADDRL); return (TRUE); } delay = delay * 2; /* Double the request delay */ if (delay > 64) /* maximum delay is 64 seconds */ delay = 64; } return (FALSE); } /* * ARP client side * Broadcasts to determine MAC address given network order IP address. * See RFC 826 * * Returns TRUE if successful, FALSE otherwise. */ static int ibd_arp(struct in_addr *ip, void *hap, uint32_t timeout) { ipoib_mac_t *ep = (ipoib_mac_t *)hap; struct arp_packet out; int result; if (!initialized) prom_panic("IPoIB device is not initialized."); bzero((char *)&out, sizeof (struct arp_packet)); out.arp_eh.ipoib_rhdr.ipoib_type = htons(ETHERTYPE_ARP); out.arp_ea.arp_op = htons(ARPOP_REQUEST); bcopy((caddr_t)&ibdbroadcastaddr, (caddr_t)&out.arp_ea.arp_tha, IPOIB_ADDRL); bcopy((caddr_t)ip, (caddr_t)out.arp_ea.arp_tpa, sizeof (struct in_addr)); result = ibd_comarp(&out, timeout); if (result && (ep != NULL)) { bcopy((caddr_t)&out.arp_ea.arp_sha, (caddr_t)ep, IPOIB_ADDRL); } return (result); } /* * Reverse ARP client side * Determine our Internet address given our MAC address * See RFC 903 */ static void ibd_revarp(void) { prom_panic("IPoIB can not boot with RARP."); } /* ARGSUSED */ static int ibd_header_len(struct inetgram *igm) { /* * We indicate to upper layers to leave enough space * in output buffers for filling in the IPoIB header * and the 20 byte destination address in ibd_output(). */ return (IPOIB_HDRSIZE + IPOIB_ADDRL); } /* * Handle a IP datagram addressed to our MAC address or to the link * layer broadcast address. Also respond to ARP requests. Generates * inetgrams as long as there's data and the mac level IP timeout timer * hasn't expired. As soon as there is no data, we try for * IBD_INPUT_ATTEMPTS for more, then exit the loop, even if there is time * left, since we expect to have data waiting for us when we're called, we just * don't know how much. * * We workaround slow proms (some proms have hard sleeps for as much as 3msec) * even though there are is data waiting. * * Returns the total number of MEDIA_LVL frames placed on the socket. * Caller is expected to free up the inetgram resources. */ static int ibd_input(int index) { struct inetgram *inp; ipoib_ptxhdr_t *eh; int frames = 0; /* successful frames */ int attempts = 0; /* failed attempts after success */ int16_t len = 0, data_len; uint32_t timeout, reltime; uint32_t pre_pr, post_pr; /* prom_read interval */ #ifdef DEBUG int failures = 0; /* total failures */ int total_attempts = 0; /* total prom_read */ int no_data = 0; /* no data in prom */ int arps = 0; /* arp requests processed */ uint32_t tot_pr = 0; /* prom_read time */ uint32_t tot_pc = 0; /* inetgram creation time */ uint32_t pre_pc; uint32_t now; #endif /* DEBUG */ if (!initialized) prom_panic("IPoIB device is not initialized."); if ((reltime = sockets[index].in_timeout) == 0) reltime = mac_state.mac_in_timeout; timeout = prom_gettime() + reltime; do { if (frames > IBD_MAX_FRAMES) { /* someone is trying a denial of service attack */ break; } /* * The following is being paranoid about possible bugs * where prom_read() returns a nonzero length, even when * it's not read a packet; it zeroes out the header to * compensate. Paranoia from calvin prom (V2) days. */ bzero(mac_state.mac_buf, sizeof (ipoib_ptxhdr_t)); /* * Prom_read() will return 0 or -2 if no data is present. A * return value of -1 means an error has occurred. We adjust * the timeout by calling the time spent in prom_read() "free". * prom_read() returns the number of bytes actually read, but * will only copy "len" bytes into our buffer. Adjust in * case the MTU is wrong. */ pre_pr = prom_gettime(); len = prom_read(mac_state.mac_dev, mac_state.mac_buf, mac_state.mac_mtu, 0, NETWORK); post_pr = prom_gettime(); timeout += (post_pr - pre_pr); #ifdef DEBUG tot_pr += (post_pr - pre_pr); total_attempts++; #endif /* DEBUG */ if (len > mac_state.mac_mtu) { dprintf("ibd_input: adjusting MTU %d -> %d\n", mac_state.mac_mtu, len); bkmem_free(mac_state.mac_buf, mac_state.mac_mtu); mac_state.mac_mtu = len; mac_state.mac_buf = bkmem_alloc(mac_state.mac_mtu); if (mac_state.mac_buf == NULL) { prom_panic("ibd_input: Cannot reallocate " "netbuf memory."); } len = 0; /* pretend there was no data */ } if (len == -1) { #ifdef DEBUG failures++; #endif /* DEBUG */ break; } if (len == 0 || len == -2) { if (frames != 0) attempts++; #ifdef DEBUG no_data++; #endif /* DEBUG */ continue; } eh = (ipoib_ptxhdr_t *)mac_state.mac_buf; if (eh->ipoib_rhdr.ipoib_type == ntohs(ETHERTYPE_IP) && len >= (sizeof (ipoib_ptxhdr_t) + sizeof (struct ip))) { int offset; #ifdef DEBUG pre_pc = prom_gettime(); #endif /* DEBUG */ inp = (struct inetgram *)bkmem_zalloc( sizeof (struct inetgram)); if (inp == NULL) { errno = ENOMEM; return (frames == 0 ? -1 : frames); } offset = sizeof (ipoib_ptxhdr_t); data_len = len - offset; inp->igm_mp = allocb(data_len, 0); if (inp->igm_mp == NULL) { errno = ENOMEM; bkmem_free((caddr_t)inp, sizeof (struct inetgram)); return (frames == 0 ? -1 : frames); } bcopy((caddr_t)(mac_state.mac_buf + offset), inp->igm_mp->b_rptr, data_len); inp->igm_mp->b_wptr += data_len; inp->igm_level = NETWORK_LVL; add_grams(&sockets[index].inq, inp); frames++; attempts = 0; #ifdef DEBUG tot_pc += prom_gettime() - pre_pc; #endif /* DEBUG */ continue; } if (eh->ipoib_rhdr.ipoib_type == ntohs(ETHERTYPE_ARP) && len >= sizeof (struct arp_packet)) { struct in_addr ip; struct ibd_arp *ea; #ifdef DEBUG printf("ibd_input: ARP message received\n"); arps++; #endif /* DEBUG */ ea = (struct ibd_arp *)(mac_state.mac_buf + sizeof (ipoib_ptxhdr_t)); if (ea->arp_pro != ntohs(ETHERTYPE_IP)) continue; ipv4_getipaddr(&ip); ip.s_addr = ntohl(ip.s_addr); if (ea->arp_op == ntohs(ARPOP_REQUEST) && ip.s_addr != INADDR_ANY && (bcmp((caddr_t)ea->arp_tpa, (caddr_t)&ip, sizeof (struct in_addr)) == 0)) { ea->arp_op = htons(ARPOP_REPLY); bcopy((caddr_t)&ea->arp_sha, (caddr_t)&eh->ipoib_dest, IPOIB_ADDRL); bcopy((caddr_t)&ea->arp_sha, (caddr_t)&ea->arp_tha, IPOIB_ADDRL); bcopy((caddr_t)ea->arp_spa, (caddr_t)ea->arp_tpa, sizeof (struct in_addr)); bcopy(mac_state.mac_addr_buf, (caddr_t)&ea->arp_sha, mac_state.mac_addr_len); bcopy((caddr_t)&ip, (caddr_t)ea->arp_spa, sizeof (struct in_addr)); (void) prom_write(mac_state.mac_dev, mac_state.mac_buf, sizeof (struct arp_packet), 0, NETWORK); /* don't charge for ARP replies */ timeout += reltime; } } } while (attempts < IBD_INPUT_ATTEMPTS && #ifdef DEBUG (now = prom_gettime()) < timeout); #else prom_gettime() < timeout); #endif /* DEBUG */ #ifdef DEBUG printf("ibd_input(%d): T/S/N/A/F/P/M: %d/%d/%d/%d/%d/%d/%d " "T/O: %d < %d = %s\n", index, total_attempts, frames, no_data, arps, failures, tot_pr, tot_pc, now, timeout, (now < timeout) ? "TRUE" : "FALSE"); #endif /* DEBUG */ return (frames); } /* * Send out an IPoIB datagram. We expect a IP frame appropriately fragmented * at this level. * * Errno is set and -1 is returned if an error occurs. Number of bytes sent * is returned on success. */ /* ARGSUSED */ static int ibd_output(int index, struct inetgram *ogp) { int header_len, result; ipoib_ptxhdr_t eh; struct ip *ip; struct in_addr tmpip, ipdst; int broadcast = FALSE; int size; mblk_t *mp; if (!initialized) prom_panic("IPoIB device is not initialized."); if (ogp->igm_level != MEDIA_LVL) { dprintf("ibd_output: frame type wrong: socket: %d\n", index * SOCKETTYPE); errno = EINVAL; return (-1); } header_len = IPOIB_HDRSIZE + IPOIB_ADDRL; mp = ogp->igm_mp; size = mp->b_wptr - mp->b_rptr; if (size > (mac_state.mac_mtu - IPOIB_ADDRL)) { dprintf("ibd_output: frame size too big: %d\n", size); errno = E2BIG; return (-1); } size += header_len; ip = (struct ip *)(mp->b_rptr); eh.ipoib_rhdr.ipoib_type = htons(ETHERTYPE_IP); eh.ipoib_rhdr.ipoib_mbz = 0; bcopy((caddr_t)&ip->ip_dst, (caddr_t)&ipdst, sizeof (ipdst)); if (ipdst.s_addr == htonl(INADDR_BROADCAST)) broadcast = TRUE; /* limited broadcast */ if (!broadcast) { struct in_addr mask; ipv4_getnetmask(&mask); mask.s_addr = htonl(mask.s_addr); if (mask.s_addr != htonl(INADDR_BROADCAST) && (ipdst.s_addr & ~mask.s_addr) == 0) { broadcast = TRUE; /* directed broadcast */ } else { if (ogp->igm_router.s_addr != htonl(INADDR_ANY)) tmpip.s_addr = ogp->igm_router.s_addr; else tmpip.s_addr = ipdst.s_addr; result = mac_get_arp(&tmpip, (void *)&eh.ipoib_dest, IPOIB_ADDRL, mac_state.mac_arp_timeout); if (!result) { errno = ETIMEDOUT; dprintf("ibd_output: ARP request for %s " "timed out.\n", inet_ntoa(tmpip)); return (-1); } } } if (broadcast) bcopy((caddr_t)&ibdbroadcastaddr, (caddr_t)&eh.ipoib_dest, IPOIB_ADDRL); /* add the ibd header */ mp->b_rptr -= sizeof (eh); bcopy((caddr_t)&eh, mp->b_rptr, sizeof (eh)); #ifdef DEBUG printf("ibd_output(%d): level(%d) frame(0x%x) len(%d)\n", index, ogp->igm_level, mp->b_rptr, size); #endif /* DEBUG */ return (prom_write(mac_state.mac_dev, (char *)mp->b_rptr, size, 0, NETWORK)); } void ibd_init(void) { pnode_t chosen; char *mtuprop = "ipib-frame-size"; char *bcastprop = "ipib-broadcast"; char *addrprop = "ipib-address"; char *cidprop = "client-id"; int cidlen; uint8_t dhcpcid[DHCP_MAX_CID_LEN]; mac_state.mac_addr_len = IPOIB_ADDRL; mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len); if (mac_state.mac_addr_buf == NULL) prom_panic("ibd_init: Cannot allocate memory."); chosen = prom_finddevice("/chosen"); if (chosen == OBP_NONODE || chosen == OBP_BADNODE) prom_panic("ibd_init: Cannot find /chosen."); if (prom_getprop(chosen, addrprop, (caddr_t)mac_state.mac_addr_buf) != IPOIB_ADDRL) prom_panic("ibd_init: Cannot find /chosen:ipib-address\n."); if (prom_getprop(chosen, bcastprop, (caddr_t)&ibdbroadcastaddr) != IPOIB_ADDRL) prom_panic("ibd_init: Cannot find /chosen:ipib-broadcast\n."); if (((cidlen = prom_getproplen(chosen, cidprop)) <= 0) || (cidlen > DHCP_MAX_CID_LEN) || (prom_getprop(chosen, cidprop, (caddr_t)&dhcpcid) != cidlen)) prom_panic("ibd_init: Invalid /chosen:client-id\n."); dhcp_set_client_id(dhcpcid, cidlen); /* * Note that prom reports mtu including 20 bytes of * addressing information. */ if (prom_getprop(chosen, mtuprop, (caddr_t)&mac_state.mac_mtu) <= 0) mac_state.mac_mtu = IBDSIZE + IPOIB_ADDRL; /* * Tell upper layers that we can support a little * more. We will be taking off these 20 bytes at * the start before we invoke prom_write() to send * over the wire. */ mac_state.mac_arp_timeout = IBD_ARP_TIMEOUT; mac_state.mac_in_timeout = IBD_IN_TIMEOUT; mac_state.mac_arp = ibd_arp; mac_state.mac_rarp = ibd_revarp; mac_state.mac_header_len = ibd_header_len; mac_state.mac_input = ibd_input; mac_state.mac_output = ibd_output; } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _IBD_INET_H #define _IBD_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define IBDSIZE (2048) #define IBD_ARP_TIMEOUT (300000) /* in milliseconds */ #define IBD_IN_TIMEOUT (5) /* msecond wait for IP frames */ #define IBD_MAX_FRAMES (200) /* Maximum of consecutive frames */ #define IBD_INPUT_ATTEMPTS (8) /* Number of consecutive attempts */ #define IBD_WAITCNT (2) /* Activity interval */ extern void ibd_init(void); #ifdef __cplusplus } #endif #endif /* _IBD_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1991-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * icmp4.c, Code implementing the Internet Control Message Protocol (v4) ICMP. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include #include #include #include #include "icmp4.h" #include "ipv4.h" #include "ipv4_impl.h" #include "mac.h" #include "v4_sum_impl.h" #include /* * Handle ICMP redirects, ICMP echo messages. We only deal with redirects to a * different default router by changing the default route to the specified * value. */ void icmp4(struct inetgram *igp, struct ip *iphp, uint16_t iphlen, struct in_addr ipsrc) { int icmp_len; struct in_addr our_ip; struct icmp *icmphp; icmp_len = ntohs(iphp->ip_len) - iphlen; if (icmp_len < ICMP_MINLEN) { #ifdef DEBUG printf("icmp4: ICMP message from %s is too short\n", inet_ntoa(ipsrc)); #endif /* DEBUG */ return; } icmphp = (struct icmp *)(igp->igm_mp->b_rptr + iphlen); /* check alignment */ if ((uintptr_t)icmphp % sizeof (uint16_t)) { dprintf("icmp4: ICMP header not aligned (from %s)\n", inet_ntoa(ipsrc)); return; } if (ipv4cksum((uint16_t *)icmphp, icmp_len) != 0) { dprintf("icmp4: Bad ICMP checksum (from %s)\n", inet_ntoa(ipsrc)); return; } switch (icmphp->icmp_type) { case ICMP_REDIRECT: if (icmphp->icmp_code != ICMP_REDIRECT_HOST) break; dprintf("ICMP Redirect to gateway %s.\n", inet_ntoa(icmphp->icmp_gwaddr)); if (ipv4_route(IPV4_ADD_ROUTE, RT_HOST, &icmphp->icmp_ip.ip_dst, &icmphp->icmp_gwaddr) != 0) { dprintf("icmp4: Cannot add route %s, %d\n", inet_ntoa(icmphp->icmp_ip.ip_dst), errno); } break; case ICMP_UNREACH: /* * Need to highlight an error on the socket, and save the * destination address so that we can ensure it is destined * to this socket. We need the port number to be sure... */ dprintf("ICMP destination unreachable (%s)\n", inet_ntoa(icmphp->icmp_ip.ip_dst)); break; case ICMP_ECHO: /* * swap the source and destination IP addresses * and send a reply right out. */ ipv4_getipaddr(&our_ip); if (our_ip.s_addr != INADDR_ANY) { int s; struct sockaddr_in dest; if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) { dprintf("icmp4: socket: %d\n", errno); break; } icmphp->icmp_type = ICMP_ECHOREPLY; icmphp->icmp_cksum = 0; icmphp->icmp_cksum = ipv4cksum((uint16_t *)icmphp, icmp_len); dest.sin_family = AF_INET; dest.sin_addr.s_addr = ipsrc.s_addr; dest.sin_port = htons(0); (void) sendto(s, (caddr_t)icmphp, icmp_len, 0, (const struct sockaddr *)&dest, sizeof (dest)); (void) socket_close(s); } break; default: dprintf("icmp4: Unsupported ICMP message type: 0x%x " "received from %s\n", icmphp->icmp_type, inet_ntoa(ipsrc)); break; } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1999, Sun Microsystems, Inc. * All rights reserved. * * ICMPv4 implementation-specific definitions */ #ifndef _ICMP4_H #define _ICMP4_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif extern void icmp4(struct inetgram *, struct ip *, uint16_t, struct in_addr); #ifdef __cplusplus } #endif #endif /* _ICMP4_H */ #!/bin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" find_files "s.*" usr/src/common/net/dhcp /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * ipv4.c, Code implementing the IPv4 internet protocol. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "icmp4.h" #include "ipv4.h" #include "ipv4_impl.h" #include "mac.h" #include "mac_impl.h" #include "v4_sum_impl.h" #include static struct ip_frag fragment[FRAG_MAX]; /* ip fragment buffers */ static int fragments; /* Number of fragments */ static uint8_t ttl = MAXTTL; /* IP ttl */ static struct in_addr myip; /* our network-order IP addr */ static struct in_addr mynet; /* net-order netaddr */ static struct in_addr netmask = { 0xff, 0xff, 0xff, 0xff }; /* our network-order netmask */ static boolean_t netmask_set = B_FALSE; /* has anyone set netmask? */ static struct in_addr defaultrouter; /* net-order defaultrouter */ static int promiscuous; /* promiscuous mode */ static struct routing table[IPV4_ROUTE_TABLE_SIZE]; static uint16_t g_ip_id; #ifdef DEBUG #define FRAG_DEBUG #endif /* DEBUG */ #ifdef FRAG_DEBUG /* * display the fragment list. For debugging purposes. */ static void frag_disp(uint16_t size) { int i; uint_t total = 0; printf("Dumping fragment info: (%d)\n\n", fragments); printf("More:\tOffset:\tDatap:\t\tIPid:\t\tIPlen:\tIPhlen:\n"); for (i = 0; i < FRAG_MAX; i++) { if (fragment[i].mp == NULL) continue; printf("%d\t%d\t0x%x\t%d\t\t%d\t%d\n", fragment[i].more, fragment[i].offset, fragment[i].mp->b_rptr, fragment[i].ipid, fragment[i].iplen, fragment[i].iphlen); total += (fragment[i].iplen - fragment[i].iphlen); } printf("Total length is: %d. It should be: %d\n\n", total, size); } #endif /* FRAG_DEBUG */ /* * This function returns index of fragment 0 of the current fragmented DGRAM * (which would contain the transport header). Return the fragment number * for success, -1 if we don't yet have the first fragment. */ static int frag_first(void) { int i; if (fragments == 0) return (-1); for (i = 0; i < FRAG_MAX; i++) { if (fragment[i].mp != NULL && fragment[i].offset == 0) return (i); } return (-1); } /* * This function returns index of the last fragment of the current DGRAM. * Returns the fragment number for success, -1 if we don't yet have the * last fragment. */ static int frag_last(void) { int i; if (fragments == 0) return (-1); for (i = 0; i < FRAG_MAX; i++) { if (fragment[i].mp != NULL && !fragment[i].more) return (i); } return (-1); } /* * This function adds a fragment to the current pkt fragment list. Returns * FRAG_NOSLOTS if there are no more slots, FRAG_DUP if the fragment is * a duplicate, or FRAG_SUCCESS if it is successful. */ static int frag_add(int16_t offset, mblk_t *mp, uint16_t ipid, int16_t iplen, int16_t iphlen, uint8_t ipp) { int i; int16_t true_offset = IPV4_OFFSET(offset); /* first pass - look for duplicates */ for (i = 0; i < FRAG_MAX; i++) { if (fragment[i].mp != NULL && fragment[i].offset == true_offset) return (FRAG_DUP); } /* second pass - fill in empty slot */ for (i = 0; i < FRAG_MAX; i++) { if (fragment[i].mp == NULL) { fragment[i].more = (offset & IP_MF); fragment[i].offset = true_offset; fragment[i].mp = mp; fragment[i].ipid = ipid; fragment[i].iplen = iplen; fragment[i].iphlen = iphlen; fragment[i].ipp = ipp; fragments++; return (FRAG_SUCCESS); } } return (FRAG_NOSLOTS); } /* * Nuke a fragment. */ static void frag_free(int index) { if (fragment[index].mp != NULL) { freeb(fragment[index].mp); fragments--; } bzero((caddr_t)&fragment[index], sizeof (struct ip_frag)); } /* * zero the frag list. */ static void frag_flush(void) { int i; for (i = 0; i < FRAG_MAX; i++) frag_free(i); fragments = 0; } /* * Analyze the fragment list - see if we captured all our fragments. * * Returns TRUE if we've got all the fragments, and FALSE if we don't. */ static int frag_chk(void) { int i, first_frag, last_frag; int16_t actual, total; uint16_t ip_id; uint8_t ipp; if (fragments == 0 || (first_frag = frag_first()) < 0 || (last_frag = frag_last()) < 0) return (FALSE); /* * Validate the ipid's of our fragments - nuke those that don't * match the id of the first fragment or don't match the IP * protocol of the first fragment. */ ip_id = fragment[first_frag].ipid; ipp = fragment[first_frag].ipp; for (i = 0; i < FRAG_MAX; i++) { if (fragment[i].mp != NULL && ip_id != fragment[i].ipid && fragment[i].ipp != ipp) { #ifdef FRAG_DEBUG printf("ipv4: Frag id mismatch: %x != %x\n", fragment[i].ipid, ip_id); #endif /* FRAG_DEBUG */ frag_free(i); } } if (frag_last() < 0) return (FALSE); total = fragment[last_frag].offset + fragment[last_frag].iplen - fragment[last_frag].iphlen; for (i = 0, actual = 0; i < FRAG_MAX; i++) actual += (fragment[i].iplen - fragment[i].iphlen); #ifdef FRAG_DEBUG frag_disp(total); #endif /* FRAG_DEBUG */ return (total == actual); } /* * Load the assembled fragments into igp. Returns 0 for success, nonzero * otherwise. */ static int frag_load(struct inetgram *igp) { int i; int16_t len; uint_t total_len; boolean_t first_frag = B_FALSE; mblk_t *mp; struct ip *iph; int first_iph_len; if (fragments == 0) return (ENOENT); mp = igp->igm_mp; /* Get the IP header length of the first fragment. */ i = frag_first(); assert(i >= 0); first_iph_len = fragment[i].iphlen; for (i = 0, len = 0, total_len = 0; i < FRAG_MAX; i++) { if (fragment[i].mp != NULL) { /* * Copy just the data (omit the ip header of all * fragments except the first one which contains * all the info...) */ if (fragment[i].offset == 0) { len = fragment[i].iplen; first_frag = B_TRUE; } else { len = fragment[i].iplen - fragment[i].iphlen; } total_len += len; if (total_len > mp->b_size) return (E2BIG); if (first_frag) { bcopy((caddr_t)(fragment[i].mp->b_rptr), (caddr_t)mp->b_rptr, len); first_frag = B_FALSE; } else { bcopy((caddr_t)(fragment[i].mp->b_rptr + fragment[i].iphlen), (caddr_t)(mp->b_rptr + first_iph_len + fragment[i].offset), len); } mp->b_wptr += len; } } /* Fix the total length in the IP header. */ iph = (struct ip *)mp->b_rptr; iph->ip_len = htons(total_len); return (0); } /* * Locate a routing table entry based upon arguments. IP addresses expected * in network order. Returns index for success, -1 if entry not found. */ static int find_route(uint8_t *flagp, struct in_addr *destp, struct in_addr *gatewayp) { int i, table_entry = -1; for (i = 0; table_entry == -1 && i < IPV4_ROUTE_TABLE_SIZE; i++) { if (flagp != NULL) { if (*flagp & table[i].flag) table_entry = i; } if (destp != NULL) { if (destp->s_addr == table[i].dest.s_addr) table_entry = i; else table_entry = -1; } if (gatewayp != NULL) { if (gatewayp->s_addr == table[i].gateway.s_addr) table_entry = i; else table_entry = -1; } } return (table_entry); } /* * ADD or DEL a routing table entry. Returns 0 for success, -1 and errno * otherwise. IP addresses are expected in network order. */ int ipv4_route(int cmd, uint8_t flag, struct in_addr *destp, struct in_addr *gatewayp) { static int routing_table_initialized; int index; uint8_t tmp_flag; if (gatewayp == NULL) { errno = EINVAL; return (-1); } /* initialize routing table */ if (routing_table_initialized == 0) { for (index = 0; index < IPV4_ROUTE_TABLE_SIZE; index++) table[index].flag = RT_UNUSED; routing_table_initialized = 1; } switch (cmd) { case IPV4_ADD_ROUTE: tmp_flag = (uint8_t)RT_UNUSED; if ((index = find_route(&tmp_flag, NULL, NULL)) == -1) { dprintf("ipv4_route: routing table full.\n"); errno = ENOSPC; return (-1); } table[index].flag = flag; if (destp != NULL) table[index].dest.s_addr = destp->s_addr; else table[index].dest.s_addr = htonl(INADDR_ANY); table[index].gateway.s_addr = gatewayp->s_addr; break; case IPV4_BAD_ROUTE: /* FALLTHRU */ case IPV4_DEL_ROUTE: if ((index = find_route(&flag, destp, gatewayp)) == -1) { dprintf("ipv4_route: No such routing entry.\n"); errno = ENOENT; return (-1); } if (cmd == IPV4_DEL_ROUTE) { table[index].flag = RT_UNUSED; table[index].dest.s_addr = htonl(INADDR_ANY); table[index].gateway.s_addr = htonl(INADDR_ANY); } else { table[index].flag = RT_NG; } break; default: errno = EINVAL; return (-1); } return (0); } /* * Return gateway to destination. Returns gateway IP address in network order * for success, NULL if no route to destination exists. */ struct in_addr * ipv4_get_route(uint8_t flag, struct in_addr *destp, struct in_addr *gatewayp) { int index; if ((index = find_route(&flag, destp, gatewayp)) == -1) return (NULL); return (&table[index].gateway); } /* * Initialize the IPv4 generic parts of the socket, as well as the routing * table. */ void ipv4_socket_init(struct inetboot_socket *isp) { isp->input[NETWORK_LVL] = ipv4_input; isp->output[NETWORK_LVL] = ipv4_output; isp->close[NETWORK_LVL] = NULL; isp->headerlen[NETWORK_LVL] = ipv4_header_len; } /* * Initialize a raw ipv4 socket. */ void ipv4_raw_socket(struct inetboot_socket *isp, uint8_t proto) { isp->type = INETBOOT_RAW; if (proto == 0) isp->proto = IPPROTO_IP; else isp->proto = proto; isp->input[TRANSPORT_LVL] = NULL; isp->output[TRANSPORT_LVL] = NULL; isp->headerlen[TRANSPORT_LVL] = NULL; isp->ports = NULL; } /* * Return the size of an IPv4 header (no options) */ /* ARGSUSED */ int ipv4_header_len(struct inetgram *igm) { return (sizeof (struct ip)); } /* * Set our source address. * Argument is assumed to be host order. */ void ipv4_setipaddr(struct in_addr *ip) { myip.s_addr = htonl(ip->s_addr); } /* * Returns our current source address in host order. */ void ipv4_getipaddr(struct in_addr *ip) { ip->s_addr = ntohl(myip.s_addr); } /* * Set our netmask. * Argument is assumed to be host order. */ void ipv4_setnetmask(struct in_addr *ip) { netmask_set = B_TRUE; netmask.s_addr = htonl(ip->s_addr); mynet.s_addr = netmask.s_addr & myip.s_addr; /* implicit */ } void ipv4_getnetid(struct in_addr *my_netid) { struct in_addr my_netmask; if (mynet.s_addr != 0) my_netid->s_addr = ntohl(mynet.s_addr); else { ipv4_getnetmask(&my_netmask); my_netid->s_addr = my_netmask.s_addr & ntohl(myip.s_addr); } } /* * Returns our current netmask in host order. * Neither OBP nor the standalone DHCP client mandate * that the netmask be specified, so in the absence of * a netmask, we attempt to derive it using class-based * heuristics. */ void ipv4_getnetmask(struct in_addr *ip) { if (netmask_set || (myip.s_addr == 0)) ip->s_addr = ntohl(netmask.s_addr); else { /* base the netmask on our IP address */ if (IN_CLASSA(ntohl(myip.s_addr))) ip->s_addr = ntohl(IN_CLASSA_NET); else if (IN_CLASSB(ntohl(myip.s_addr))) ip->s_addr = ntohl(IN_CLASSB_NET); else if (IN_CLASSC(ntohl(myip.s_addr))) ip->s_addr = ntohl(IN_CLASSC_NET); else ip->s_addr = ntohl(IN_CLASSE_NET); } } /* * Set our default router. * Argument is assumed to be host order, and *MUST* be on the same network * as our source IP address. */ void ipv4_setdefaultrouter(struct in_addr *ip) { defaultrouter.s_addr = htonl(ip->s_addr); } /* * Returns our current default router in host order. */ void ipv4_getdefaultrouter(struct in_addr *ip) { ip->s_addr = ntohl(defaultrouter.s_addr); } /* * Toggle promiscuous flag. If set, client disregards destination IP * address. Otherwise, only limited broadcast, network broadcast, and * unicast traffic get through. Returns previous setting. */ int ipv4_setpromiscuous(int toggle) { int old = promiscuous; promiscuous = toggle; return (old); } /* * Set IP TTL. */ void ipv4_setmaxttl(uint8_t cttl) { ttl = cttl; } /* * Convert an ipv4 address to dotted notation. * Returns ptr to statically allocated buffer containing dotted string. */ char * inet_ntoa(struct in_addr ip) { uint8_t *p; static char ipaddr[16]; p = (uint8_t *)&ip.s_addr; (void) sprintf(ipaddr, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]); return (ipaddr); } /* * Construct a transport datagram from a series of IP fragments (igp == NULL) * or from a single IP datagram (igp != NULL). Return the address of the * contructed transport datagram. */ struct inetgram * make_trans_datagram(int index, struct inetgram *igp, struct in_addr ipsrc, struct in_addr ipdst, uint16_t iphlen) { uint16_t trans_len, *transp, new_len; int first_frag, last_frag; boolean_t fragmented; struct inetgram *ngp; struct ip *iph; fragmented = (igp == NULL); ngp = (struct inetgram *)bkmem_zalloc(sizeof (struct inetgram)); if (ngp == NULL) { errno = ENOMEM; if (fragmented) frag_flush(); return (NULL); } if (fragmented) { last_frag = frag_last(); trans_len = fragment[last_frag].offset + fragment[last_frag].iplen - fragment[last_frag].iphlen; first_frag = frag_first(); /* * The returned buffer contains the IP header of the * first fragment. */ trans_len += fragment[first_frag].iphlen; transp = (uint16_t *)(fragment[first_frag].mp->b_rptr + fragment[first_frag].iphlen); } else { /* * Note that igm_len may not be the real length of an * IP packet because some network interface, such as * Ethernet, as a minimum frame size. So we should not * use the interface frame size to determine the * length of an IP packet. We should use the IP * length field in the IP header. */ iph = (struct ip *)igp->igm_mp->b_rptr; trans_len = ntohs(iph->ip_len); transp = (uint16_t *)(igp->igm_mp->b_rptr + iphlen); } ngp->igm_saddr.sin_addr.s_addr = ipsrc.s_addr; ngp->igm_saddr.sin_port = sockets[index].ports(transp, SOURCE); ngp->igm_target.s_addr = ipdst.s_addr; ngp->igm_level = TRANSPORT_LVL; /* * Align to 16bit value. Checksum code may require an extra byte * for padding. */ new_len = ((trans_len + sizeof (int16_t) - 1) & ~(sizeof (int16_t) - 1)); if ((ngp->igm_mp = allocb(new_len, 0)) == NULL) { errno = ENOMEM; bkmem_free((caddr_t)ngp, sizeof (struct inetgram)); if (fragmented) frag_flush(); return (NULL); } if (fragmented) { if (frag_load(ngp) != 0) { freeb(ngp->igm_mp); bkmem_free((caddr_t)ngp, sizeof (struct inetgram)); frag_flush(); return (NULL); } frag_flush(); } else { bcopy((caddr_t)(igp->igm_mp->b_rptr), (caddr_t)ngp->igm_mp->b_rptr, trans_len); ngp->igm_mp->b_wptr += trans_len; } return (ngp); } /* * ipv4_input: Pull in IPv4 datagrams addressed to us. Handle IP fragmentation * (fragments received in any order) and ICMP at this level. * * Note that because our network is serviced by polling when we expect * something (upon a referenced socket), we don't go through the work of * locating the appropriate socket a datagram is destined for. We'll only * accept data for the referenced socket. This means we don't have * asynchronous networking, but since we can't service the net using an * interrupt handler, it doesn't do us any good to try to service datagrams * destined for sockets other than the referenced one. Data is handled in * a fifo manner. * * The mac layer will grab all frames for us. If we find we don't have all * the necessary fragments to reassemble the datagram, we'll call the mac * layer again for FRAG_ATTEMPTS to see if it has any more frames. * * Supported protocols: IPPROTO_IP, IPPROTO_ICMP, IPPROTO_UDP. * * Returns: number of NETWORK_LVL datagrams placed on socket , -1 if error * occurred. * * Note: errno is set to ETIMEDOUT if fragment reassembly fails. */ int ipv4_input(int index) { int datagrams = 0; int frag_stat, input_attempts = 0; uint16_t iphlen, iplen, ip_id; int16_t curr_off; struct ip *iphp; struct inetgram *igp, *newgp = NULL, *ipv4_listp = NULL; struct in_addr ipdst, ipsrc; mblk_t *mp; enum SockType type; #ifdef DEBUG printf("ipv4_input(%d): start ######################################\n", index); #endif /* DEBUG */ frag_flush(); ipv4_try_again: while ((igp = sockets[index].inq) != NULL) { if (igp->igm_level != NETWORK_LVL) { #ifdef DEBUG printf("ipv4_input(%d): unexpected frame type: %d\n", index, igp->igm_level); #endif /* DEBUG */ del_gram(&sockets[index].inq, igp, TRUE); continue; } iphp = (struct ip *)igp->igm_mp->b_rptr; if (iphp->ip_v != IPVERSION) { dprintf("ipv4_input(%d): IPv%d datagram discarded\n", index, iphp->ip_v); del_gram(&sockets[index].inq, igp, TRUE); continue; } iphlen = iphp->ip_hl << 2; if (iphlen < sizeof (struct ip)) { dprintf("ipv4_input(%d): IP msg too short (%d < %u)\n", index, iphlen, (uint_t)sizeof (struct ip)); del_gram(&sockets[index].inq, igp, TRUE); continue; } iplen = ntohs(iphp->ip_len); if (iplen > msgdsize(igp->igm_mp)) { dprintf("ipv4_input(%d): IP len/buffer mismatch " "(%d > %lu)\n", index, iplen, igp->igm_mp->b_size); del_gram(&sockets[index].inq, igp, TRUE); continue; } bcopy((caddr_t)&(iphp->ip_dst), (caddr_t)&ipdst, sizeof (ipdst)); bcopy((caddr_t)&(iphp->ip_src), (caddr_t)&ipsrc, sizeof (ipsrc)); /* igp->igm_mp->b_datap is guaranteed to be 64 bit aligned] */ if (ipv4cksum((uint16_t *)iphp, iphlen) != 0) { dprintf("ipv4_input(%d): Bad IP header checksum " "(to %s)\n", index, inet_ntoa(ipdst)); del_gram(&sockets[index].inq, igp, TRUE); continue; } if (!promiscuous) { /* validate destination address */ if (ipdst.s_addr != htonl(INADDR_BROADCAST) && ipdst.s_addr != (mynet.s_addr | ~netmask.s_addr) && ipdst.s_addr != myip.s_addr) { #ifdef DEBUG printf("ipv4_input(%d): msg to %s discarded.\n", index, inet_ntoa(ipdst)); #endif /* DEBUG */ /* not ours */ del_gram(&sockets[index].inq, igp, TRUE); continue; } } /* Intercept ICMP first */ if (!promiscuous && (iphp->ip_p == IPPROTO_ICMP)) { icmp4(igp, iphp, iphlen, ipsrc); del_gram(&sockets[index].inq, igp, TRUE); continue; } #ifdef DEBUG printf("ipv4_input(%d): processing ID: 0x%x protocol %d " "(0x%x) (0x%x,%d)\n", index, ntohs(iphp->ip_id), iphp->ip_p, igp, igp->igm_mp, igp->igm_mp->b_size); #endif /* DEBUG */ type = sockets[index].type; if (type == INETBOOT_RAW) { /* No fragmentation - Just the raw packet. */ #ifdef DEBUG printf("ipv4_input(%d): Raw packet.\n", index); #endif /* DEBUG */ del_gram(&sockets[index].inq, igp, FALSE); add_grams(&ipv4_listp, igp); igp->igm_mp->b_rptr += iphlen; igp->igm_mp->b_wptr = igp->igm_mp->b_rptr + iplen; datagrams++; continue; } if ((type == INETBOOT_DGRAM && iphp->ip_p != IPPROTO_UDP) || (type == INETBOOT_STREAM && iphp->ip_p != IPPROTO_TCP)) { /* Wrong protocol. */ dprintf("ipv4_input(%d): unexpected protocol: " "%d for socket type %d\n", index, iphp->ip_p, type); del_gram(&sockets[index].inq, igp, TRUE); continue; } /* * The following code is common to both STREAM and DATAGRAM * sockets. */ /* * Once we process the first fragment, we won't have * the transport header, so we'll have to match on * IP id. */ curr_off = ntohs(iphp->ip_off); if ((curr_off & ~(IP_DF | IP_MF)) == 0) { uint16_t *transp; /* Validate transport header. */ mp = igp->igm_mp; if ((mp->b_wptr - mp->b_rptr - iphlen) < sockets[index].headerlen[TRANSPORT_LVL](igp)) { dprintf("ipv4_input(%d): datagram 0 " "too small to hold transport header " "(from %s)\n", index, inet_ntoa(ipsrc)); del_gram(&sockets[index].inq, igp, TRUE); continue; } /* * check alignment - transport elements are 16 * bit aligned.. */ transp = (uint16_t *)(mp->b_rptr + iphlen); if ((uintptr_t)transp % sizeof (uint16_t)) { dprintf("ipv4_input(%d): Transport " "header is not 16-bit aligned " "(0x%lx, from %s)\n", index, (long)transp, inet_ntoa(ipsrc)); del_gram(&sockets[index].inq, igp, TRUE); continue; } if (curr_off & IP_MF) { /* fragment 0 of fragmented datagram */ ip_id = ntohs(iphp->ip_id); frag_stat = frag_add(curr_off, igp->igm_mp, ip_id, iplen, iphlen, iphp->ip_p); if (frag_stat != FRAG_SUCCESS) { #ifdef FRAG_DEBUG if (frag_stat == FRAG_DUP) { printf("ipv4_input" "(%d): Frag dup.\n", index); } else { printf("ipv4_input" "(%d): too many " "frags\n", index); } #endif /* FRAG_DEBUG */ del_gram(&sockets[index].inq, igp, TRUE); continue; } del_gram(&sockets[index].inq, igp, FALSE); /* keep the data, lose the inetgram */ bkmem_free((caddr_t)igp, sizeof (struct inetgram)); #ifdef FRAG_DEBUG printf("ipv4_input(%d): Frag/Off/Id " "(%d/%d/%x)\n", index, fragments, IPV4_OFFSET(curr_off), ip_id); #endif /* FRAG_DEBUG */ } else { /* Single, unfragmented datagram */ newgp = make_trans_datagram(index, igp, ipsrc, ipdst, iphlen); if (newgp != NULL) { add_grams(&ipv4_listp, newgp); datagrams++; } del_gram(&sockets[index].inq, igp, TRUE); continue; } } else { /* fragments other than 0 */ frag_stat = frag_add(curr_off, igp->igm_mp, ntohs(iphp->ip_id), iplen, iphlen, iphp->ip_p); if (frag_stat == FRAG_SUCCESS) { #ifdef FRAG_DEBUG printf("ipv4_input(%d): Frag(%d) " "off(%d) id(%x)\n", index, fragments, IPV4_OFFSET(curr_off), ntohs(iphp->ip_id)); #endif /* FRAG_DEBUG */ del_gram(&sockets[index].inq, igp, FALSE); /* keep the data, lose the inetgram */ bkmem_free((caddr_t)igp, sizeof (struct inetgram)); } else { #ifdef FRAG_DEBUG if (frag_stat == FRAG_DUP) printf("ipv4_input(%d): Frag " "dup.\n", index); else { printf("ipv4_input(%d): too " "many frags\n", index); } #endif /* FRAG_DEBUG */ del_gram(&sockets[index].inq, igp, TRUE); continue; } } /* * Determine if we have all of the fragments. * * NOTE: at this point, we've placed the data in the * fragment table, and the inetgram (igp) has been * deleted. */ if (!frag_chk()) continue; newgp = make_trans_datagram(index, NULL, ipsrc, ipdst, iphlen); if (newgp == NULL) continue; add_grams(&ipv4_listp, newgp); datagrams++; } if (ipv4_listp == NULL && fragments != 0) { if (++input_attempts > FRAG_ATTEMPTS) { dprintf("ipv4_input(%d): reassembly(%d) timed out in " "%d msecs.\n", index, fragments, sockets[index].in_timeout * input_attempts); frag_flush(); errno = ETIMEDOUT; return (-1); } else { /* * Call the media layer again... there may be more * packets waiting. */ if (sockets[index].input[MEDIA_LVL](index) < 0) { /* errno will be set appropriately */ frag_flush(); return (-1); } goto ipv4_try_again; } } add_grams(&sockets[index].inq, ipv4_listp); return (datagrams); } /* * ipv4_output: Generate IPv4 datagram(s) for the payload and deliver them. * Routing is handled here as well, by reusing the saddr field to hold the * router's IP address. * * We don't deal with fragmentation on the outgoing side. * * Arguments: index to socket, inetgram to send. * * Returns: 0 for success, -1 if error occurred. */ int ipv4_output(int index, struct inetgram *ogp) { struct ip *iphp; uint64_t iphbuffer[sizeof (struct ip)]; #ifdef DEBUG printf("ipv4_output(%d): size %d\n", index, ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr); #endif /* DEBUG */ /* we don't deal (yet) with fragmentation. Maybe never will */ if ((ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr) > mac_get_mtu()) { dprintf("ipv4: datagram too big for MAC layer.\n"); errno = E2BIG; return (-1); } if (ogp->igm_level != NETWORK_LVL) { #ifdef DEBUG printf("ipv4_output(%d): unexpected frame type: %d\n", index, ogp->igm_level); #endif /* DEBUG */ errno = EINVAL; return (-1); } if (sockets[index].out_flags & SO_DONTROUTE) ogp->igm_oflags |= MSG_DONTROUTE; iphp = (struct ip *)&iphbuffer; iphp->ip_v = IPVERSION; iphp->ip_hl = sizeof (struct ip) / 4; iphp->ip_tos = 0; iphp->ip_len = htons(ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr + sizeof (struct ip)); iphp->ip_id = htons(++g_ip_id); iphp->ip_off = htons(IP_DF); iphp->ip_p = sockets[index].proto; iphp->ip_sum = htons(0); iphp->ip_ttl = ttl; /* struct copies */ iphp->ip_src = myip; iphp->ip_dst = ogp->igm_saddr.sin_addr; /* * On local / limited broadcasts, don't route. From a purist's * perspective, we should be setting the TTL to 1. But * operational experience has shown that some BOOTP relay agents * (ciscos) discard our packets. Furthermore, these devices also * *don't* reset the TTL to MAXTTL on the unicast side of the * BOOTP relay agent! Sigh. Thus to work correctly in these * environments, we leave the TTL as it has been been set by * the application layer, and simply don't check for a route. */ if (iphp->ip_dst.s_addr == htonl(INADDR_BROADCAST) || (netmask.s_addr != htonl(INADDR_BROADCAST) && iphp->ip_dst.s_addr == (mynet.s_addr | ~netmask.s_addr))) { ogp->igm_oflags |= MSG_DONTROUTE; } /* Routing necessary? */ if ((ogp->igm_oflags & MSG_DONTROUTE) == 0 && ((iphp->ip_dst.s_addr & netmask.s_addr) != mynet.s_addr)) { struct in_addr *rip; if ((rip = ipv4_get_route(RT_HOST, &iphp->ip_dst, NULL)) == NULL) { rip = ipv4_get_route(RT_DEFAULT, NULL, NULL); } if (rip == NULL) { dprintf("ipv4(%d): No route to %s.\n", index, inet_ntoa(iphp->ip_dst)); errno = EHOSTUNREACH; return (-1); } ogp->igm_router.s_addr = rip->s_addr; } else ogp->igm_router.s_addr = htonl(INADDR_ANY); iphp->ip_sum = ipv4cksum((uint16_t *)iphp, sizeof (struct ip)); ogp->igm_mp->b_rptr -= sizeof (struct ip); bcopy((caddr_t)iphp, (caddr_t)(ogp->igm_mp->b_rptr), sizeof (struct ip)); ogp->igm_level = MEDIA_LVL; return (0); } /* * Function to be called by TCP to send out a packet. This is used * when TCP wants to send out packets which it has already filled in * most of the header fields. */ int ipv4_tcp_output(int sock_id, mblk_t *pkt) { struct ip *iph; struct in_addr *rip = NULL; struct inetgram datagram; iph = (struct ip *)pkt->b_rptr; bzero(&datagram, sizeof (struct inetgram)); /* * Bootparams doesn't know about subnet masks, so we need to * explicitly check for this flag. */ if (sockets[sock_id].out_flags & SO_DONTROUTE) datagram.igm_oflags |= MSG_DONTROUTE; /* Routing necessary? */ if (((datagram.igm_oflags & MSG_DONTROUTE) == 0) && ((iph->ip_dst.s_addr & netmask.s_addr) != mynet.s_addr)) { if ((rip = ipv4_get_route(RT_HOST, &iph->ip_dst, NULL)) == NULL) { rip = ipv4_get_route(RT_DEFAULT, NULL, NULL); } if (rip == NULL) { dprintf("ipv4(%d): No route to %s.\n", sock_id, inet_ntoa(iph->ip_dst)); errno = EHOSTUNREACH; return (-1); } } iph->ip_id = htons(++g_ip_id); iph->ip_sum = ipv4cksum((uint16_t *)iph, sizeof (struct ip)); #if DEBUG > 1 printf("ipv4_tcp_output: dump IP packet(%d)\n", iph->ip_len); hexdump((char *)pkt->b_rptr, iph->ip_len); #endif /* Call the MAC layer output routine to send it out. */ datagram.igm_mp = pkt; datagram.igm_level = MEDIA_LVL; if (rip != NULL) datagram.igm_router.s_addr = rip->s_addr; else datagram.igm_router.s_addr = 0; return (mac_state.mac_output(sock_id, &datagram)); } /* * Internet address interpretation routine. * All the network library routines call this * routine to interpret entries in the data bases * which are expected to be an address. * The value returned is in network order. */ in_addr_t inet_addr(const char *cp) { uint32_t val, base, n; char c; uint32_t parts[4], *pp = parts; if (*cp == '\0') return ((uint32_t)-1); /* disallow null string in cp */ again: /* * Collect number up to ``.''. * Values are specified as for C: * 0x=hex, 0=octal, other=decimal. */ val = 0; base = 10; if (*cp == '0') { if (*++cp == 'x' || *cp == 'X') base = 16, cp++; else base = 8; } while ((c = *cp) != '\0') { if (isdigit(c)) { if ((c - '0') >= base) break; val = (val * base) + (c - '0'); cp++; continue; } if (base == 16 && isxdigit(c)) { val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A')); cp++; continue; } break; } if (*cp == '.') { /* * Internet format: * a.b.c.d * a.b.c (with c treated as 16-bits) * a.b (with b treated as 24 bits) */ if ((pp >= parts + 3) || (val > 0xff)) { return ((uint32_t)-1); } *pp++ = val, cp++; goto again; } /* * Check for trailing characters. */ if (*cp && !isspace(*cp)) { return ((uint32_t)-1); } *pp++ = val; /* * Concoct the address according to * the number of parts specified. */ n = pp - parts; switch (n) { case 1: /* a -- 32 bits */ val = parts[0]; break; case 2: /* a.b -- 8.24 bits */ if (parts[1] > 0xffffff) return ((uint32_t)-1); val = (parts[0] << 24) | (parts[1] & 0xffffff); break; case 3: /* a.b.c -- 8.8.16 bits */ if (parts[2] > 0xffff) return ((uint32_t)-1); val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | (parts[2] & 0xffff); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if (parts[3] > 0xff) return ((uint32_t)-1); val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | ((parts[2] & 0xff) << 8) | (parts[3] & 0xff); break; default: return ((uint32_t)-1); } val = htonl(val); return (val); } void hexdump(char *data, int datalen) { char *p; ushort_t *p16 = (ushort_t *)data; char *p8 = data; int i, left, len; int chunk = 16; /* 16 bytes per line */ printf("\n"); for (p = data; p < data + datalen; p += chunk) { printf("\t%4d: ", (int)(p - data)); left = (data + datalen) - p; len = MIN(chunk, left); for (i = 0; i < (len / 2); i++) printf("%04x ", ntohs(*p16++) & 0xffff); if (len % 2) { printf("%02x ", *((unsigned char *)p16)); } for (i = 0; i < (chunk - left) / 2; i++) printf(" "); printf(" "); for (i = 0; i < len; i++, p8++) printf("%c", isprint(*p8) ? *p8 : '.'); printf("\n"); } printf("\n"); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * IPv4 implementation-specific definitions */ #ifndef _IPV4_H #define _IPV4_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define RT_UNUSED 1 /* Table entry is unused */ #define RT_DEFAULT 2 /* Gateway is a default router */ #define RT_HOST 4 /* Destination is a host */ #define RT_NET 8 /* Destination is a network */ #define RT_NG 10 /* Route is No Good */ #define IPV4_ROUTE_TABLE_SIZE (5) /* Number of entries in the table */ #define IPV4_ADD_ROUTE 0 #define IPV4_DEL_ROUTE 1 #define IPV4_BAD_ROUTE 2 extern char *inet_ntoa(struct in_addr); extern void ipv4_setdefaultrouter(struct in_addr *); extern int ipv4_setpromiscuous(int); extern void ipv4_setipaddr(struct in_addr *); extern void ipv4_getipaddr(struct in_addr *); extern void ipv4_setnetmask(struct in_addr *); extern void ipv4_getnetmask(struct in_addr *); extern int ipv4_route(int, uint8_t, struct in_addr *, struct in_addr *); extern void ipv4_setmaxttl(uint8_t); extern in_addr_t inet_addr(const char *); extern void hexdump(char *, int); extern int prom_cached_reply(int); extern void ipv4_getnetid(struct in_addr *); #ifdef __cplusplus } #endif #endif /* _IPV4_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Internal IPv4 implementation-specific definitions */ #ifndef _IPV4_IMPL_H #define _IPV4_IMPL_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define FRAG_MAX (40) /* max number of IP fragments per datagram */ #define FRAG_SUCCESS (0) /* datagram reassembled ok */ #define FRAG_DUP (1) /* duplicate ip fragment */ #define FRAG_NOSLOTS (2) /* no more ip fragment slots */ #define FRAG_ATTEMPTS 1 /* Try twice to get all the fragments */ /* * IP fragmentation data structure */ struct ip_frag { int16_t more; /* Fragment bit (TRUE == MF, FALSE == No more */ int16_t offset; /* Offset within the encapsulated datagram */ mblk_t *mp; /* Fragment including IP header */ uint16_t ipid; /* fragment ident */ int16_t iplen; /* IP datagram's length */ int16_t iphlen; /* Len of IP header */ uint8_t ipp; /* IP protocol */ }; /* * true offset is in 8 octet units. The high order 3 bits of the IP header * offset field are therefore used for fragmentation flags. Shift these * bits off to produce the true offset. The high order flag bit is unused * (what would be considered the sign bit). Still, we cast the callers * value as an unsigned quantity to ensure it is treated as positive. */ #define IPV4_OFFSET(a) ((uint16_t)(a) << 3) #define IPV4_VERSION 4 #define IPH_HDR_LENGTH(iph) (((struct ip *)(iph))->ip_hl << 2) /* ECN code points for IPv4 TOS byte and IPv6 traffic class octet. */ #define IPH_ECN_NECT 0x0 /* Not ECN-Capabable Transport */ #define IPH_ECN_ECT1 0x1 /* ECN-Capable Transport, ECT(1) */ #define IPH_ECN_ECT0 0x2 /* ECN-Capable Transport, ECT(0) */ #define IPH_ECN_CE 0x3 /* ECN-Congestion Experienced (CE) */ #define IPV4_VERSION 4 #define IP_VERSION IPV4_VERSION #define IP_SIMPLE_HDR_LENGTH_IN_WORDS 5 #define IP_SIMPLE_HDR_LENGTH 20 #define IP_MAX_HDR_LENGTH 60 #define IP_MIN_MTU (IP_MAX_HDR_LENGTH + 8) /* 68 bytes */ /* * IP routing table. IP addresses are in network-order. */ struct routing { struct in_addr dest; struct in_addr gateway; uint8_t flag; }; extern void ipv4_raw_socket(struct inetboot_socket *, uint8_t); extern void ipv4_socket_init(struct inetboot_socket *); extern int ipv4_header_len(struct inetgram *); extern int ipv4_input(int); extern int ipv4_output(int, struct inetgram *); extern int ipv4_tcp_output(int, mblk_t *); extern struct in_addr *ipv4_get_route(uint8_t, struct in_addr *, struct in_addr *); #ifdef __cplusplus } #endif #endif /* _IPV4_IMPL_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mac.h" #include "mac_impl.h" #include "atm_inet.h" #include "ethernet_inet.h" #include "fddi_inet.h" #include "token_inet.h" #include "ibd_inet.h" /* * MAC layer interface */ boolean_t initialized; /* Boolean state */ struct mac_type mac_state; int arp_index; /* current arp table index */ static struct arptable atable[ARP_TABLE_SIZE]; struct ofw_net_types { char *n_name; /* OFW network media name */ int n_type; /* IFT */ } ofw_types[] = { { "atm", IFT_ATM }, { "ethernet", IFT_ETHER }, { "fddi", IFT_FDDI }, { "token-ring", IFT_ISO88025 }, { "ipib", IFT_IB } }; /* * given the mac type, initialize the mac interface state. */ void mac_init(char *bootdevicename) { int type = 0; static char *mtu_name = "max-frame-size"; static char *chosen_net = "chosen-network-type"; static char *supported_net = "supported-network-types"; static char *netiftype = "network-interface-type"; pnode_t node; char *wp, *media_type; int len = 0, i; char tmpbuf[MAXNAMELEN]; char devname[MAXNAMELEN]; if (initialized) return; mac_state.mac_in_timeout = MAC_IN_TIMEOUT; #ifdef DEBUG printf("mac_init: device path: %s\n", bootdevicename); #endif /* DEBUG */ if ((mac_state.mac_dev = prom_open(bootdevicename)) == 0) { (void) snprintf(tmpbuf, sizeof (tmpbuf), "Cannot prom_open network device %s.", bootdevicename); prom_panic(tmpbuf); } (void) prom_devname_from_pathname(bootdevicename, devname); #ifdef DEBUG printf("mac_init: Network device name: %s\n", devname); #endif /* DEBUG */ /* * Ask the prom for our MTU and media type. "chosen-network-type" * is of the form of ",,, * : e.g.: "ethernet,100,rj45,full" */ node = prom_finddevice(devname); if (node != OBP_NONODE && node != OBP_BADNODE) { if (prom_getproplen(node, mtu_name) == sizeof (ihandle_t)) { (void) prom_getprop(node, mtu_name, (caddr_t)&mac_state.mac_mtu); } bzero(tmpbuf, sizeof (tmpbuf)); /* * The following order of looking for properties is * from FWARC 2002/345. */ if ((len = prom_getproplen(node, netiftype)) > 0 && len < sizeof (tmpbuf)) { (void) prom_getprop(node, netiftype, tmpbuf); } else if ((len = prom_getproplen(node, chosen_net)) > 0 && len < sizeof (tmpbuf)) { (void) prom_getprop(node, chosen_net, tmpbuf); } else if ((len = prom_getproplen(node, supported_net)) > 0 && len < sizeof (tmpbuf)) { (void) prom_getprop(node, supported_net, tmpbuf); } media_type = NULL; if (len > 0) { if ((wp = strstr(tmpbuf, ",")) != NULL) *wp = '\0'; media_type = tmpbuf; } if (media_type != NULL) { #ifdef DEBUG printf("mac_init: Media type: %s\n", media_type); #endif /* DEBUG */ for (i = 0; i < sizeof (ofw_types) / sizeof (struct ofw_net_types); i++) { if (strcmp(ofw_types[i].n_name, media_type) == 0) { type = ofw_types[i].n_type; break; } } } } switch (type) { case IFT_ATM: /* * ATM is currently treated mostly like ethernet, * with the exception that the MTU is most likely * different. */ mac_state.mac_type = IFT_ATM; mac_state.mac_arp_timeout = ATM_ARP_TIMEOUT; mac_state.mac_in_timeout = ATM_IN_TIMEOUT; if (mac_state.mac_mtu == 0) mac_state.mac_mtu = ATMSIZE; mac_state.mac_addr_len = sizeof (ether_addr_t); mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len); if (mac_state.mac_addr_buf == NULL) prom_panic("mac_init: Cannot allocate memory."); if (prom_getmacaddr(mac_state.mac_dev, (caddr_t)mac_state.mac_addr_buf) != 0) prom_panic("mac_init: Cannot obtain MAC address."); mac_state.mac_arp = ether_arp; mac_state.mac_rarp = ether_revarp; mac_state.mac_header_len = ether_header_len; mac_state.mac_input = ether_input; mac_state.mac_output = ether_output; break; case IFT_FDDI: /* * FDDI is currently treated mostly like ethernet, * with the exception that the MTU is most likely * different. */ mac_state.mac_type = IFT_FDDI; mac_state.mac_arp_timeout = FDDI_ARP_TIMEOUT; mac_state.mac_in_timeout = FDDI_IN_TIMEOUT; if (mac_state.mac_mtu == 0) mac_state.mac_mtu = FDDISIZE; mac_state.mac_addr_len = sizeof (ether_addr_t); mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len); if (mac_state.mac_addr_buf == NULL) prom_panic("mac_init: Cannot allocate memory."); if (prom_getmacaddr(mac_state.mac_dev, (caddr_t)mac_state.mac_addr_buf) != 0) prom_panic("mac_init: Cannot obtain MAC address."); mac_state.mac_arp = ether_arp; mac_state.mac_rarp = ether_revarp; mac_state.mac_header_len = ether_header_len; mac_state.mac_input = ether_input; mac_state.mac_output = ether_output; break; case IFT_ISO88025: /* * Token ring is currently treated mostly like ethernet, * with the exception that the MTU is most likely different. */ mac_state.mac_type = IFT_ISO88025; mac_state.mac_arp_timeout = TOKEN_ARP_TIMEOUT; mac_state.mac_in_timeout = TOKEN_IN_TIMEOUT; if (mac_state.mac_mtu == 0) mac_state.mac_mtu = TOKENSIZE; mac_state.mac_addr_len = sizeof (ether_addr_t); mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len); if (mac_state.mac_addr_buf == NULL) prom_panic("mac_init: Cannot allocate memory."); if (prom_getmacaddr(mac_state.mac_dev, (caddr_t)mac_state.mac_addr_buf) != 0) prom_panic("mac_init: Cannot obtain MAC address."); mac_state.mac_arp = ether_arp; mac_state.mac_rarp = ether_revarp; mac_state.mac_header_len = ether_header_len; mac_state.mac_input = ether_input; mac_state.mac_output = ether_output; break; case IFT_IB: mac_state.mac_type = IFT_IB; ibd_init(); break; case IFT_ETHER: /* FALLTHRU - default to ethernet */ default: mac_state.mac_type = IFT_ETHER; mac_state.mac_mtu = ETHERSIZE; mac_state.mac_arp_timeout = ETHER_ARP_TIMEOUT; mac_state.mac_in_timeout = ETHER_IN_TIMEOUT; if (mac_state.mac_mtu == 0) mac_state.mac_mtu = ETHERSIZE; mac_state.mac_addr_len = sizeof (ether_addr_t); mac_state.mac_addr_buf = bkmem_alloc(mac_state.mac_addr_len); if (mac_state.mac_addr_buf == NULL) prom_panic("mac_init: Cannot allocate memory."); if (prom_getmacaddr(mac_state.mac_dev, (caddr_t)mac_state.mac_addr_buf) != 0) prom_panic("mac_init: Cannot obtain MAC address."); mac_state.mac_arp = ether_arp; mac_state.mac_rarp = ether_revarp; mac_state.mac_header_len = ether_header_len; mac_state.mac_input = ether_input; mac_state.mac_output = ether_output; break; } mac_state.mac_buf = bkmem_alloc(mac_state.mac_mtu); if (mac_state.mac_buf == NULL) prom_panic("mac_init: Cannot allocate netbuf memory."); else initialized = B_TRUE; } void mac_fini() { if (mac_state.mac_addr_buf != NULL) { bkmem_free((caddr_t)mac_state.mac_addr_buf, mac_state.mac_addr_len); mac_state.mac_addr_buf = NULL; } if (mac_state.mac_buf != NULL) { bkmem_free(mac_state.mac_buf, mac_state.mac_mtu); mac_state.mac_buf = NULL; } (void) prom_close(mac_state.mac_dev); initialized = B_FALSE; } /* MAC layer specific socket initialization */ void mac_socket_init(struct inetboot_socket *isp) { isp->input[MEDIA_LVL] = mac_state.mac_input; isp->output[MEDIA_LVL] = mac_state.mac_output; isp->close[MEDIA_LVL] = NULL; isp->headerlen[MEDIA_LVL] = mac_state.mac_header_len; isp->in_timeout = mac_state.mac_in_timeout; } /* * Add an entry to the ARP table. All values in table are network order. * No checking is done to determine whether there's duplicates. */ void mac_set_arp(struct in_addr *ip, void *hp, int hl) { atable[arp_index].ia.s_addr = ip->s_addr; bcopy(hp, (char *)atable[arp_index].ha, hl); atable[arp_index].hl = hl; arp_index++; if (arp_index >= ARP_TABLE_SIZE) arp_index = 0; } /* * Retrieve an entry from the ARP table using network-order IP address as * search criteria. HW address buffer is filled in up to hl in len. (make * sure the buffer is big enough given the mac type) * * Returns TRUE if successful, FALSE otherwise. Will wait timeout milliseconds * for a response. */ int mac_get_arp(struct in_addr *ip, void *hp, int hl, uint32_t timeout) { int i, result; for (i = 0; i < ARP_TABLE_SIZE; i++) { if (ip->s_addr == atable[i].ia.s_addr) { bcopy((char *)atable[i].ha, hp, hl); return (TRUE); } } /* Not found. ARP for it. */ bzero(hp, hl); result = mac_state.mac_arp(ip, hp, timeout); if (result) { /* Cool - add it to the arp table */ mac_set_arp(ip, hp, hl); } return (result); } int mac_get_mtu(void) { if (!initialized) return (-1); else return (mac_state.mac_mtu); } int mac_get_dev(void) { if (!initialized) return (-1); else return (mac_state.mac_dev); } uint8_t * mac_get_addr_buf(void) { if (!initialized) return (NULL); else return (mac_state.mac_addr_buf); } int mac_get_addr_len(void) { if (!initialized) return (-1); else return (mac_state.mac_addr_len); } int mac_get_type(void) { if (!initialized) return (-1); else return (mac_state.mac_type); } void mac_set_arp_timeout(unsigned int timeout) { mac_state.mac_arp_timeout = timeout; } int mac_get_arp_timeout(void) { if (!initialized) return (-1); else return (mac_state.mac_arp_timeout); } int mac_get_hdr_len(void) { if (!initialized) return (-1); else return (mac_state.mac_header_len(NULL)); } int mac_call_arp(struct in_addr *addr, void *buf, uint32_t timeout) { return (mac_state.mac_arp(addr, buf, timeout)); } void mac_call_rarp(void) { mac_state.mac_rarp(); } /* * Map a IFT_ type to an RFC 1700 arp hwtype. */ uint8_t mac_arp_type(uint8_t ift_type) { uint8_t arptype; switch (ift_type) { case IFT_ISO88025: arptype = 4; /* token ring */ break; case IFT_ATM: arptype = 16; /* ATM */ break; case IFT_FDDI: arptype = 18; /* Fiber Channel */ break; case IFT_IB: arptype = 32; /* Infiniband */ break; case IFT_ETHER: /* FALLTHRU */ default: arptype = 1; /* default to ethernet */ break; } return (arptype); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * mac.h contains MAC layer independent definttions */ #ifndef _MAC_H #define _MAC_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif extern int mac_call_arp(struct in_addr *, void *, uint32_t); extern void mac_call_rarp(void); extern void mac_init(char *); /* initialize MAC layer */ extern void mac_fini(void); /* tear down MAC layer */ extern uint8_t *mac_get_addr_buf(void); extern int mac_get_addr_len(void); extern int mac_get_arp_timeout(void); extern int mac_get_hdr_len(void); extern int mac_get_mtu(void); extern int mac_get_type(void); extern int mac_get_arp(struct in_addr *, void *, int, uint32_t); extern int mac_get_dev(void); extern uint8_t mac_arp_type(uint8_t); extern void mac_set_arp_timeout(unsigned int); extern struct mac_type mac_state; /* in mac.c */ #ifdef __cplusplus } #endif #endif /* _MAC_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * mac_impl.h contains internal MAC layer independent definttions */ #ifndef _MAC_IMPL_H #define _MAC_IMPL_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif extern boolean_t initialized; /* TRUE if network device initialized */ extern int arp_index; /* current arp table index */ struct mac_type { int mac_type; /* if_types.h */ int mac_dev; int mac_mtu; caddr_t mac_buf; /* MTU sized buffer */ uint8_t *mac_addr_buf; uint32_t mac_arp_timeout; uint32_t mac_in_timeout; uint32_t mac_in_timeo_incr; int mac_addr_len; int (*mac_arp)(struct in_addr *, void *, uint32_t); void (*mac_rarp)(void); int (*mac_header_len)(struct inetgram *); int (*mac_input)(int); int (*mac_output)(int, struct inetgram *); }; #define ARP_TABLE_SIZE (3) /* size of ARP table */ #define HW_ADDR_SIZE (128) /* max size of hardware address */ #define MAC_IN_TIMEOUT (10) /* collect IP grams for X mseconds. */ #define MAC_IN_TIMEO_MULT (8) /* Multiplier to arrive at maximum */ /* format of an arp table entry */ struct arptable { struct in_addr ia; uchar_t ha[HW_ADDR_SIZE]; int hl; }; extern void mac_set_arp(struct in_addr *, void *, int); extern void mac_socket_init(struct inetboot_socket *); #ifdef __cplusplus } #endif #endif /* _MAC_IMPL_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1990-1999, Sun Microsystems, Inc. * All rights reserved. * * Token ring implementation-specific definitions */ #ifndef _TOKEN_INET_H #define _TOKEN_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #define TOKENSIZE (17800) /* Default Token Ring MTU size */ #define TOKEN_ARP_TIMEOUT (300000) /* in milliseconds */ #define TOKEN_IN_TIMEOUT (8) /* millisecond wait for IP frames */ #ifdef __cplusplus } #endif #endif /* _TOKEN_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1991-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * udp.c, Code implementing the UDP internet protocol. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include #include "udp_inet.h" #include "ipv4.h" #include "ipv4_impl.h" #include "mac.h" #include "mac_impl.h" #include "v4_sum_impl.h" #include /* Checksum all architectures */ static int udp_cksum_flag = TRUE; /* checksum on if set */ /* * Initialize the udp-specific parts of a socket. */ void udp_socket_init(struct inetboot_socket *isp) { isp->type = INETBOOT_DGRAM; isp->proto = IPPROTO_UDP; isp->input[TRANSPORT_LVL] = udp_input; isp->output[TRANSPORT_LVL] = udp_output; isp->close[TRANSPORT_LVL] = NULL; isp->headerlen[TRANSPORT_LVL] = udp_header_len; isp->ports = udp_ports; } /* * Return the size of an UDP header */ /* ARGSUSED */ int udp_header_len(struct inetgram *igm) { return (sizeof (struct udphdr)); } /* * Return the requested port number in network order. */ in_port_t udp_ports(uint16_t *udphp, enum Ports request) { if (request == SOURCE) return (((struct udphdr *)udphp)->uh_sport); return (((struct udphdr *)udphp)->uh_dport); } /* * Process the IPv4 datagram that IPv4 has given us. We: * * 1) Checksum the datagram if checksum is turned on. * 2) Strip the udp header from the inetgram. * 3) Return the number of TRANSPORT frames for success, -1 if a * failure occurred. * * Arguments: index: index into the open socket table, ip is the inetgram * we got from IPv4, which will contain the udp header and all the data. */ int udp_input(int index) { int frames = 0, header_len; struct inetgram *igp, *ugp = NULL; struct udphdr *udphp; mblk_t *mp; #ifdef DEBUG printf("udp_input(%d) ###############################\n", index); #endif while ((igp = sockets[index].inq) != NULL) { if (igp->igm_level != TRANSPORT_LVL) { #ifdef DEBUG printf("udp_input(%d): level %d datagram discarded.\n", index, igp->igm_level); #endif /* DEBUG */ del_gram(&sockets[index].inq, igp, TRUE); continue; } mp = igp->igm_mp; udphp = (struct udphdr *)(mp->b_rptr + IPH_HDR_LENGTH(mp->b_rptr)); header_len = (sockets[index].headerlen[TRANSPORT_LVL])(NULL); mp->b_rptr = ((unsigned char *)udphp) + header_len; mp->b_wptr = ((unsigned char *)udphp) + ntohs(udphp->uh_ulen); /* generate checksum */ if (udp_cksum_flag && udphp->uh_sum != 0) { if (udp_chksum(udphp, &igp->igm_saddr.sin_addr, &igp->igm_target, sockets[index].proto) != 0) { dprintf("udp_input(%d): bad udp chksum " "from %s.\n", index, inet_ntoa(igp->igm_saddr.sin_addr)); del_gram(&sockets[index].inq, igp, TRUE); continue; } } /* validate port number */ if (sockets[index].bind.sin_port != udphp->uh_dport) { dprintf("udp_input(%d): Unexpected port number: " "%d != %d from %s.\n", index, ntohs(udphp->uh_dport), ntohs( sockets[index].bind.sin_port), inet_ntoa(igp->igm_saddr.sin_addr)); del_gram(&sockets[index].inq, igp, TRUE); continue; } igp->igm_level = APP_LVL; del_gram(&sockets[index].inq, igp, FALSE); add_grams(&ugp, igp); frames++; } add_grams(&sockets[index].inq, ugp); return (frames); } /* * Create a UDP datagram given the data and sockaddr_in we got from sendto(). * We will calculate the checksum if checksumming is turned on, and fill in * appropriate length and port fields. We convert the inetgram from a * block of data into a udp datagram... Returns the number of bytes contained * in the udp datagram (including header). * * Arguments: index: index into the open socket table, ogp is the inetgram * we got from sendto(), which will contain just the data and sockaddr_in. */ int udp_output(int index, struct inetgram *ogp) { struct udphdr *udphp; mblk_t *mp; #ifdef DEBUG printf("udp_output(%d): 0x%x, %d\n", index, ogp->igm_mp, ogp->igm_mp->b_wptr - ogp->igm_mp->b_rptr); #endif /* DEBUG */ mp = ogp->igm_mp; mp->b_rptr -= sizeof (struct udphdr); udphp = (struct udphdr *)(mp->b_rptr); udphp->uh_dport = ogp->igm_saddr.sin_port; if (sockets[index].bound) udphp->uh_sport = sockets[index].bind.sin_port; else udphp->uh_sport = ogp->igm_saddr.sin_port; udphp->uh_ulen = htons(mp->b_wptr - mp->b_rptr); udphp->uh_sum = 0; if (udp_cksum_flag) { udphp->uh_sum = udp_chksum(udphp, &sockets[index].bind.sin_addr, &ogp->igm_saddr.sin_addr, sockets[index].proto); } ogp->igm_level = NETWORK_LVL; return (0); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1990-1999, 2001-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * UDP implementation-specific definitions */ #ifndef _UDP_INET_H #define _UDP_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif extern int udp_header_len(struct inetgram *); extern in_port_t udp_ports(uint16_t *, enum Ports); extern int udp_input(int); extern int udp_output(int, struct inetgram *); extern void udp_socket_init(struct inetboot_socket *); #ifdef __cplusplus } #endif #endif /* _UDP_INET_H */ #!/bin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2005 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" echo_file usr/src/lib/Makefile.lib echo_file usr/src/stand/lib/Makefile.com echo_file usr/src/stand/lib/Makefile.sparc echo_file usr/src/stand/lib/Makefile.targ echo_file usr/src/psm/Makefile.psm.64 find_files "s.*.h" usr/src/psm/stand/sys find_files "s.*.h" usr/src/stand find_files "s.*.h" usr/src/uts # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # LIBRARY = libsa.a LOCOBJS = assert.o ctype.o errno.o libintl.o malloc.o memlist.o \ standalloc.o stdio.o stdlib.o strdup.o strings.o \ time.o unistd.o CMNOBJS = cache.o diskread.o fsswitch.o promfs.o sparc_CMNUTILOBJS = memchr.o memmove.o CMNUTILOBJS = $($(MACH)_CMNUTILOBJS) \ bsearch.o memcmp.o memcpy.o memset.o qsort.o \ string.o strtol.o strtoul.o multi3.o i386_MACHOBJS = get.o map_prog.o sparc_MACHOBJS = prom_misc.o MACHOBJS = $($(MACH)_MACHOBJS) i386_ASMOBJS = _setjmp.o samuldiv64.o sparc_ASMOBJS = _setjmp.o ASMOBJS = $($(MACH)_ASMOBJS) OBJECTS = $(LOCOBJS) $(CMNOBJS) $(CMNUTILOBJS) $(MACHOBJS) $(ASMOBJS) include ../Makefile.com CMNDIR = ../fs/common CMNUTILDIR = $(TOPDIR)/common/util SRCS = $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(CMNOBJS:%.o=$(CMNDIR)/%.c) \ $(CMNUTILOBJS:%.o=$(CMNUTILDIR)/%.c) \ $($(MACH)_ASMOBJS:%.o=$(MACH)/%.s) \ $($(MACH)_OBJS:%.o=$(MACH)/%.c) LDLIBS += -lsock CPPFLAGS += $(SOCKCPPFLAGS) CERRWARN += -Wno-parentheses CERRWARN += $(CNOWARN_UNINIT) objs/%.o: $(MACH)/%.s $(COMPILE.s) -o $@ $< $(POST_PROCESS_O) objs/%.o: $(MACH)/%.c $(COMPILE.c) -o $@ $< $(POST_PROCESS_O) objs/%.o: $(CMNUTILDIR)/%.c $(COMPILE.c) -o $@ $< $(POST_PROCESS_O) include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_ARPA_INET_H #define _SA_ARPA_INET_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libsocket's . * All standalone code *must* use this header rather than libsockets's. * * Since all the sources that #include this file do it spuriously, we provide * no definitions. Note that we do this rather than removing the errant * #includes because the code they live in (openssl) is third-party and we're * still receiving code drops for it. */ #endif /* _SA_ARPA_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include void __assert(const char *assertion, const char *file, int line) { char panicmsg[1024]; (void) snprintf(panicmsg, sizeof (panicmsg), "assertion failed: " "%s, file: %s, line: %d", assertion, file, line); prom_panic(panicmsg); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_ASSERT_H #define _SA_ASSERT_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #ifdef __cplusplus extern "C" { #endif extern void __assert(const char *, const char *, int); #ifdef __cplusplus } #endif #endif /* _SA_ASSERT_H */ /* * Note that the ANSI C Standard requires all headers to be idempotent except * which is explicitly required not to be idempotent (section 4.1.2). * Therefore, it is by intent that the header guards (#ifndef _SA_ASSERT_H) do * not span this entire file. */ #undef assert #ifdef NDEBUG #define assert(EX) ((void)0) #else #define assert(EX) (void)((EX) || (__assert(#EX, __FILE__, __LINE__), 0)) #endif /* NDEBUG */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1992-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include int tolower(int c) { /* standalone only supports the C locale */ if ((c >= 'A') && (c <= 'Z')) c += 'a' - 'A'; return (c); } int toupper(int c) { /* standalone only supports the C locale */ if ((c >= 'a') && (c <= 'z')) c -= 'a' - 'A'; return (c); } unsigned char __ctype[129] = { 0, /* EOF */ _C, _C, _C, _C, _C, _C, _C, _C, _C, _S|_C, _S|_C, _S|_C, _S|_C, _S|_C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _S|_B, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _N|_X, _N|_X, _N|_X, _N|_X, _N|_X, _N|_X, _N|_X, _N|_X, _N|_X, _N|_X, _P, _P, _P, _P, _P, _P, _P, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _P, _P, _P, _P, _P, _P, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _P, _P, _P, _P, _C, }; /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ #ifndef _SA_CTYPE_H #define _SA_CTYPE_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #ifdef __cplusplus extern "C" { #endif #define _U 0x00000001 /* Upper case */ #define _L 0x00000002 /* Lower case */ #define _N 0x00000004 /* Numeral (digit) */ #define _S 0x00000008 /* Spacing character */ #define _P 0x00000010 /* Punctuation */ #define _C 0x00000020 /* Control character */ #define _B 0x00000040 /* Blank */ #define _X 0x00000080 /* heXadecimal digit */ #define isalpha(c) ((__ctype + 1)[c] & (_U | _L)) #define isupper(c) ((__ctype + 1)[c] & _U) #define islower(c) ((__ctype + 1)[c] & _L) #define isdigit(c) ((__ctype + 1)[c] & _N) #define isxdigit(c) ((__ctype + 1)[c] & _X) #define isalnum(c) ((__ctype + 1)[c] & (_U | _L | _N)) #define isspace(c) ((__ctype + 1)[c] & _S) #define ispunct(c) ((__ctype + 1)[c] & _P) #define isprint(c) ((__ctype + 1)[c] & (_P | _U | _L | _N | _B)) #define isgraph(c) ((__ctype + 1)[c] & (_P | _U | _L | _N)) #define iscntrl(c) ((__ctype + 1)[c] & _C) #define isascii(c) (!((c) & ~0177)) extern unsigned char __ctype[]; /* * Some header files define their own macros for tolower/toupper which mangle * our prototypes -- thus only provide ours if no macros have been defined. */ #ifndef tolower extern int tolower(int); #endif #ifndef toupper extern int toupper(int); #endif #ifdef __cplusplus } #endif #endif /* _SA_CTYPE_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_DIRENT_H #define _SA_DIRENT_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #include #ifdef __cplusplus extern "C" { #endif typedef struct DIR DIR; extern DIR *opendir(const char *); extern struct dirent *readdir(DIR *); extern int closedir(DIR *); #ifdef __cplusplus } #endif #endif /* _SA_DIRENT_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include int errno; static char errmsgbuf[1024]; /* * Trivial standalone error-to-string routine; someday it might be worth * making this print actual strings like libc (or, better yet, share libc's * implementation). */ char * strerror(int errnum) { (void) snprintf(errmsgbuf, sizeof (errmsgbuf), "ERRNO: %d", errnum); return (errmsgbuf); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_ERRNO_H #define _SA_ERRNO_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #ifdef __cplusplus extern "C" { #endif extern int errno; #ifdef __cplusplus } #endif #endif /* _SA_ERRNO_H */ #!/bin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" find_files "s.*" usr/src/common/util find_files "s.*" usr/src/stand/lib/fs/common /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include /* * Get a localized string. Since localization is not * supported in the sa environment just return the * pointer to the msgid. */ /*ARGSUSED*/ char * dgettext(const char *domainname, const char *msgid) { return ((char *)msgid); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_LIBINTL_H #define _SA_LIBINTL_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libintl's . * All standalone code *must* use this header rather than libintl's. */ #ifdef __cplusplus extern "C" { #endif #define TEXT_DOMAIN "None" extern char *dgettext(const char *, const char *); #ifdef __cplusplus } #endif #endif /* _SA_LIBINTL_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_LIMITS_H #define _SA_LIMITS_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. * * Since all the sources that #include this file do it spuriously, we provide * no definitions. Note that we do this rather than removing the errant * #includes because the code they live in (openssl) is third-party and we're * still receiving code drops for it. */ #endif /* _SA_LIMITS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include /* * For documentation on these functions, see malloc(3C). */ void * malloc(size_t size) { size_t *iaddr; iaddr = (size_t *)bkmem_alloc(size + sizeof (size_t)); if (iaddr == NULL) { errno = ENOMEM; return (NULL); } iaddr[0] = size; return (&iaddr[1]); } void * calloc(size_t number, size_t size) { void *addr; addr = malloc(number * size); if (addr == NULL) return (NULL); return (memset(addr, 0, number * size)); } void * realloc(void *oldaddr, size_t size) { void *addr; size_t oldsize; addr = malloc(size); if (oldaddr != NULL) { oldsize = ((size_t *)oldaddr)[-1]; if (addr != NULL) { bcopy(oldaddr, addr, (oldsize > size ? oldsize : size)); free(oldaddr); } } return (addr); } void free(void *addr) { size_t *lenloc; if (addr == NULL) return; lenloc = (size_t *)addr - 1; bkmem_free((caddr_t)lenloc, *lenloc + sizeof (size_t)); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_MATH_H #define _SA_MATH_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libm's . * All standalone code *must* use this header rather than libm's. * * Since all the sources that #include this file do it spuriously, we provide * no definitions. Note that we do this rather than removing the errant * #includes because the code they live in (openssl) is third-party and we're * still receiving code drops for it. */ #endif /* _SA_MATH_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_MD5_H #define _SA_MD5_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libmd5's . * All standalone code *must* use this header rather than libmd5's. */ #include #endif /* _SA_MD5_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2010 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include #include #include #include #include #include caddr_t memlistpage; /* Always pts to the next free link in the headtable */ /* i.e. it is always memlistpage+tableoffset */ caddr_t tablep = NULL; static int table_freespace; /* * Function prototypes */ extern void reset_alloc(void); void print_memlist(struct memlist *av) { struct memlist *p = av; while (p != NULL) { printf("addr = 0x%x:0x%x, size = 0x%x:0x%x\n", (uint_t)(p->ml_address >> 32), (uint_t)p->ml_address, (uint_t)(p->ml_size >> 32), (uint_t)p->ml_size); p = p->ml_next; } } /* allocate room for n bytes, return 8-byte aligned address */ void * getlink(uint_t n) { void *p; extern int pagesize; if (memlistpage == NULL) reset_alloc(); if (tablep == NULL) { /* * Took the following 2 lines out of above test for * memlistpage == null so we can initialize table_freespace */ table_freespace = pagesize - sizeof (struct bsys_mem); tablep = memlistpage + sizeof (struct bsys_mem); tablep = (caddr_t)roundup((uintptr_t)tablep, 8); } if (n == 0) return (NULL); n = roundup(n, 8); p = tablep; table_freespace -= n; tablep += n; if (table_freespace <= 0) { char buf[80]; (void) sprintf(buf, "Boot getlink(): no memlist space (need %d)\n", n); prom_panic(buf); } return (p); } /* * This is the number of memlist structures allocated in one shot. kept * to small number to reduce wastage of memory, it should not be too small * to slow down boot. */ #define ALLOC_SZ 5 static struct memlist *free_memlist_ptr = NULL; /* * Free memory lists are maintained as simple single linked lists. * get_memlist_struct returns a memlist structure without initializing * any of the fields. It is caller's responsibility to do that. */ struct memlist * get_memlist_struct(void) { struct memlist *ptr; int i; if (free_memlist_ptr == NULL) { ptr = free_memlist_ptr = getlink(ALLOC_SZ * sizeof (struct memlist)); bzero(free_memlist_ptr, (ALLOC_SZ * sizeof (struct memlist))); for (i = 0; i < ALLOC_SZ; i++) ptr[i].ml_next = &ptr[i+1]; ptr[i-1].ml_next = NULL; } ptr = free_memlist_ptr; free_memlist_ptr = ptr->ml_next; return (ptr); } /* * Return memlist structure to free list. */ void add_to_freelist(struct memlist *ptr) { struct memlist *tmp; if (free_memlist_ptr == NULL) { free_memlist_ptr = ptr; } else { for (tmp = free_memlist_ptr; tmp->ml_next; tmp = tmp->ml_next) ; tmp->ml_next = ptr; } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ /* All Rights Reserved */ /* * Portions of this source code were derived from Berkeley 4.3 BSD * under license from the Regents of the University of California. */ #ifndef _SA_NETDB_H #define _SA_NETDB_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libnsl's . * All standalone code *must* use this header rather than libnsl's. */ #ifdef __cplusplus extern "C" { #endif #define MAXHOSTNAMELEN 256 #define HOST_NOT_FOUND 1 /* Authoritive Answer Host not found */ #define TRY_AGAIN 2 /* Non-Authoritive Host not found, or SERVERFAIL */ #define NO_RECOVERY 3 /* Non recoverable errors, FORMERR, REFUSED, NOTIMP */ #define NO_DATA 4 /* Valid name, no data record of requested type */ struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses from name server */ #define h_addr h_addr_list[0] /* address, for backward compatiblity */ }; extern int h_errno; extern struct hostent *gethostbyname(const char *); #ifdef __cplusplus } #endif #endif /* _SA_NETDB_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include #include #include #include #include #ifdef DEBUG static int resalloc_debug = 1; #else /* DEBUG */ static int resalloc_debug = 0; #endif /* DEBUG */ #define dprintf if (resalloc_debug) printf extern caddr_t resalloc(enum RESOURCES type, size_t bytes, caddr_t virthint, int align); extern void resfree(enum RESOURCES type, caddr_t virtaddr, size_t bytes); extern int pagesize; /* * This routine should be called get_a_page(). * It allocates from the appropriate entity one or * more pages and maps them in. */ caddr_t kern_resalloc(caddr_t virthint, size_t size, int align) { if (virthint != 0) return (resalloc(RES_CHILDVIRT, size, virthint, align)); else { return (resalloc(RES_BOOTSCRATCH, size, NULL, NULL)); } } /* * This is called only on sparcv9 for freeing scratch memory. * The standalone allocator cannot free other types of memory. */ void kern_resfree(caddr_t virtaddr, size_t size) { resfree(RES_BOOTSCRATCH, virtaddr, size); } int get_progmemory(caddr_t vaddr, size_t size, int align) { uintptr_t n; /* * if the vaddr given is not a mult of PAGESIZE, * then we rounddown to a page, but keep the same * ending addr. */ n = (uintptr_t)vaddr & (pagesize - 1); if (n) { vaddr -= n; size += n; } dprintf("get_progmemory: requesting %lx bytes at %p\n", size, (void *)vaddr); if (resalloc(RES_CHILDVIRT, size, vaddr, align) != vaddr) return (-1); return (0); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_STDARG_H #define _SA_STDARG_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #endif /* _SA_STDARG_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_STDDEF_H #define _SA_STDDEF_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #ifdef __cplusplus extern "C" { #endif #ifndef NULL #define NULL 0 #endif #ifndef offsetof #define offsetof(s, m) (size_t)(&(((s *)0)->m)) #endif #ifdef __cplusplus } #endif #endif /* _SA_STDDEF_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * "buffered" i/o functions for the standalone environment. (ugh). */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include enum { F_OPEN = 0x01, F_ERROR = 0x02, F_SEEKABLE = 0x04 }; FILE __iob[_NFILE] = { { F_OPEN, 0, 0, 0, "stdin" }, { F_OPEN, 1, 0, 0, "stdout" }, { F_OPEN, 2, 0, 0, "stderr" } }; static boolean_t fcheck(FILE *stream, int flags) { errno = 0; if ((stream->_flag & flags) != flags) { errno = EBADF; return (B_FALSE); } return (B_TRUE); } int fclose(FILE *stream) { if (!fcheck(stream, F_OPEN)) return (EOF); (void) close(stream->_file); stream->_flag = 0; stream->_file = -1; stream->_name[0] = '\0'; return (0); } int feof(FILE *stream) { if (!fcheck(stream, F_OPEN)) return (0); return (stream->_len == stream->_offset); } int ferror(FILE *stream) { if (!fcheck(stream, F_OPEN)) return (0); return ((stream->_flag & F_ERROR) != 0); } void clearerr(FILE *stream) { stream->_flag &= ~F_ERROR; } int fflush(FILE *stream) { if (!fcheck(stream, F_OPEN)) return (EOF); /* Currently, a nop */ return (0); } char * fgets(char *s, int n, FILE *stream) { int bytes; ssize_t cnt; if (!fcheck(stream, F_OPEN)) return (NULL); for (bytes = 0; bytes < (n - 1); ++bytes) { cnt = read(stream->_file, &s[bytes], 1); if (cnt < 0) { if (bytes != 0) { s[bytes] = '\0'; return (s); } else { stream->_flag |= F_ERROR; return (NULL); } } else if (cnt == 0) { /* EOF */ if (bytes != 0) { s[bytes] = '\0'; return (s); } else return (NULL); } else { stream->_offset++; if (s[bytes] == '\n') { s[bytes + 1] = '\0'; return (s); } } } s[bytes] = '\0'; return (s); } /* * We currently only support read-only ("r" mode) opens and unbuffered I/O. */ FILE * fopen(const char *filename, const char *mode) { FILE *stream; const char *t; int fd, i; errno = 0; /* * Make sure we have a filesystem underneath us before even trying. */ if (get_default_fs() == NULL) return (NULL); for (t = mode; t != NULL && *t != '\0'; t++) { switch (*t) { case 'b': /* We ignore this a'la ISO C standard conformance */ break; case 'r': /* We ignore this because we always open for reading */ break; case 'a': case 'w': case '+': errno = EROFS; return (NULL); default: errno = EINVAL; return (NULL); } } for (i = 0; i < _NFILE; i++) { stream = &__iob[i]; if ((stream->_flag & F_OPEN) == 0) { fd = open(filename, O_RDONLY); if (fd < 0) return (NULL); stream->_file = fd; stream->_flag |= F_OPEN; (void) strlcpy(stream->_name, filename, sizeof (stream->_name)); return (stream); } } errno = EMFILE; return (NULL); } /* PRINTFLIKE1 */ void printf(const char *fmt, ...) { va_list adx; va_start(adx, fmt); prom_vprintf(fmt, adx); va_end(adx); } /* * Only writing to stderr or stdout is permitted. */ /* PRINTFLIKE2 */ int fprintf(FILE *stream, const char *format, ...) { int nwritten; va_list va; if (!fcheck(stream, F_OPEN)) return (-1); /* * Since fopen() doesn't return writable streams, the only valid * writable streams are stdout and stderr. */ if (stream != stdout && stream != stderr) { errno = EBADF; return (-1); } va_start(va, format); printf(format, va); va_end(va); va_start(va, format); nwritten = vsnprintf(NULL, 0, format, va); va_end(va); return (nwritten); } size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream) { size_t items; ssize_t bytes, totbytes = 0; char *strp = ptr; if (!fcheck(stream, F_OPEN)) return (0); for (items = 0, bytes = 0; items < nitems; items++) { bytes = read(stream->_file, &strp[totbytes], size); if (bytes < 0) { stream->_flag |= F_ERROR; return (0); } else if (bytes == 0) { /* EOF */ return ((totbytes == 0) ? 0 : totbytes / size); } else if (bytes == size) { stream->_offset += bytes; totbytes += bytes; } else { (void) lseek(stream->_file, stream->_offset, SEEK_SET); return (totbytes / size); } } return (totbytes / size); } /* * We don't grow files. */ int fseek(FILE *stream, long offset, int whence) { off_t new_offset, result; if (!fcheck(stream, F_OPEN | F_SEEKABLE)) return (-1); switch (whence) { case SEEK_SET: new_offset = (off_t)offset; break; case SEEK_CUR: new_offset = stream->_offset + (off_t)offset; break; case SEEK_END: new_offset = (off_t)stream->_len + (off_t)offset; break; default: errno = EINVAL; return (-1); } if (new_offset > (off_t)stream->_len) { errno = EFBIG; } else if (new_offset < 0L) { errno = EOVERFLOW; } else { errno = 0; } result = lseek(stream->_file, new_offset, SEEK_SET); if (result >= 0) stream->_offset = result; else stream->_flag |= F_ERROR; return (result); } long ftell(FILE *stream) { if (!fcheck(stream, F_OPEN | F_SEEKABLE)) return (0); return ((long)stream->_offset); } size_t fwrite(const void *ptr, size_t size, size_t nitems, FILE *stream) { if (!fcheck(stream, F_OPEN)) return (0); /* * Since fopen() doesn't return writable streams, the only valid * writable streams are stdout and stderr. */ if (stream != stdout && stream != stderr) { errno = EBADF; return (0); } prom_writestr(ptr, size * nitems); return (nitems); } /*ARGSUSED*/ int setvbuf(FILE *stream, char *buf, int type, size_t size) { if (!fcheck(stream, F_OPEN)) return (-1); /* Currently a nop, probably always will be. */ return (0); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_STDIO_H #define _SA_STDIO_H #pragma ident "%Z%%M% %I% %E% SMI" #include #include /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #ifdef __cplusplus extern "C" { #endif #ifndef NULL #define NULL 0 #endif #ifndef EOF #define EOF (-1) #endif /* * Flags to setvbuf() which we pretend to support. We're always really _IONBF. */ #define _IOFBF 0000 /* full buffered */ #define _IOLBF 0100 /* line buffered */ #define _IONBF 0004 /* not buffered */ typedef struct { unsigned char _flag; /* state of the stream */ int _file; /* file descriptor */ ssize_t _len; /* total len of file */ ssize_t _offset; /* offset within the file */ char _name[256]; /* name of the file (for debugging) */ } FILE; #define stdin (&__iob[0]) #define stdout (&__iob[1]) #define stderr (&__iob[2]) #define _NFILE 10 extern FILE __iob[_NFILE]; extern int fclose(FILE *); extern int feof(FILE *); extern int fflush(FILE *); extern int ferror(FILE *); extern void clearerr(FILE *); extern char *fgets(char *, int, FILE *); extern FILE *fopen(const char *, const char *); extern size_t fread(void *, size_t, size_t, FILE *); extern int fseek(FILE *, long, int); extern long ftell(FILE *); extern size_t fwrite(const void *, size_t, size_t, FILE *); extern int setvbuf(FILE *, char *, int, size_t); /* PRINTFLIKE1 */ extern void printf(const char *, ...); /* PRINTFLIKE2 */ extern int fprintf(FILE *, const char *, ...); /* PRINTFLIKE2 */ extern int sprintf(char *, const char *, ...); /* PRINTFLIKE3 */ extern size_t snprintf(char *, size_t, const char *, ...); extern int vsprintf(char *, const char *, va_list); extern size_t vsnprintf(char *, size_t, const char *, va_list); #ifdef __cplusplus } #endif #endif /* _SA_STDIO_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include /* * Trivial version of getenv() -- since standalone has no environment * variables, just return NULL. */ /* ARGSUSED */ char * getenv(const char *name) { return (NULL); } /* * Standalone's approximation of abort(). */ void abort(void) { prom_panic("fatal error; aborting"); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_STDLIB_H #define _SA_STDLIB_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #ifdef __cplusplus extern "C" { #endif extern void *malloc(size_t); extern void *calloc(size_t, size_t); extern void *realloc(void *, size_t); extern void free(void *); extern void abort(void); extern char *getenv(const char *); extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *)); extern void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); #ifdef __cplusplus } #endif #endif /* _SA_STDLIB_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include char * strdup(const char *s) { int n; char *ret; n = strlen(s) + 1; if ((ret = malloc(n)) == NULL) return (NULL); return (strcpy(ret, s)); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_STRING_H #define _SA_STRING_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #ifdef __cplusplus extern "C" { #endif #ifndef NULL #define NULL 0 /* defined here as per ISO C */ #endif extern int memcmp(const void *, const void *, size_t); extern void *memmove(void *, const void *, size_t); extern void *memset(void *, int, size_t); extern void *memcpy(void *, const void *, size_t); extern void *memchr(const void *, int, size_t); extern int strcmp(const char *, const char *); extern int strncmp(const char *, const char *, size_t); extern size_t strlen(const char *); extern char *strcat(char *, const char *); extern char *strncat(char *, const char *, size_t); extern size_t strlcat(char *, const char *, size_t); extern char *strcpy(char *, const char *); extern char *strncpy(char *, const char *, size_t); extern size_t strlcpy(char *, const char *, size_t); extern char *strchr(const char *, int); extern char *strrchr(const char *, int); extern char *strstr(const char *, const char *); extern char *strtok(char *, const char *); extern char *strerror(int); extern char *strdup(const char *); extern long strtol(const char *, char **, int); extern unsigned long strtoul(const char *, char **, int); #ifdef __cplusplus } #endif #endif /* _SA_STRING_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1998, 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" /* from SVR4.0 1.1 */ #include #include /* * NOTE: strcasecmp()/strncasecmp() are in $SRC/common/util/string.c. */ int bcmp(const void *s1, const void *s2, size_t len) { return (memcmp(s1, s2, len) != 0); } /* * NOTE: our memmove() implementation depends on the fact that this bcopy() * supports overlapping regions. */ void bcopy(const void *src, void *dest, size_t count) { const char *csrc = src; char *cdest = dest; if (count == 0) return; if (csrc < cdest && (csrc + count) > cdest) { /* overlap copy */ while (count != 0) --count, *(cdest + count) = *(csrc + count); } else { while (count != 0) --count, *cdest++ = *csrc++; } } void bzero(void *p, size_t n) { char *cp; for (cp = p; n != 0; n--) *cp++ = 0; } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_STRINGS_H #define _SA_STRINGS_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #include #ifdef __cplusplus extern "C" { #endif extern int bcmp(const void *, const void *, size_t); extern void bcopy(const void *, void *, size_t); extern void bzero(void *, size_t); extern int strcasecmp(const char *, const char *); extern int strncasecmp(const char *, const char *, size_t); #ifdef __cplusplus } #endif #endif /* _SA_STRINGS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Time routines, snagged from libc. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #define CBUFSIZ 26 static time_t start_time, secs_since_boot; const int __year_lengths[2] = { DAYS_PER_NYEAR, DAYS_PER_LYEAR }; const int __mon_lengths[2][MONS_PER_YEAR] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; /* * Initializes our "clock" to the creation date of /timestamp, which is * made on the fly for us by the web server. Thereafter, time() will keep * time sort of up to date. */ void init_boot_time(void) { struct stat sb; if (start_time == 0) { if (stat("/timestamp", &sb) < 0) prom_panic("init_boot_time: cannot stat /timestamp"); start_time = sb.st_ctim.tv_sec; secs_since_boot = prom_gettime() / 1000; } } /* * Time is crudely incremented. */ time_t time(time_t *tloc) { time_t time_now; time_now = start_time + ((prom_gettime() / 1000) - secs_since_boot); if (tloc != NULL) *tloc = time_now; if (start_time == 0) return (0); else return (time_now); } struct tm * gmtime(const time_t *clock) { static struct tm result; struct tm *tmp; long days; int rem; long y; long newy; const int *ip; tmp = &result; days = *clock / SECS_PER_DAY; rem = *clock % SECS_PER_DAY; while (rem < 0) { rem += SECS_PER_DAY; --days; } while (rem >= SECS_PER_DAY) { rem -= SECS_PER_DAY; ++days; } tmp->tm_hour = (int)(rem / SECS_PER_HOUR); rem = rem % SECS_PER_HOUR; tmp->tm_min = (int)(rem / SECS_PER_MIN); tmp->tm_sec = (int)(rem % SECS_PER_MIN); tmp->tm_wday = (int)((EPOCH_WDAY + days) % DAYS_PER_WEEK); if (tmp->tm_wday < 0) tmp->tm_wday += DAYS_PER_WEEK; y = EPOCH_YEAR; #define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400) while (days < 0 || days >= (long)__year_lengths[isleap(y)]) { newy = y + days / DAYS_PER_NYEAR; if (days < 0) --newy; days -= ((long)newy - (long)y) * DAYS_PER_NYEAR + LEAPS_THRU_END_OF(newy > 0 ? newy - 1L : newy) - LEAPS_THRU_END_OF(y > 0 ? y - 1L : y); y = newy; } tmp->tm_year = y - TM_YEAR_BASE; tmp->tm_yday = days; ip = __mon_lengths[isleap(y)]; for (tmp->tm_mon = 0; days >= ip[tmp->tm_mon]; ++(tmp->tm_mon)) days = days - ip[tmp->tm_mon]; tmp->tm_mday = (days + 1); tmp->tm_isdst = 0; return (tmp); } /* * The standalone booter runs in GMT. */ struct tm * localtime(const time_t *clock) { return (gmtime(clock)); } static char * ct_numb(char *cp, int n) { cp++; if (n >= 10) *cp++ = (n / 10) % 10 + '0'; else *cp++ = ' '; /* Pad with blanks */ *cp++ = n % 10 + '0'; return (cp); } char * asctime(const struct tm *t) { char *cp; const char *ncp; const int *tp; const char *Date = "Day Mon 00 00:00:00 1900\n"; const char *Day = "SunMonTueWedThuFriSat"; const char *Month = "JanFebMarAprMayJunJulAugSepOctNovDec"; static char cbuf[CBUFSIZ]; cp = cbuf; for (ncp = Date; *cp++ = *ncp++; /* */); ncp = Day + (3 * t->tm_wday); cp = cbuf; *cp++ = *ncp++; *cp++ = *ncp++; *cp++ = *ncp++; cp++; tp = &t->tm_mon; ncp = Month + ((*tp) * 3); *cp++ = *ncp++; *cp++ = *ncp++; *cp++ = *ncp++; cp = ct_numb(cp, *--tp); cp = ct_numb(cp, *--tp + 100); cp = ct_numb(cp, *--tp + 100); --tp; cp = ct_numb(cp, *tp + 100); if (t->tm_year < 100) { /* Common case: "19" already in buffer */ cp += 2; } else if (t->tm_year < 8100) { cp = ct_numb(cp, (1900 + t->tm_year) / 100); cp--; } else { /* Only 4-digit years are supported */ errno = EOVERFLOW; return (NULL); } (void) ct_numb(cp, t->tm_year + 100); return (cbuf); } char * ctime(const time_t *t) { return (asctime(localtime(t))); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_TIME_H #define _SA_TIME_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #ifdef __cplusplus extern "C" { #endif struct tm { int tm_sec; /* seconds after the minute */ int tm_min; /* minutes after the hour */ int tm_hour; /* hour since midnight */ int tm_mday; /* day of the month */ int tm_mon; /* months since January */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday */ int tm_yday; /* Days since January 1 */ int tm_isdst; /* flag for alternate daylight savings time */ }; extern time_t time(time_t *); extern char *ctime(const time_t *t); extern struct tm *gmtime(const time_t *); extern struct tm *localtime(const time_t *); /* * The following silly #defines are actually ripped off from . * Since is not a documented header, it seemed better to just * inline them here rather than having a full-blown of our own. */ #define EPOCH_YEAR 1970 #define EPOCH_WDAY 4 #define SECS_PER_MIN 60 #define DAYS_PER_WEEK 7 #define DAYS_PER_NYEAR 365 #define DAYS_PER_LYEAR 366 #define MONS_PER_YEAR 12 #define SECS_PER_HOUR (SECS_PER_MIN * 60) #define SECS_PER_DAY (SECS_PER_HOUR * 24) #define TM_YEAR_BASE 1900 #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) #ifdef __cplusplus } #endif #endif /* _SA_TIME_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include static char hostname[MAXHOSTNAMELEN] = "UNKNOWN"; /* * Get system hostname */ int gethostname(char *name, int namelen) { (void) strlcpy(name, hostname, MIN(namelen, MAXHOSTNAMELEN)); return (0); } /* * Set system hostname */ int sethostname(char *name, int namelen) { (void) strlcpy(hostname, name, MIN(namelen + 1, MAXHOSTNAMELEN)); return (0); } /* * Get the current PID; in standalone we always use 2 since it's the first * "mortal" PID. */ pid_t getpid(void) { return (2); } /* * Sleep for a given number of seconds */ unsigned int sleep(unsigned int secs) { uint_t end = (secs * 1000) + prom_gettime(); while (prom_gettime() < end) /* Null body */; return (0); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_UNISTD_H #define _SA_UNISTD_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of libc's . * All standalone code *must* use this header rather than libc's. */ #include #ifdef __cplusplus extern "C" { #endif /* * NOTE: Some of these are duplicated from ; we do this * rather than just #including it to avoid polluting the namespace. */ extern int open(const char *, int); extern int close(int); extern off_t lseek(int, off_t, int); extern ssize_t read(int, void *, size_t); extern pid_t getpid(void); extern int gethostname(char *, int); extern int sethostname(char *, int); extern unsigned int sleep(unsigned int); #ifdef __cplusplus } #endif #endif /* _SA_UNISTD_H */ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2004 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # LIBRARY = libsock.a OBJECTS = socket.o sock_test.o include ../Makefile.com LDLIBS += -linet -ltcp CPPFLAGS += -I../inet -I../tcp $(SOCKCPPFLAGS) CERRWARN += -Wno-type-limits include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2001-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * sock_test.c. Implementing a CLI for inetboot testing. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include "socket_impl.h" #include "socket_inet.h" #include #include #include #include #include #include #include #include #include "tcp_inet.h" #include "ipv4.h" #include static int atoi(const char *); static int st_accept(void); static int st_bind(void); static int st_connect(void); static int st_echo(void); static int st_getsockname(void); static int st_getsockopt(void); static int st_get_addr_and_port(in_addr_t *, unsigned short *); static int st_get_buf_and_cnt(char **, int *); static int st_listen(void); static int st_match_option(char *, int *, int *); static int st_send(void); static int st_sendto(void); static int st_recv(void); static int st_recvfrom(void); static int st_set_addr(void); static int st_set_netmask(void); static int st_set_router(void); static int st_setsockopt(void); static int st_socket(void); static int st_sock_close(void); static int st_tcp_tw_report(void); static int st_toggle_promiscuous(void); static int st_use_obp(void); /* Wrapper for socket calls. */ static int st_local_accept(int, struct sockaddr *, socklen_t *); static int st_local_bind(int, const struct sockaddr *, socklen_t); static int st_local_connect(int, const struct sockaddr *, socklen_t); static int st_local_getsockname(int, struct sockaddr *, socklen_t *); static int st_local_getsockopt(int, int, int, void *, socklen_t *); static int st_local_listen(int, int); static int st_local_recv(int, void *, size_t, int); static int st_local_recvfrom(int, void *, size_t, int, struct sockaddr *, socklen_t *); static int st_local_send(int, const void *, size_t, int); static int st_local_sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t); static int st_local_setsockopt(int, int, int, const void *, socklen_t); static int st_local_socket(int, int, int); static int st_local_socket_close(int); struct sock_test_cmd_s { char *st_cmd; int (*st_fn)(void); }; static struct sock_test_cmd_s st_cmds[] = { { "set_addr", st_set_addr}, { "set_netmask", st_set_netmask}, { "set_router", st_set_router}, { "socket", st_socket }, { "bind", st_bind }, { "accept", st_accept }, { "connect", st_connect }, { "listen", st_listen }, { "send", st_send }, { "sendto", st_sendto }, { "recv", st_recv }, { "recvfrom", st_recvfrom }, { "setsockopt", st_setsockopt }, { "getsockopt", st_getsockopt }, { "getsockname", st_getsockname }, { "close", st_sock_close }, { "echo", st_echo }, { "toggle_promiscous", st_toggle_promiscuous}, { "use_obp", st_use_obp}, { "tcp_tw_report", st_tcp_tw_report}, { NULL, NULL } }; struct so_option_string_s { char *so_name; int so_opt; int so_opt_level; } so_option_array[] = { { "rcvtimeo", SO_RCVTIMEO, SOL_SOCKET }, { "dontroute", SO_DONTROUTE, SOL_SOCKET }, { "reuseaddr", SO_REUSEADDR, SOL_SOCKET }, { "rcvbuf", SO_RCVBUF, SOL_SOCKET }, { "sndbuf", SO_SNDBUF, SOL_SOCKET }, { NULL, 0 } }; #define NO_OPENED_SOCKET -1 /* Right now, we only allow one socket at one time. */ static int g_sock_fd = NO_OPENED_SOCKET; static int save_g_sock_fd = NO_OPENED_SOCKET; /* Boolean to decide if OBP network routines should be used. */ static boolean_t use_obp = B_FALSE; /* * The following routines are wrappers for the real socket routines. The * boolean use_obp is used to decide whether the real socket routines is * called or the "equivalent" OBP provided routines should be called. */ static int st_local_socket(int domain, int type, int protocol) { if (!use_obp) { return (socket(domain, type, protocol)); } else { return (0); } } static int st_local_socket_close(int sd) { if (!use_obp) { return (socket_close(sd)); } else { return (0); } } static int st_local_accept(int sd, struct sockaddr *addr, socklen_t *addr_len) { if (!use_obp) { return (accept(sd, addr, addr_len)); } else { return (0); } } static int st_local_bind(int sd, const struct sockaddr *name, socklen_t namelen) { if (!use_obp) { return (bind(sd, name, namelen)); } else { return (0); } } static int st_local_connect(int sd, const struct sockaddr *addr, socklen_t addr_len) { if (!use_obp) { return (connect(sd, addr, addr_len)); } else { return (0); } } static int st_local_listen(int sd, int backlog) { if (!use_obp) { return (listen(sd, backlog)); } else { return (0); } } static int st_local_send(int sd, const void *msg, size_t len, int flags) { if (!use_obp) { return (send(sd, msg, len, flags)); } else { return (0); } } static int st_local_sendto(int sd, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) { if (!use_obp) { return (sendto(sd, msg, len, flags, to, tolen)); } else { return (0); } } static int st_local_recv(int sd, void *buf, size_t len, int flags) { if (!use_obp) { return (recv(sd, buf, len, flags)); } else { return (0); } } static int st_local_recvfrom(int sd, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) { if (!use_obp) { return (recvfrom(sd, buf, len, flags, from, fromlen)); } else { return (0); } } static int st_local_getsockname(int sd, struct sockaddr *name, socklen_t *namelen) { if (!use_obp) { return (getsockname(sd, name, namelen)); } else { return (0); } } static int st_local_getsockopt(int sd, int level, int option, void *optval, socklen_t *optlen) { if (!use_obp) { return (getsockopt(sd, level, option, optval, optlen)); } else { return (0); } } static int st_local_setsockopt(int sd, int level, int option, const void *optval, socklen_t optlen) { if (!use_obp) { return (setsockopt(sd, level, option, optval, optlen)); } else { return (0); } } static int atoi(const char *p) { int n; int c = *p++, neg = 0; while (isspace(c)) { c = *p++; } if (!isdigit(c)) { switch (c) { case '-': neg++; /* FALLTHROUGH */ case '+': c = *p++; } } for (n = 0; isdigit(c); c = *p++) { n *= 10; /* two steps to avoid unnecessary overflow */ n += '0' - c; /* accum neg to avoid surprises at MAX */ } return (neg ? n : -n); } int st_interpret(char *buf) { char *cmd; int i; if ((cmd = strtok(buf, " ")) == NULL) return (-1); for (i = 0; st_cmds[i].st_cmd != NULL; i++) { if (strcmp(cmd, st_cmds[i].st_cmd) == 0) { return (st_cmds[i].st_fn()); } } printf("! Unknown command: %s\n", cmd); return (-1); } static int st_socket(void) { char *type; if ((type = strtok(NULL, " ")) == NULL) { printf("! usage: socket type\n"); return (-1); } if (g_sock_fd != NO_OPENED_SOCKET) { printf("! Cannot open more than 1 socket\n"); return (-1); } if (strcmp(type, "stream") == 0) { if ((g_sock_fd = st_local_socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("! Error in opening TCP socket: %d\n", errno); return (-1); } else { printf("@ TCP socket opened\n"); } } else if (strcmp(type, "dgram") == 0) { if ((g_sock_fd = st_local_socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("! Error in opening UDP socket: %d\n", errno); return (-1); } else { printf("@ UDP socket opened\n"); } } else if (strcmp(type, "raw") == 0) { if ((g_sock_fd = st_local_socket(AF_INET, SOCK_RAW, 0)) < 0) { printf("! Error in opening RAW socket: %d\n", errno); return (-1); } else { printf("@ RAW socket opened\n"); } } else { printf("! Unknown socket type: %s\n", type); return (-1); } return (0); } static int st_set_addr(void) { char *tmp; struct in_addr addr; tmp = strtok(NULL, " "); if (tmp == NULL) { printf("! No address given\n"); return (-1); } if ((addr.s_addr = inet_addr(tmp)) == (uint32_t)-1) { printf("! Malformed address\n"); return (-1); } ipv4_setipaddr(&addr); printf("@ IP address %s set\n", inet_ntoa(addr)); return (0); } static int st_set_netmask(void) { char *tmp; struct in_addr addr; tmp = strtok(NULL, " "); if (tmp == NULL) { printf("! No netmask given\n"); return (-1); } if ((addr.s_addr = inet_addr(tmp)) == (uint32_t)-1) { printf("! Malformed netmask\n"); return (-1); } ipv4_setnetmask(&addr); printf("@ Netmask %s set\n", inet_ntoa(addr)); return (0); } static int st_set_router(void) { char *tmp; struct in_addr addr; tmp = strtok(NULL, " "); if (tmp == NULL) { printf("! No router address given\n"); return (-1); } if ((addr.s_addr = inet_addr(tmp)) == (uint32_t)-1) { printf("! Malformed router address\n"); return (-1); } ipv4_setdefaultrouter(&addr); if (ipv4_route(IPV4_ADD_ROUTE, RT_DEFAULT, NULL, &addr) < 0) { printf("! Cannot add default route\n"); } else { printf("@ Default router %s set\n", inet_ntoa(addr)); } return (0); } static int st_get_addr_and_port(in_addr_t *addr, unsigned short *port) { char *tmp; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } tmp = strtok(NULL, "/"); if (tmp == NULL) { printf("! No address given\n"); return (-1); } if ((*addr = inet_addr(tmp)) == (uint32_t)-1) { printf("! Malformed address\n"); return (-1); } tmp = strtok(NULL, " "); if (tmp == NULL) { printf("! No port given\n"); return (-1); } *port = htons(atoi(tmp)); return (0); } static int st_bind(void) { struct sockaddr_in local_addr; if (st_get_addr_and_port(&(local_addr.sin_addr.s_addr), &(local_addr.sin_port)) < 0) { return (-1); } local_addr.sin_family = AF_INET; if (st_local_bind(g_sock_fd, (struct sockaddr *)&local_addr, sizeof (local_addr)) < 0) { printf("! Bind failed: %d\n", errno); return (-1); } printf("@ Socket bound to %s/%d\n", inet_ntoa(local_addr.sin_addr), ntohs(local_addr.sin_port)); return (0); } static int st_listen(void) { char *tmp; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if ((tmp = strtok(NULL, " ")) == NULL) { printf("! No backlog given\n"); return (-1); } if (st_local_listen(g_sock_fd, atoi(tmp)) < 0) { printf("! Listen failed: %d\n", errno); return (-1); } printf("@ Listen succeeded\n"); return (0); } static int st_accept(void) { struct sockaddr_in addr; socklen_t addr_len; int sd; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } addr_len = sizeof (struct sockaddr_in); if ((sd = st_local_accept(g_sock_fd, (struct sockaddr *)&addr, &addr_len)) < 0) { printf("! Accept failed: %d\n", errno); return (-1); } printf("@ Accept succeeded from %s:%d. Socket descriptor saved\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); save_g_sock_fd = g_sock_fd; g_sock_fd = sd; return (0); } static int st_connect(void) { struct sockaddr_in peer_addr; if (st_get_addr_and_port(&(peer_addr.sin_addr.s_addr), &(peer_addr.sin_port)) < 0) { return (-1); } peer_addr.sin_family = AF_INET; if (st_local_connect(g_sock_fd, (struct sockaddr *)&peer_addr, sizeof (peer_addr)) < 0) { printf("! Connect failed: %d\n", errno); return (-1); } printf("@ Socket connected to %s/%d\n", inet_ntoa(peer_addr.sin_addr), ntohs(peer_addr.sin_port)); return (0); } static int st_get_buf_and_cnt(char **buf, int *send_cnt) { char *cnt; if ((*buf = strtok(NULL, " ")) == NULL) { printf("! No send buffer\n"); return (-1); } if ((cnt = strtok(NULL, " ")) == NULL) { printf("! Missing send length\n"); return (-1); } if ((*send_cnt = atoi(cnt)) < 0) { printf("! Invalid send count\n"); return (-1); } return (0); } static int st_send(void) { char *buf; int send_cnt; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if (st_get_buf_and_cnt(&buf, &send_cnt) < 0) return (-1); if ((send_cnt = st_local_send(g_sock_fd, buf, send_cnt, 0)) < 0) { printf("! Send failed: %d\n", errno); return (-1); } printf("@ Send %d bytes\n", send_cnt); return (0); } static int st_sendto(void) { struct sockaddr_in peer_addr; char *buf; int send_cnt; if (st_get_addr_and_port(&(peer_addr.sin_addr.s_addr), &(peer_addr.sin_port)) < 0) { return (-1); } peer_addr.sin_family = AF_INET; if (st_get_buf_and_cnt(&buf, &send_cnt) < 0) return (-1); if ((send_cnt = st_local_sendto(g_sock_fd, buf, send_cnt, 0, (struct sockaddr *)&peer_addr, sizeof (peer_addr))) < 0) { printf("! Sendto failed: %d\n", errno); return (-1); } printf("@ Send %d bytes\n", send_cnt); return (0); } static int st_recv(void) { char *tmp; char *buf; int buf_len, ret; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if ((tmp = strtok(NULL, " ")) == NULL) { printf("! No buffer len given\n"); return (-1); } buf_len = atoi(tmp); if ((buf = bkmem_zalloc(buf_len)) == NULL) { printf("! Cannot allocate buffer: %d\n", errno); return (-1); } if ((ret = st_local_recv(g_sock_fd, buf, buf_len, 0)) <= 0) { if (ret == 0) { printf("@ EOF received: %d\n", errno); return (0); } printf("! Cannot recv: %d\n", errno); return (-1); } printf("@ Bytes received: %d\n", ret); hexdump(buf, ret); bkmem_free(buf, buf_len); return (0); } static int st_recvfrom(void) { char *tmp; char *buf; int buf_len, ret; struct sockaddr_in from; socklen_t fromlen; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if ((tmp = strtok(NULL, " ")) == NULL) { printf("! No buffer len given\n"); return (-1); } buf_len = atoi(tmp); if ((buf = bkmem_zalloc(buf_len)) == NULL) { printf("! Cannot allocate buffer: %d\n", errno); return (-1); } fromlen = sizeof (from); if ((ret = st_local_recvfrom(g_sock_fd, buf, buf_len, 0, (struct sockaddr *)&from, &fromlen)) <= 0) { if (ret == 0) { printf("@ EOF received: %d\n", errno); return (0); } printf("! Cannot recv: %d\n", errno); return (-1); } printf("@ Bytes received from %s/%d: %d\n", inet_ntoa(from.sin_addr), ntohs(from.sin_port), ret); hexdump(buf, ret); bkmem_free(buf, buf_len); return (0); } /* * To act as an echo server. Note that it assumes the address and * netmask have been set. */ static int st_echo(void) { char *tmp; int listen_fd, newfd; int echo_port; struct sockaddr_in addr; socklen_t addr_size; int backlog = 20; char *buf; int buf_len, ret, snd_cnt; tmp = strtok(NULL, " "); if (tmp == NULL) { printf("! No echo port given\n"); return (-1); } echo_port = atoi(tmp); tmp = strtok(NULL, " "); if (tmp == NULL) { printf("! No buffer size given\n"); return (-1); } buf_len = atoi(tmp); /* Create local socket for echo server */ if ((listen_fd = st_local_socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("! Error in opening TCP socket: %d\n", errno); return (-1); } else { printf("@ Local TCP socket opened\n"); } /* Bind local socket */ addr.sin_family = AF_INET; addr.sin_port = htons(echo_port); addr.sin_addr.s_addr = INADDR_ANY; if (st_local_bind(listen_fd, (struct sockaddr *)&addr, sizeof (addr)) < 0) { printf("! Bind failed: %d\n", errno); return (-1); } if (st_local_listen(listen_fd, backlog) < 0) { printf("! Listen failed: %d\n", errno); return (-1); } addr_size = sizeof (addr); if ((newfd = st_local_accept(listen_fd, (struct sockaddr *)&addr, &addr_size)) < 0) { printf("! Accept failed: %d\n", errno); (void) st_local_socket_close(listen_fd); return (-1); } printf("@ Accepted connection: %s/%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); (void) st_local_socket_close(listen_fd); if ((buf = bkmem_zalloc(buf_len)) == NULL) { printf("! Cannot allocate buffer: %d\n", errno); (void) st_local_socket_close(newfd); return (-1); } while ((ret = st_local_recv(newfd, buf, buf_len, 0)) > 0) { printf("@ Bytes received: %d\n", ret); hexdump(buf, ret); if ((snd_cnt = st_local_send(newfd, buf, ret, 0)) < ret) { printf("! Send failed: %d\n", errno); bkmem_free(buf, buf_len); return (-1); } printf("@ Sent %d bytes\n", snd_cnt); } (void) st_local_socket_close(newfd); if (ret < 0) { printf("! Cannot recv: %d\n", errno); bkmem_free(buf, buf_len); return (-1); } else { return (0); } } static int st_match_option(char *opt_s, int *opt, int *opt_level) { int i; for (i = 0; so_option_array[i].so_name != NULL; i++) { if (strcmp(so_option_array[i].so_name, opt_s) == 0) { *opt = so_option_array[i].so_opt; *opt_level = so_option_array[i].so_opt_level; return (0); } } printf("! Unknown option\n"); return (-1); } static int st_setsockopt(void) { char *tmp; int opt, opt_level, opt_val; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if ((tmp = strtok(NULL, " ")) == NULL) { printf("! No option given\n"); return (-1); } if (st_match_option(tmp, &opt, &opt_level) < 0) { return (-1); } /* We only support integer option for the moment. */ if ((tmp = strtok(NULL, " ")) == NULL) { printf("! No option value given\n"); return (-1); } opt_val = atoi(tmp); if (st_local_setsockopt(g_sock_fd, opt_level, opt, &opt_val, sizeof (int)) < 0) { printf("! Cannot set option: %d\n", errno); return (-1); } printf("@ Option set successfully\n"); return (0); } static int st_getsockname(void) { struct sockaddr_in addr; socklen_t len; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } len = sizeof (addr); if (st_local_getsockname(g_sock_fd, (struct sockaddr *)&addr, &len) < 0) { printf("! getsockname failed: %d\n", errno); return (-1); } printf("@ Local socket name: %s/%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); return (0); } static int st_getsockopt(void) { char *tmp; int opt, opt_level, opt_val; socklen_t opt_len; if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if ((tmp = strtok(NULL, " ")) == NULL) { printf("! No option given\n"); return (-1); } if (st_match_option(tmp, &opt, &opt_level) < 0) { return (-1); } opt_len = sizeof (opt_val); if (st_local_getsockopt(g_sock_fd, opt_level, opt, &opt_val, &opt_len) < 0) { printf("! Cannot get option: %d\n", errno); return (-1); } printf("@ Option value is %d\n", opt_val); return (-1); } static int st_sock_close(void) { if (g_sock_fd == NO_OPENED_SOCKET) { printf("! No socket opened\n"); return (-1); } if (st_local_socket_close(g_sock_fd) < 0) { printf("! Error in closing socket: %d\n", errno); return (-1); } printf("@ Socket closed"); if (save_g_sock_fd != NO_OPENED_SOCKET) { g_sock_fd = save_g_sock_fd; save_g_sock_fd = NO_OPENED_SOCKET; printf(", switching to saved socket descriptor\n"); } else { g_sock_fd = NO_OPENED_SOCKET; printf("\n"); } return (0); } static int st_toggle_promiscuous(void) { /* We always start with non-promiscuous mode. */ static boolean_t promiscuous = B_FALSE; promiscuous = !promiscuous; (void) ipv4_setpromiscuous(promiscuous); printf("@ Setting promiscuous to %d\n", promiscuous); return (0); } static int st_use_obp(void) { if ((use_obp = !use_obp) == B_TRUE) { printf("@ Now using OBP routines\n"); } else { printf("@ Now using socket routines\n"); } return (0); } static int st_tcp_tw_report(void) { printf("@ TCP Time Wait report\n"); tcp_time_wait_report(); return (0); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2001-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Socket CLI testing header file. */ #ifndef _SOCK_TEST_H #define _SOCK_TEST_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif extern int st_interpret(char *); #ifdef __cplusplus } #endif #endif /* _SOCK_TEST_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * socket.c, Code implementing a simple socket interface. */ #include #include "socket_impl.h" #include #include #include #include #include #include #include #include #include #include "socket_inet.h" #include "ipv4.h" #include "ipv4_impl.h" #include "udp_inet.h" #include "tcp_inet.h" #include "mac.h" #include "mac_impl.h" #include struct inetboot_socket sockets[MAXSOCKET] = { 0 }; /* Default send and receive socket buffer size */ #define SO_DEF_SNDBUF 48*1024 #define SO_DEF_RCVBUF 48*1024 /* Default max socket buffer size */ #define SO_MAX_BUF 4*1024*1024 static ssize_t dgram_sendto(int, const void *, size_t, int, const struct sockaddr *, int); static ssize_t stream_sendto(int, const void *, size_t, int); static int bind_check(int, const struct sockaddr *); static int quickbind(int); /* Check the validity of a fd and return the socket index of that fd. */ int so_check_fd(int fd, int *errno) { int i; i = FD_TO_SOCKET(fd); if (i < 0 || i >= MAXSOCKET) { *errno = ENOTSOCK; return (-1); } if (sockets[i].type == INETBOOT_UNUSED) { *errno = ENOTSOCK; return (-1); } return (i); } /* * Create an endpoint for network communication. Returns a descriptor. * * Notes: * Only PF_INET communication domains are supported. Within * this domain, only SOCK_RAW, SOCK_DGRAM and SOCK_STREAM types are * supported. */ int socket(int domain, int type, int protocol) { static int sock_initialized; int i; errno = 0; if (!sock_initialized) { for (i = 0; i < MAXSOCKET; i++) sockets[i].type = INETBOOT_UNUSED; sock_initialized = B_TRUE; } if (domain != AF_INET) { errno = EPROTONOSUPPORT; return (-1); } /* Find available socket */ for (i = 0; i < MAXSOCKET; i++) { if (sockets[i].type == INETBOOT_UNUSED) break; } if (i >= MAXSOCKET) { errno = EMFILE; /* No slots left. */ return (-1); } /* Some socket initialization... */ sockets[i].so_rcvbuf = SO_DEF_RCVBUF; sockets[i].so_sndbuf = SO_DEF_SNDBUF; /* * Note that we ignore the protocol field for SOCK_DGRAM and * SOCK_STREAM. When we support different protocols in future, * this needs to be changed. */ switch (type) { case SOCK_RAW: ipv4_raw_socket(&sockets[i], (uint8_t)protocol); break; case SOCK_DGRAM: udp_socket_init(&sockets[i]); break; case SOCK_STREAM: tcp_socket_init(&sockets[i]); break; default: errno = EPROTOTYPE; break; } if (errno != 0) return (-1); /* IPv4 generic initialization. */ ipv4_socket_init(&sockets[i]); /* MAC generic initialization. */ mac_socket_init(&sockets[i]); return (i + SOCKETTYPE); } int getsockname(int s, struct sockaddr *name, socklen_t *namelen) { int i; errno = 0; if ((i = so_check_fd(s, &errno)) == -1) return (-1); if (*namelen < sizeof (struct sockaddr_in)) { errno = ENOMEM; return (-1); } /* Structure assignment... */ *((struct sockaddr_in *)name) = sockets[i].bind; *namelen = sizeof (struct sockaddr_in); return (0); } /* * The socket options we support are: * SO_RCVTIMEO - Value is in msecs, and is of uint32_t. * SO_DONTROUTE - Value is an int, and is a boolean (nonzero if set). * SO_REUSEADDR - Value is an int boolean. * SO_RCVBUF - Value is an int. * SO_SNDBUF - Value is an int. */ int getsockopt(int s, int level, int option, void *optval, socklen_t *optlen) { int i; errno = 0; if ((i = so_check_fd(s, &errno)) == -1) return (-1); switch (level) { case SOL_SOCKET: { switch (option) { case SO_RCVTIMEO: if (*optlen == sizeof (uint32_t)) { *(uint32_t *)optval = sockets[i].in_timeout; } else { *optlen = 0; errno = EINVAL; } break; case SO_DONTROUTE: if (*optlen == sizeof (int)) { *(int *)optval = (sockets[i].out_flags & SO_DONTROUTE); } else { *optlen = 0; errno = EINVAL; } break; case SO_REUSEADDR: if (*optlen == sizeof (int)) { *(int *)optval = (sockets[i].so_opt & SO_REUSEADDR); } else { *optlen = 0; errno = EINVAL; } break; case SO_RCVBUF: if (*optlen == sizeof (int)) { *(int *)optval = sockets[i].so_rcvbuf; } else { *optlen = 0; errno = EINVAL; } break; case SO_SNDBUF: if (*optlen == sizeof (int)) { *(int *)optval = sockets[i].so_sndbuf; } else { *optlen = 0; errno = EINVAL; } break; case SO_LINGER: if (*optlen == sizeof (struct linger)) { /* struct copy */ *(struct linger *)optval = sockets[i].so_linger; } else { *optlen = 0; errno = EINVAL; } break; default: errno = ENOPROTOOPT; break; } break; } /* case SOL_SOCKET */ case IPPROTO_TCP: case IPPROTO_IP: { switch (option) { default: *optlen = 0; errno = ENOPROTOOPT; break; } break; } /* case IPPROTO_IP or IPPROTO_TCP */ default: errno = ENOPROTOOPT; break; } /* switch (level) */ if (errno != 0) return (-1); else return (0); } /* * Generate a network-order source port from the privileged range if * "reserved" is true, dynamic/private range otherwise. We consider the * range of 512-1023 privileged ports as ports we can use. This mirrors * historical rpc client practice for privileged port selection. */ in_port_t get_source_port(boolean_t reserved) { static in_port_t dynamic = IPPORT_DYNAMIC_START - 1, rsvdport = (IPPORT_RESERVED / 2) - 1; in_port_t p; if (reserved) { if (++rsvdport >= IPPORT_RESERVED) p = rsvdport = IPPORT_RESERVED / 2; else p = rsvdport; } else p = ++dynamic; return (htons(p)); } /* * The socket options we support are: * SO_RECVTIMEO - Value is uint32_t msecs. * SO_DONTROUTE - Value is int boolean (nonzero == TRUE, zero == FALSE). * SO_REUSEADDR - value is int boolean. * SO_RCVBUF - Value is int. * SO_SNDBUF - Value is int. */ int setsockopt(int s, int level, int option, const void *optval, socklen_t optlen) { int i; errno = 0; if ((i = so_check_fd(s, &errno)) == -1) return (-1); switch (level) { case SOL_SOCKET: { switch (option) { case SO_RCVTIMEO: if (optlen == sizeof (uint32_t)) sockets[i].in_timeout = *(uint32_t *)optval; else { errno = EINVAL; } break; case SO_DONTROUTE: if (optlen == sizeof (int)) { if (*(int *)optval) sockets[i].out_flags |= SO_DONTROUTE; else sockets[i].out_flags &= ~SO_DONTROUTE; } else { errno = EINVAL; } break; case SO_REUSEADDR: if (optlen == sizeof (int)) { if (*(int *)optval) sockets[i].so_opt |= SO_REUSEADDR; else sockets[i].so_opt &= ~SO_REUSEADDR; } else { errno = EINVAL; } break; case SO_RCVBUF: if (optlen == sizeof (int)) { sockets[i].so_rcvbuf = *(int *)optval; if (sockets[i].so_rcvbuf > SO_MAX_BUF) sockets[i].so_rcvbuf = SO_MAX_BUF; (void) tcp_opt_set(sockets[i].pcb, level, option, optval, optlen); } else { errno = EINVAL; } break; case SO_SNDBUF: if (optlen == sizeof (int)) { sockets[i].so_sndbuf = *(int *)optval; if (sockets[i].so_sndbuf > SO_MAX_BUF) sockets[i].so_sndbuf = SO_MAX_BUF; (void) tcp_opt_set(sockets[i].pcb, level, option, optval, optlen); } else { errno = EINVAL; } break; case SO_LINGER: if (optlen == sizeof (struct linger)) { /* struct copy */ sockets[i].so_linger = *(struct linger *)optval; (void) tcp_opt_set(sockets[i].pcb, level, option, optval, optlen); } else { errno = EINVAL; } break; default: errno = ENOPROTOOPT; break; } break; } /* case SOL_SOCKET */ case IPPROTO_TCP: case IPPROTO_IP: { switch (option) { default: errno = ENOPROTOOPT; break; } break; } /* case IPPROTO_IP or IPPROTO_TCP */ default: errno = ENOPROTOOPT; break; } /* switch (level) */ if (errno != 0) return (-1); else return (0); } /* * Shut down part of a full-duplex connection. * * Only supported for TCP sockets */ int shutdown(int s, int how) { int sock_id; int i; errno = 0; if ((sock_id = so_check_fd(s, &errno)) == -1) return (-1); /* shutdown only supported for TCP sockets */ if (sockets[sock_id].type != INETBOOT_STREAM) { errno = EOPNOTSUPP; return (-1); } if (!(sockets[sock_id].so_state & SS_ISCONNECTED)) { errno = ENOTCONN; return (-1); } switch (how) { case 0: sockets[sock_id].so_state |= SS_CANTRCVMORE; break; case 1: sockets[sock_id].so_state |= SS_CANTSENDMORE; break; case 2: sockets[sock_id].so_state |= (SS_CANTRCVMORE | SS_CANTSENDMORE); break; default: errno = EINVAL; return (-1); } switch (sockets[sock_id].so_state & (SS_CANTRCVMORE | SS_CANTSENDMORE)) { case (SS_CANTRCVMORE | SS_CANTSENDMORE): /* Call lower level protocol close routine. */ for (i = TRANSPORT_LVL; i >= MEDIA_LVL; i--) { if (sockets[sock_id].close[i] != NULL) { (void) sockets[sock_id].close[i](sock_id); } } nuke_grams(&sockets[sock_id].inq); break; case SS_CANTRCVMORE: nuke_grams(&sockets[sock_id].inq); break; case SS_CANTSENDMORE: /* Call lower level protocol close routine. */ if (tcp_shutdown(sock_id) < 0) return (-1); break; default: errno = EINVAL; return (-1); } return (0); } /* * "close" a socket. */ int socket_close(int s) { int sock_id, i; errno = 0; if ((sock_id = so_check_fd(s, &errno)) == -1) return (-1); /* Call lower level protocol close routine. */ for (i = TRANSPORT_LVL; i >= MEDIA_LVL; i--) { if (sockets[sock_id].close[i] != NULL) { /* * Note that the close() routine of other * layers can return an error. But right * now, the only mechanism to report that * back is for the close() routine to set * the errno and socket_close() will return * an error. But the close operation will * not be stopped. */ (void) sockets[sock_id].close[i](sock_id); } } /* * Clear the input queue. This has to be done * after the lower level protocol close routines have been * called as they may want to do something about the queue. */ nuke_grams(&sockets[sock_id].inq); bzero((caddr_t)&sockets[sock_id], sizeof (struct inetboot_socket)); sockets[sock_id].type = INETBOOT_UNUSED; return (0); } /* * Read up to `nbyte' of data from socket `s' into `buf'; if non-zero, * then give up after `read_timeout' seconds. Returns the number of * bytes read, or -1 on failure. */ int socket_read(int s, void *buf, size_t nbyte, int read_timeout) { ssize_t n; uint_t start, diff; /* * keep calling non-blocking recvfrom until something received * or an error occurs */ start = prom_gettime(); for (;;) { n = recvfrom(s, buf, nbyte, MSG_DONTWAIT, NULL, NULL); if (n == -1 && errno == EWOULDBLOCK) { diff = (uint_t)((prom_gettime() - start) + 500) / 1000; if (read_timeout != 0 && diff > read_timeout) { errno = EINTR; return (-1); } } else { return (n); } } } /* * Write up to `nbyte' bytes of data from `buf' to the address pointed to * `addr' using socket `s'. Returns the number of bytes writte on success, * or -1 on failure. */ int socket_write(int s, const void *buf, size_t nbyte, struct sockaddr_in *addr) { return (sendto(s, buf, nbyte, 0, (struct sockaddr *)addr, sizeof (*addr))); } static int bind_check(int sock_id, const struct sockaddr *addr) { int k; struct sockaddr_in *in_addr = (struct sockaddr_in *)addr; /* Do not check for duplicate bind() if SO_REUSEADDR option is set. */ if (! (sockets[sock_id].so_opt & SO_REUSEADDR)) { for (k = 0; k < MAXSOCKET; k++) { if (sockets[k].type != INETBOOT_UNUSED && sockets[k].proto == sockets[sock_id].proto && sockets[k].bound) { if ((sockets[k].bind.sin_addr.s_addr == in_addr->sin_addr.s_addr) && (sockets[k].bind.sin_port == in_addr->sin_port)) { errno = EADDRINUSE; return (-1); } } } } return (0); } /* Assign a name to an unnamed socket. */ int bind(int s, const struct sockaddr *name, socklen_t namelen) { int i; errno = 0; if ((i = so_check_fd(s, &errno)) == -1) return (-1); if (name == NULL) { /* unbind */ if (sockets[i].bound) { bzero((caddr_t)&sockets[i].bind, sizeof (struct sockaddr_in)); sockets[i].bound = B_FALSE; } return (0); } if (namelen != sizeof (struct sockaddr_in) || name == NULL) { errno = EINVAL; return (-1); } if (name->sa_family != AF_INET) { errno = EAFNOSUPPORT; return (-1); } if (sockets[i].bound) { if (bcmp((caddr_t)&sockets[i].bind, (caddr_t)name, namelen) == 0) { /* attempt to bind to same address ok... */ return (0); } errno = EINVAL; /* already bound */ return (-1); } if (errno != 0) { return (-1); } /* Check for duplicate bind(). */ if (bind_check(i, name) < 0) return (-1); bcopy((caddr_t)name, (caddr_t)&sockets[i].bind, namelen); if (sockets[i].type == INETBOOT_STREAM) { if (tcp_bind(i) < 0) { return (-1); } } sockets[i].bound = B_TRUE; return (0); } static int quickbind(int sock_id) { int i; struct sockaddr_in addr; /* * XXX This needs more work. Right now, if ipv4_setipaddr() * have not been called, this will be wrong. But we need * something better. Need to be revisited. */ ipv4_getipaddr(&addr.sin_addr); addr.sin_family = AF_INET; for (i = SMALLEST_ANON_PORT; i <= LARGEST_ANON_PORT; i++) { addr.sin_port = htons(i); if (bind_check(sock_id, (struct sockaddr *)&addr) == 0) break; } /* Need to clear errno as it is probably set by bind_check(). */ errno = 0; if (i <= LARGEST_ANON_PORT) { bcopy((caddr_t)&addr, (caddr_t)&sockets[sock_id].bind, sizeof (struct sockaddr_in)); sockets[sock_id].bound = B_TRUE; #ifdef DEBUG printf("quick bind done addr %s port %d\n", inet_ntoa(sockets[sock_id].bind.sin_addr), ntohs(sockets[sock_id].bind.sin_port)); #endif return (0); } else { return (-1); } } int listen(int fd, int backlog) { int sock_id; errno = 0; if ((sock_id = so_check_fd(fd, &errno)) == -1) return (-1); if (sockets[sock_id].type != INETBOOT_STREAM) { errno = EOPNOTSUPP; return (-1); } if (sockets[sock_id].so_error != 0) { errno = sockets[sock_id].so_error; return (-1); } return (tcp_listen(sock_id, backlog)); } int accept(int fd, struct sockaddr *addr, socklen_t *addr_len) { int sock_id; int new_sd; errno = 0; if ((sock_id = so_check_fd(fd, &errno)) == -1) return (-1); if (sockets[sock_id].type != INETBOOT_STREAM) { errno = EOPNOTSUPP; return (-1); } if (sockets[sock_id].so_error != 0) { errno = sockets[sock_id].so_error; return (-1); } if ((new_sd = tcp_accept(sock_id, addr, addr_len)) == -1) return (-1); sock_id = so_check_fd(new_sd, &errno); sockets[sock_id].so_state |= SS_ISCONNECTED; return (new_sd); } int connect(int fd, const struct sockaddr *addr, socklen_t addr_len) { int sock_id; int so_type; errno = 0; if ((sock_id = so_check_fd(fd, &errno)) == -1) return (-1); so_type = sockets[sock_id].type; if (addr == NULL || addr_len == 0) { errno = EINVAL; return (-1); } /* Don't allow connect for raw socket. */ if (so_type == INETBOOT_RAW) { errno = EPROTONOSUPPORT; return (-1); } if (sockets[sock_id].so_state & SS_ISCONNECTED) { errno = EINVAL; return (-1); } if (sockets[sock_id].so_error != 0) { errno = sockets[sock_id].so_error; return (-1); } /* If the socket is not bound, we need to do a quick bind. */ if (!sockets[sock_id].bound) { /* For TCP socket, just call tcp_bind(). */ if (so_type == INETBOOT_STREAM) { if (tcp_bind(sock_id) < 0) return (-1); } else { if (quickbind(sock_id) < 0) { errno = EADDRNOTAVAIL; return (-1); } } } /* Should do some sanity check for addr .... */ bcopy((caddr_t)addr, &sockets[sock_id].remote, sizeof (struct sockaddr_in)); if (sockets[sock_id].type == INETBOOT_STREAM) { /* Call TCP connect routine. */ if (tcp_connect(sock_id) == 0) sockets[sock_id].so_state |= SS_ISCONNECTED; else { if (sockets[sock_id].so_error != 0) errno = sockets[sock_id].so_error; return (-1); } } else { sockets[sock_id].so_state |= SS_ISCONNECTED; } return (0); } /* Just a wrapper around recvfrom(). */ ssize_t recv(int s, void *buf, size_t len, int flags) { return (recvfrom(s, buf, len, flags, NULL, NULL)); } /* * Receive messages from a connectionless socket. Legal flags are 0 and * MSG_DONTWAIT. MSG_WAITALL is not currently supported. * * Returns length of message for success, -1 if error occurred. */ ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) { int sock_id, i; ssize_t datalen, bytes = 0; struct inetgram *icp; enum SockType so_type; char *tmp_buf; mblk_t *mp; errno = 0; if ((sock_id = so_check_fd(s, &errno)) == -1) { errno = EINVAL; return (-1); } if (sockets[sock_id].type == INETBOOT_STREAM && !(sockets[sock_id].so_state & SS_ISCONNECTED)) { errno = ENOTCONN; return (-1); } if (buf == NULL || len == 0) { errno = EINVAL; return (-1); } /* Yup - MSG_WAITALL not implemented */ if ((flags & ~MSG_DONTWAIT) != 0) { errno = EINVAL; return (-1); } retry: if (sockets[sock_id].inq == NULL) { /* Go out and check the wire */ for (i = MEDIA_LVL; i < APP_LVL; i++) { if (sockets[sock_id].input[i] != NULL) { if (sockets[sock_id].input[i](sock_id) < 0) { if (sockets[sock_id].so_error != 0) { errno = sockets[sock_id].so_error; } return (-1); } } } } so_type = sockets[sock_id].type; /* Remove unknown inetgrams from the head of inq. Can this happen? */ while ((icp = sockets[sock_id].inq) != NULL) { if ((so_type == INETBOOT_DGRAM || so_type == INETBOOT_STREAM) && icp->igm_level != APP_LVL) { #ifdef DEBUG printf("recvfrom: unexpected level %d frame found\n", icp->igm_level); #endif /* DEBUG */ del_gram(&sockets[sock_id].inq, icp, B_TRUE); continue; } else { break; } } if (icp == NULL) { /* * Checking for error should be done everytime a lower layer * input routing is called. For example, if TCP gets a RST, * this should be reported asap. */ if (sockets[sock_id].so_state & SS_CANTRCVMORE) { if (sockets[sock_id].so_error != 0) { errno = sockets[sock_id].so_error; return (-1); } else { return (0); } } if ((flags & MSG_DONTWAIT) == 0) goto retry; /* wait forever */ /* no data */ errno = EWOULDBLOCK; return (-1); } if (from != NULL && fromlen != NULL) { switch (so_type) { case INETBOOT_STREAM: /* Need to copy from the socket's remote address. */ bcopy(&(sockets[sock_id].remote), from, MIN(*fromlen, sizeof (struct sockaddr_in))); break; case INETBOOT_RAW: case INETBOOT_DGRAM: default: if (*fromlen > sizeof (icp->igm_saddr)) *fromlen = sizeof (icp->igm_saddr); bcopy((caddr_t)&(icp->igm_saddr), (caddr_t)from, MIN(*fromlen, sizeof (struct sockaddr_in))); break; } } mp = icp->igm_mp; switch (so_type) { case INETBOOT_STREAM: /* * If the message has igm_id == TCP_CALLB_MAGIC_ID, we need * to drain the data held by tcp and try again. */ if (icp->igm_id == TCP_CALLB_MAGIC_ID) { del_gram(&sockets[sock_id].inq, icp, B_TRUE); tcp_rcv_drain_sock(sock_id); goto retry; } /* TCP should put only user data in the inetgram. */ tmp_buf = (char *)buf; while (len > 0 && icp != NULL) { datalen = mp->b_wptr - mp->b_rptr; if (len < datalen) { bcopy(mp->b_rptr, tmp_buf, len); bytes += len; mp->b_rptr += len; break; } else { bcopy(mp->b_rptr, tmp_buf, datalen); len -= datalen; bytes += datalen; tmp_buf += datalen; del_gram(&sockets[sock_id].inq, icp, B_TRUE); /* * If we have any embedded magic messages just * drop them. */ while ((icp = sockets[sock_id].inq) != NULL) { if (icp->igm_id != TCP_CALLB_MAGIC_ID) break; del_gram(&sockets[sock_id].inq, icp, B_TRUE); } if (icp == NULL) break; mp = icp->igm_mp; } } sockets[sock_id].so_rcvbuf += (int32_t)bytes; break; case INETBOOT_DGRAM: datalen = mp->b_wptr - mp->b_rptr; if (len < datalen) bytes = len; else bytes = datalen; bcopy(mp->b_rptr, buf, bytes); del_gram(&sockets[sock_id].inq, icp, B_TRUE); break; case INETBOOT_RAW: default: datalen = mp->b_wptr - mp->b_rptr; if (len < datalen) bytes = len; else bytes = datalen; bcopy(mp->b_rptr, buf, bytes); del_gram(&sockets[sock_id].inq, icp, B_TRUE); break; } #ifdef DEBUG printf("recvfrom(%d): data: (0x%x,%d)\n", sock_id, (icp != NULL) ? icp->igm_mp : 0, bytes); #endif /* DEBUG */ return (bytes); } /* Just a wrapper around sendto(). */ ssize_t send(int s, const void *msg, size_t len, int flags) { return (sendto(s, msg, len, flags, NULL, 0)); } /* * Transmit a message through a socket. * * Supported flags: MSG_DONTROUTE or 0. */ ssize_t sendto(int s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) { enum SockType so_type; int sock_id; ssize_t bytes; errno = 0; if ((sock_id = so_check_fd(s, &errno)) == -1) { return (-1); } if (msg == NULL) { errno = EINVAL; return (-1); } so_type = sockets[sock_id].type; if ((flags & ~MSG_DONTROUTE) != 0) { errno = EINVAL; return (-1); } if (sockets[sock_id].so_error != 0) { errno = sockets[sock_id].so_error; return (-1); } if (to != NULL && to->sa_family != AF_INET) { errno = EAFNOSUPPORT; return (-1); } switch (so_type) { case INETBOOT_RAW: case INETBOOT_DGRAM: if (!(sockets[sock_id].so_state & SS_ISCONNECTED) && (to == NULL || tolen != sizeof (struct sockaddr_in))) { errno = EINVAL; return (-1); } bytes = dgram_sendto(sock_id, msg, len, flags, to, tolen); break; case INETBOOT_STREAM: if (!((sockets[sock_id].so_state & SS_ISCONNECTED) || (sockets[sock_id].so_state & SS_ISCONNECTING))) { errno = EINVAL; return (-1); } if (sockets[sock_id].so_state & SS_CANTSENDMORE) { errno = EPIPE; return (-1); } bytes = stream_sendto(sock_id, msg, len, flags); break; default: /* Should not happen... */ errno = EPROTOTYPE; return (-1); } return (bytes); } static ssize_t dgram_sendto(int i, const void *msg, size_t len, int flags, const struct sockaddr *to, int tolen) { struct inetgram oc; int l, offset; size_t tlen; mblk_t *mp; #ifdef DEBUG { struct sockaddr_in *sin = (struct sockaddr_in *)to; printf("sendto(%d): msg of length: %d sent to port %d and host: %s\n", i, len, ntohs(sin->sin_port), inet_ntoa(sin->sin_addr)); } #endif /* DEBUG */ nuke_grams(&sockets[i].inq); /* flush the input queue */ /* calculate offset for data */ offset = sockets[i].headerlen[MEDIA_LVL](NULL) + (sockets[i].headerlen[NETWORK_LVL])(NULL); bzero((caddr_t)&oc, sizeof (oc)); if (sockets[i].type != INETBOOT_RAW) { offset += (sockets[i].headerlen[TRANSPORT_LVL])(NULL); oc.igm_level = TRANSPORT_LVL; } else oc.igm_level = NETWORK_LVL; oc.igm_oflags = flags; if (to != NULL) { bcopy((caddr_t)to, (caddr_t)&oc.igm_saddr, tolen); } else { bcopy((caddr_t)&sockets[i].remote, (caddr_t)&oc.igm_saddr, sizeof (struct sockaddr_in)); } /* Get a legal source port if the socket isn't bound. */ if (sockets[i].bound == B_FALSE && ntohs(oc.igm_saddr.sin_port == 0)) { ((struct sockaddr_in *)&oc.igm_saddr)->sin_port = get_source_port(B_FALSE); } /* Round up to 16bit value for checksum purposes */ if (sockets[i].type == INETBOOT_DGRAM) { tlen = ((len + sizeof (uint16_t) - 1) & ~(sizeof (uint16_t) - 1)); } else tlen = len; if ((oc.igm_mp = allocb(tlen + offset, 0)) == NULL) { errno = ENOMEM; return (-1); } mp = oc.igm_mp; mp->b_rptr = mp->b_wptr += offset; bcopy((caddr_t)msg, mp->b_wptr, len); mp->b_wptr += len; for (l = TRANSPORT_LVL; l >= MEDIA_LVL; l--) { if (sockets[i].output[l] != NULL) { if (sockets[i].output[l](i, &oc) < 0) { freeb(mp); if (errno == 0) errno = EIO; return (-1); } } } freeb(mp); return (len); } /* ARGSUSED */ static ssize_t stream_sendto(int i, const void *msg, size_t len, int flags) { int cnt; assert(sockets[i].pcb != NULL); /* * Call directly TCP's send routine. We do this because TCP * needs to decide whether to send out the data. * * Note also that currently, TCP ignores all flags passed in for * TCP socket. */ if ((cnt = tcp_send(i, sockets[i].pcb, msg, len)) < 0) { if (sockets[i].so_error != 0) errno = sockets[i].so_error; return (-1); } else { return (cnt); } } /* * Returns ptr to the last inetgram in the list, or null if list is null */ struct inetgram * last_gram(struct inetgram *igp) { struct inetgram *wp; for (wp = igp; wp != NULL; wp = wp->igm_next) { if (wp->igm_next == NULL) return (wp); } return (NULL); } /* * Adds an inetgram or list of inetgrams to the end of the list. */ void add_grams(struct inetgram **igpp, struct inetgram *newgp) { struct inetgram *wp; if (newgp == NULL) return; if (*igpp == NULL) *igpp = newgp; else { wp = last_gram(*igpp); wp->igm_next = newgp; } } /* * Nuke a whole list of grams. */ void nuke_grams(struct inetgram **lgpp) { while (*lgpp != NULL) del_gram(lgpp, *lgpp, B_TRUE); } /* * Remove the referenced inetgram. List is altered accordingly. Destroy the * referenced inetgram if freeit is B_TRUE. */ void del_gram(struct inetgram **lgpp, struct inetgram *igp, int freeit) { struct inetgram *wp, *pp = NULL; if (lgpp == NULL || igp == NULL) return; wp = *lgpp; while (wp != NULL) { if (wp == igp) { /* detach wp from the list */ if (*lgpp == wp) *lgpp = (*lgpp)->igm_next; else pp->igm_next = wp->igm_next; igp->igm_next = NULL; if (freeit) { if (igp->igm_mp != NULL) freeb(igp->igm_mp); bkmem_free((caddr_t)igp, sizeof (struct inetgram)); } break; } pp = wp; wp = wp->igm_next; } } struct nct_t nct[] = { "bootp", NCT_BOOTP_DHCP, "dhcp", NCT_BOOTP_DHCP, "rarp", NCT_RARP_BOOTPARAMS, "manual", NCT_MANUAL }; int nct_entries = sizeof (nct) / sizeof (nct[0]); /* * Figure out from the bootpath what kind of network configuration strategy * we should use. Returns the network config strategy. */ int get_netconfig_strategy(void) { int i; #define ISSPACE(c) (c == ' ' || c == '\t' || c == '\n' || c == '\0') char lbootpath[OBP_MAXPATHLEN]; char net_options[NCT_BUFSIZE]; char *op, *nop, *sp; pnode_t cn; int proplen; /* If the PROM DHCP cache exists, we're done */ if (prom_cached_reply(B_TRUE)) return (NCT_BOOTP_DHCP); /* * Newer (version 4) PROMs will put the name in the * "net-config-strategy" property. */ cn = prom_finddevice("/chosen"); if ((proplen = prom_getproplen(cn, "net-config-strategy")) < sizeof (net_options)) { (void) prom_getprop(cn, "net-config-strategy", net_options); net_options[proplen] = '\0'; } else { /* * We're reduced to sacanning bootpath for the prototol to use. * Since there was no "net-config-strategy" property, this is * an old PROM, so we need to excise any extraneous key/value * initializations from bootpath[]. */ for (op = prom_bootpath(), sp = lbootpath; op != NULL && !ISSPACE(*op); sp++, op++) *sp = *op; *sp = '\0'; /* find the last '/' (in the device path) */ if ((op = strrchr(lbootpath, '/')) == NULL) /* last '/' */ op = lbootpath; else op++; /* then look for the ':' separating it from the protocol */ while (*op != ':' && *op != '\0') op++; if (*op == ':') { for (nop = net_options, op++; *op != '\0' && *op != '/' && !ISSPACE(*op) && nop < &net_options[NCT_BUFSIZE]; nop++, op++) *nop = *op; *nop = '\0'; } else net_options[0] = '\0'; } #undef ISSPACE for (i = 0; i < nct_entries; i++) if (strcmp(net_options, nct[i].p_name) == 0) return (nct[i].p_id); return (NCT_DEFAULT); } /* Modified STREAM routines for ease of porting core TCP code. */ /*ARGSUSED*/ mblk_t * allocb(size_t size, uint_t pri) { unsigned char *base; mblk_t *mp; if ((mp = (mblk_t *)bkmem_zalloc(sizeof (mblk_t))) == NULL) return (NULL); if ((base = (unsigned char *)bkmem_zalloc(size)) == NULL) return (NULL); mp->b_next = mp->b_prev = mp->b_cont = NULL; mp->b_rptr = mp->b_wptr = mp->b_datap = (unsigned char *)base; mp->b_size = size; return (mp); } void freeb(mblk_t *mp) { #ifdef DEBUG printf("freeb datap %x\n", mp->b_datap); #endif bkmem_free((caddr_t)(mp->b_datap), mp->b_size); #ifdef DEBUG printf("freeb mp %x\n", mp); #endif bkmem_free((caddr_t)mp, sizeof (mblk_t)); } void freemsg(mblk_t *mp) { while (mp) { mblk_t *mp_cont = mp->b_cont; freeb(mp); mp = mp_cont; } } mblk_t * copyb(mblk_t *bp) { mblk_t *nbp; unsigned char *ndp; assert((uintptr_t)(bp->b_wptr - bp->b_rptr) >= 0); if (!(nbp = allocb(bp->b_size, 0))) return (NULL); nbp->b_cont = NULL; ndp = nbp->b_datap; nbp->b_rptr = ndp + (bp->b_rptr - bp->b_datap); nbp->b_wptr = nbp->b_rptr + (bp->b_wptr - bp->b_rptr); bcopy(bp->b_datap, nbp->b_datap, bp->b_size); return (nbp); } /* To simplify things, dupb() is implemented as copyb(). */ mblk_t * dupb(mblk_t *mp) { return (copyb(mp)); } /* * get number of data bytes in message */ size_t msgdsize(mblk_t *bp) { size_t count = 0; for (; bp != NULL; bp = bp->b_cont) { assert(bp->b_wptr >= bp->b_rptr); count += bp->b_wptr - bp->b_rptr; } return (count); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Internal socket-specific definitions */ #ifndef _SOCKET_IMPL_H #define _SOCKET_IMPL_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include #include /* * Socket support definitions */ #define MAXSOCKET (10) #define SOCKETTYPE (65536) #define MEDIA_LVL 0 #define NETWORK_LVL 1 #define TRANSPORT_LVL 2 #define APP_LVL 3 /* Anonymous ports assigned by socket. */ #define SMALLEST_ANON_PORT 32768 #define LARGEST_ANON_PORT ((64 * 1024) - 1) /* Socket state bits. */ #define SS_ISCONNECTED 0x000001 /* socket connected to a peer */ #define SS_ISCONNECTING 0x000002 /* in process of connecting to peer */ #define SS_CANTRCVMORE 0x000010 /* can't receive more data from peer */ #define SS_CANTSENDMORE 0x000008 /* can't send more data to peer */ enum { FALSE, TRUE }; enum SockType { INETBOOT_UNUSED, INETBOOT_DGRAM, INETBOOT_RAW, INETBOOT_STREAM }; enum Ports { SOURCE, DESTINATION }; #define FD_TO_SOCKET(v) ((v) - SOCKETTYPE) /* * Message block descriptor copied from usr/src/uts/common/sys/stream.h. * We need to do that to simplify the porting of TCP code from core * kernel to inetboot. Note that fields which are not used by TCP * code are removed. */ typedef struct msgb { struct msgb *b_next; struct msgb *b_prev; struct msgb *b_cont; unsigned char *b_rptr; unsigned char *b_wptr; unsigned char *b_datap; size_t b_size; } mblk_t; /* Modified stream routines to ease TCP porting. */ extern mblk_t *allocb(size_t, uint_t); extern mblk_t *dupb(mblk_t *); extern void freeb(mblk_t *); extern void freemsg(mblk_t *); extern size_t msgdsize(mblk_t *); /* * "target" is needed for input prior to IP address assignment. It may * seem redundant given the binding information contained in the socket, * but that's only true if we have an IP address. If we don't, and we * try DHCP, we'll try to udp checksum using INADDR_ANY as the destination * IP address, when in fact the destination IP address was the IP address * we were OFFERED/Assigned. */ struct inetgram { /* Common */ struct sockaddr_in igm_saddr; /* source address info */ int igm_level; /* Stack level (LVL) of data */ mblk_t *igm_mp; struct inetgram *igm_next; /* next inetgram in list */ union { struct { /* Input specific */ struct in_addr in_t; uint16_t in_i; } _IN_un; struct { /* Output specific */ struct in_addr out_r; int out_f; } _OUT_un; } _i_o_inet; #define igm_target _i_o_inet._IN_un.in_t /* See above comment block */ #define igm_id _i_o_inet._IN_un.in_i /* IP id */ #define igm_router _i_o_inet._OUT_un.out_r /* first router IP ... */ #define igm_oflags _i_o_inet._OUT_un.out_f /* flag: 0 or MSG_DONTROUTE */ }; struct inetboot_socket { enum SockType type; /* socket type */ uint8_t proto; /* ip protocol */ int out_flags; /* 0 or MSG_DONTROUTE */ boolean_t bound; /* boolean */ uint32_t so_state; /* Socket state */ int so_error; /* Socket error */ struct sockaddr_in bind; /* Binding info */ struct sockaddr_in remote; /* Remote address */ struct inetgram *inq; /* input queue */ int so_sndbuf; /* max send buf size */ int so_rcvbuf; /* max receive buf size */ struct linger so_linger; /* close linger time */ uint32_t in_timeout; /* Input timeout (msec) */ uint32_t so_opt; /* socket level option */ int (*headerlen[APP_LVL])(struct inetgram *); int (*input[APP_LVL])(int); int (*output[APP_LVL])(int, struct inetgram *); int (*close[APP_LVL])(int); in_port_t (*ports)(uint16_t *, enum Ports); void *pcb; /* Protocol control block */ }; extern struct inetboot_socket sockets[MAXSOCKET]; extern void add_grams(struct inetgram **, struct inetgram *); extern void del_gram(struct inetgram **, struct inetgram *, int); extern void nuke_grams(struct inetgram **); extern struct inetgram *last_gram(struct inetgram *); extern int so_check_fd(int, int *); #ifdef __cplusplus } #endif #endif /* _SOCKET_IMPL_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Socket-specific definitions */ #ifndef _SOCKET_INET_H #define _SOCKET_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #include #include #ifdef __cplusplus extern "C" { #endif /* Network configuration protocol definitions */ enum nc_type { NCT_BOOTP_DHCP, NCT_RARP_BOOTPARAMS, NCT_MANUAL }; struct nct_t { char *p_name; enum nc_type p_id; }; #define NCT_DEFAULT NCT_RARP_BOOTPARAMS #define NCT_BUFSIZE (64) extern struct nct_t nct[]; extern int nct_entries; /* * Dynamic/private ports can be allocated in the range of 49152-65535. * Source: IANA (www.iana.org) port numbers. */ #define IPPORT_DYNAMIC_START 49152 extern int dontroute; extern int socket_read(int, void *, size_t, int); extern int socket_write(int, const void *, size_t, struct sockaddr_in *); extern int socket_close(int); extern int get_netconfig_strategy(void); extern in_port_t get_source_port(boolean_t); #ifdef __cplusplus } #endif #endif /* _SOCKET_INET_H */ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # LIBRARY = libtcp.a OBJECTS = tcp.o tcp_sack.o include ../Makefile.com CMNDIR = $(CMNNETDIR)/dhcp LDLIBS += -linet CPPFLAGS += -I../inet $(SOCKCPPFLAGS) CERRWARN += -Wno-unused-label CERRWARN += $(CNOWARN_UNINIT) # tcp.c is too hairy. SMATCH=off include ../Makefile.targ Copyright (c) 1982, 1986 Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the University of California, Berkeley and its contributors. 4. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PORTIONS OF STANDALONE TCP FUNCTIONALITY /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * Copyright (c) 2016 by Delphix. All rights reserved. * * tcp.c, Code implementing the TCP protocol. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "ipv4.h" #include "ipv4_impl.h" #include "mac.h" #include "mac_impl.h" #include "v4_sum_impl.h" #include #include "tcp_inet.h" #include "tcp_sack.h" #include #include /* * We need to redefine BUMP_MIB/UPDATE_MIB to not have DTrace probes. */ #undef BUMP_MIB #define BUMP_MIB(x) (x)++ #undef UPDATE_MIB #define UPDATE_MIB(x, y) x += y /* * MIB-2 stuff for SNMP */ mib2_tcp_t tcp_mib; /* SNMP fixed size info */ /* The TCP mib does not include the following errors. */ static uint_t tcp_cksum_errors; static uint_t tcp_drops; /* Macros for timestamp comparisons */ #define TSTMP_GEQ(a, b) ((int32_t)((a)-(b)) >= 0) #define TSTMP_LT(a, b) ((int32_t)((a)-(b)) < 0) /* * Parameters for TCP Initial Send Sequence number (ISS) generation. * The ISS is calculated by adding three components: a time component * which grows by 1 every 4096 nanoseconds (versus every 4 microseconds * suggested by RFC 793, page 27); * a per-connection component which grows by 125000 for every new connection; * and an "extra" component that grows by a random amount centered * approximately on 64000. This causes the the ISS generator to cycle every * 4.89 hours if no TCP connections are made, and faster if connections are * made. */ #define ISS_INCR 250000 #define ISS_NSEC_SHT 0 static uint32_t tcp_iss_incr_extra; /* Incremented for each connection */ #define TCP_XMIT_LOWATER 4096 #define TCP_XMIT_HIWATER 49152 #define TCP_RECV_LOWATER 2048 #define TCP_RECV_HIWATER 49152 /* * PAWS needs a timer for 24 days. This is the number of ms in 24 days */ #define PAWS_TIMEOUT ((uint32_t)(24*24*60*60*1000)) /* * TCP options struct returned from tcp_parse_options. */ typedef struct tcp_opt_s { uint32_t tcp_opt_mss; uint32_t tcp_opt_wscale; uint32_t tcp_opt_ts_val; uint32_t tcp_opt_ts_ecr; tcp_t *tcp; } tcp_opt_t; /* * RFC1323-recommended phrasing of TSTAMP option, for easier parsing */ #ifdef _BIG_ENDIAN #define TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \ (TCPOPT_TSTAMP << 8) | 10) #else #define TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \ (TCPOPT_NOP << 8) | TCPOPT_NOP) #endif /* * Flags returned from tcp_parse_options. */ #define TCP_OPT_MSS_PRESENT 1 #define TCP_OPT_WSCALE_PRESENT 2 #define TCP_OPT_TSTAMP_PRESENT 4 #define TCP_OPT_SACK_OK_PRESENT 8 #define TCP_OPT_SACK_PRESENT 16 /* TCP option length */ #define TCPOPT_NOP_LEN 1 #define TCPOPT_MAXSEG_LEN 4 #define TCPOPT_WS_LEN 3 #define TCPOPT_REAL_WS_LEN (TCPOPT_WS_LEN+1) #define TCPOPT_TSTAMP_LEN 10 #define TCPOPT_REAL_TS_LEN (TCPOPT_TSTAMP_LEN+2) #define TCPOPT_SACK_OK_LEN 2 #define TCPOPT_REAL_SACK_OK_LEN (TCPOPT_SACK_OK_LEN+2) #define TCPOPT_REAL_SACK_LEN 4 #define TCPOPT_MAX_SACK_LEN 36 #define TCPOPT_HEADER_LEN 2 /* TCP cwnd burst factor. */ #define TCP_CWND_INFINITE 65535 #define TCP_CWND_SS 3 #define TCP_CWND_NORMAL 5 /* Named Dispatch Parameter Management Structure */ typedef struct tcpparam_s { uint32_t tcp_param_min; uint32_t tcp_param_max; uint32_t tcp_param_val; char *tcp_param_name; } tcpparam_t; /* Max size IP datagram is 64k - 1 */ #define TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (struct ip) + \ sizeof (tcph_t))) /* Max of the above */ #define TCP_MSS_MAX TCP_MSS_MAX_IPV4 /* Largest TCP port number */ #define TCP_MAX_PORT (64 * 1024 - 1) /* Round up the value to the nearest mss. */ #define MSS_ROUNDUP(value, mss) ((((value) - 1) / (mss) + 1) * (mss)) #define MS 1L #define SECONDS (1000 * MS) #define MINUTES (60 * SECONDS) #define HOURS (60 * MINUTES) #define DAYS (24 * HOURS) /* All NDD params in the core TCP became static variables. */ static int tcp_time_wait_interval = 1 * MINUTES; static int tcp_conn_req_max_q = 128; static int tcp_conn_req_max_q0 = 1024; static int tcp_conn_req_min = 1; static int tcp_conn_grace_period = 0 * SECONDS; static int tcp_cwnd_max_ = 1024 * 1024; static int tcp_smallest_nonpriv_port = 1024; static int tcp_ip_abort_cinterval = 3 * MINUTES; static int tcp_ip_abort_linterval = 3 * MINUTES; static int tcp_ip_abort_interval = 8 * MINUTES; static int tcp_ip_notify_cinterval = 10 * SECONDS; static int tcp_ip_notify_interval = 10 * SECONDS; static int tcp_ipv4_ttl = 64; static int tcp_mss_def_ipv4 = 536; static int tcp_mss_max_ipv4 = TCP_MSS_MAX_IPV4; static int tcp_mss_min = 108; static int tcp_naglim_def = (4*1024)-1; static int tcp_rexmit_interval_initial = 3 * SECONDS; static int tcp_rexmit_interval_max = 60 * SECONDS; static int tcp_rexmit_interval_min = 400 * MS; static int tcp_dupack_fast_retransmit = 3; static int tcp_smallest_anon_port = 32 * 1024; static int tcp_largest_anon_port = TCP_MAX_PORT; static int tcp_xmit_lowat = TCP_XMIT_LOWATER; static int tcp_recv_hiwat_minmss = 4; static int tcp_fin_wait_2_flush_interval = 1 * MINUTES; static int tcp_max_buf = 1024 * 1024; static int tcp_wscale_always = 1; static int tcp_tstamp_always = 1; static int tcp_tstamp_if_wscale = 1; static int tcp_rexmit_interval_extra = 0; static int tcp_slow_start_after_idle = 2; static int tcp_slow_start_initial = 2; static int tcp_sack_permitted = 2; static int tcp_ecn_permitted = 2; /* Extra room to fit in headers. */ static uint_t tcp_wroff_xtra; /* Hint for next port to try. */ static in_port_t tcp_next_port_to_try = 32*1024; /* * Figure out the value of window scale opton. Note that the rwnd is * ASSUMED to be rounded up to the nearest MSS before the calculation. * We cannot find the scale value and then do a round up of tcp_rwnd * because the scale value may not be correct after that. */ #define SET_WS_VALUE(tcp) \ { \ int i; \ uint32_t rwnd = (tcp)->tcp_rwnd; \ for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT; \ i++, rwnd >>= 1) \ ; \ (tcp)->tcp_rcv_ws = i; \ } /* * Set ECN capable transport (ECT) code point in IP header. * * Note that there are 2 ECT code points '01' and '10', which are called * ECT(1) and ECT(0) respectively. Here we follow the original ECT code * point ECT(0) for TCP as described in RFC 2481. */ #define SET_ECT(tcp, iph) \ if ((tcp)->tcp_ipversion == IPV4_VERSION) { \ /* We need to clear the code point first. */ \ ((struct ip *)(iph))->ip_tos &= 0xFC; \ ((struct ip *)(iph))->ip_tos |= IPH_ECN_ECT0; \ } /* * The format argument to pass to tcp_display(). * DISP_PORT_ONLY means that the returned string has only port info. * DISP_ADDR_AND_PORT means that the returned string also contains the * remote and local IP address. */ #define DISP_PORT_ONLY 1 #define DISP_ADDR_AND_PORT 2 /* * TCP reassembly macros. We hide starting and ending sequence numbers in * b_next and b_prev of messages on the reassembly queue. The messages are * chained using b_cont. These macros are used in tcp_reass() so we don't * have to see the ugly casts and assignments. * Note. use uintptr_t to suppress the gcc warning. */ #define TCP_REASS_SEQ(mp) ((uint32_t)(uintptr_t)((mp)->b_next)) #define TCP_REASS_SET_SEQ(mp, u) ((mp)->b_next = \ (mblk_t *)((uintptr_t)(u))) #define TCP_REASS_END(mp) ((uint32_t)(uintptr_t)((mp)->b_prev)) #define TCP_REASS_SET_END(mp, u) ((mp)->b_prev = \ (mblk_t *)((uintptr_t)(u))) #define TCP_TIMER_RESTART(tcp, intvl) \ (tcp)->tcp_rto_timeout = prom_gettime() + intvl; \ (tcp)->tcp_timer_running = B_TRUE; static int tcp_accept_comm(tcp_t *, tcp_t *, mblk_t *, uint_t); static mblk_t *tcp_ack_mp(tcp_t *); static in_port_t tcp_bindi(in_port_t, in_addr_t *, boolean_t, boolean_t); static uint16_t tcp_cksum(uint16_t *, uint32_t); static void tcp_clean_death(int, tcp_t *, int err); static tcp_t *tcp_conn_request(tcp_t *, mblk_t *mp, uint_t, uint_t); static char *tcp_display(tcp_t *, char *, char); static int tcp_drain_input(tcp_t *, int, int); static void tcp_drain_needed(int, tcp_t *); static boolean_t tcp_drop_q0(tcp_t *); static mblk_t *tcp_get_seg_mp(tcp_t *, uint32_t, int32_t *); static int tcp_header_len(struct inetgram *); static in_port_t tcp_report_ports(uint16_t *, enum Ports); static int tcp_input(int); static void tcp_iss_init(tcp_t *); static tcp_t *tcp_lookup_ipv4(struct ip *, tcpha_t *, int, int *); static tcp_t *tcp_lookup_listener_ipv4(in_addr_t, in_port_t, int *); static int tcp_conn_check(tcp_t *); static int tcp_close(int); static void tcp_close_detached(tcp_t *); static void tcp_eager_cleanup(tcp_t *, boolean_t, int); static void tcp_eager_unlink(tcp_t *); static void tcp_free(tcp_t *); static int tcp_header_init_ipv4(tcp_t *); static void tcp_mss_set(tcp_t *, uint32_t); static int tcp_parse_options(tcph_t *, tcp_opt_t *); static boolean_t tcp_paws_check(tcp_t *, tcph_t *, tcp_opt_t *); static void tcp_process_options(tcp_t *, tcph_t *); static int tcp_random(void); static void tcp_random_init(void); static mblk_t *tcp_reass(tcp_t *, mblk_t *, uint32_t); static void tcp_reass_elim_overlap(tcp_t *, mblk_t *); static void tcp_rcv_drain(int sock_id, tcp_t *); static void tcp_rcv_enqueue(tcp_t *, mblk_t *, uint_t); static void tcp_rput_data(tcp_t *, mblk_t *, int); static int tcp_rwnd_set(tcp_t *, uint32_t); static int32_t tcp_sack_rxmit(tcp_t *, int); static void tcp_set_cksum(mblk_t *); static void tcp_set_rto(tcp_t *, int32_t); static void tcp_ss_rexmit(tcp_t *, int); static int tcp_state_wait(int, tcp_t *, int); static void tcp_timer(tcp_t *, int); static void tcp_time_wait_append(tcp_t *); static void tcp_time_wait_collector(void); static void tcp_time_wait_processing(tcp_t *, mblk_t *, uint32_t, uint32_t, int, tcph_t *, int sock_id); static void tcp_time_wait_remove(tcp_t *); static in_port_t tcp_update_next_port(in_port_t); static int tcp_verify_cksum(mblk_t *); static void tcp_wput_data(tcp_t *, mblk_t *, int); static void tcp_xmit_ctl(char *, tcp_t *, mblk_t *, uint32_t, uint32_t, int, uint_t, int); static void tcp_xmit_early_reset(char *, int, mblk_t *, uint32_t, uint32_t, int, uint_t); static int tcp_xmit_end(tcp_t *, int); static void tcp_xmit_listeners_reset(int, mblk_t *, uint_t); static mblk_t *tcp_xmit_mp(tcp_t *, mblk_t *, int32_t, int32_t *, mblk_t **, uint32_t, boolean_t, uint32_t *, boolean_t); static int tcp_init_values(tcp_t *, struct inetboot_socket *); #if DEBUG > 1 #define TCP_DUMP_PACKET(str, mp) \ { \ int len = (mp)->b_wptr - (mp)->b_rptr; \ \ printf("%s: dump TCP(%d): \n", (str), len); \ hexdump((char *)(mp)->b_rptr, len); \ } #else #define TCP_DUMP_PACKET(str, mp) #endif #ifdef DEBUG #define DEBUG_1(str, arg) printf(str, (arg)) #define DEBUG_2(str, arg1, arg2) printf(str, (arg1), (arg2)) #define DEBUG_3(str, arg1, arg2, arg3) printf(str, (arg1), (arg2), (arg3)) #else #define DEBUG_1(str, arg) #define DEBUG_2(str, arg1, arg2) #define DEBUG_3(str, arg1, arg2, arg3) #endif /* Whether it is the first time TCP is used. */ static boolean_t tcp_initialized = B_FALSE; /* TCP time wait list. */ static tcp_t *tcp_time_wait_head; static tcp_t *tcp_time_wait_tail; static uint32_t tcp_cum_timewait; /* When the tcp_time_wait_collector is run. */ static uint32_t tcp_time_wait_runtime; #define TCP_RUN_TIME_WAIT_COLLECTOR() \ if (prom_gettime() > tcp_time_wait_runtime) \ tcp_time_wait_collector(); /* * Accept will return with an error if there is no connection coming in * after this (in ms). */ static int tcp_accept_timeout = 60000; /* * Initialize the TCP-specific parts of a socket. */ void tcp_socket_init(struct inetboot_socket *isp) { /* Do some initializations. */ if (!tcp_initialized) { tcp_random_init(); /* Extra head room for the MAC layer address. */ if ((tcp_wroff_xtra = mac_get_hdr_len()) & 0x3) { tcp_wroff_xtra = (tcp_wroff_xtra & ~0x3) + 0x4; } /* Schedule the first time wait cleanup time */ tcp_time_wait_runtime = prom_gettime() + tcp_time_wait_interval; tcp_initialized = B_TRUE; } TCP_RUN_TIME_WAIT_COLLECTOR(); isp->proto = IPPROTO_TCP; isp->input[TRANSPORT_LVL] = tcp_input; /* Socket layer should call tcp_send() directly. */ isp->output[TRANSPORT_LVL] = NULL; isp->close[TRANSPORT_LVL] = tcp_close; isp->headerlen[TRANSPORT_LVL] = tcp_header_len; isp->ports = tcp_report_ports; if ((isp->pcb = bkmem_alloc(sizeof (tcp_t))) == NULL) { errno = ENOBUFS; return; } if ((errno = tcp_init_values((tcp_t *)isp->pcb, isp)) != 0) { bkmem_free(isp->pcb, sizeof (tcp_t)); return; } /* * This is set last because this field is used to determine if * a socket is in use or not. */ isp->type = INETBOOT_STREAM; } /* * Return the size of a TCP header including TCP option. */ static int tcp_header_len(struct inetgram *igm) { mblk_t *pkt; int ipvers; /* Just returns the standard TCP header without option */ if (igm == NULL) return (sizeof (tcph_t)); if ((pkt = igm->igm_mp) == NULL) return (0); ipvers = ((struct ip *)pkt->b_rptr)->ip_v; if (ipvers == IPV4_VERSION) { return (TCP_HDR_LENGTH((tcph_t *)(pkt + IPH_HDR_LENGTH(pkt)))); } else { dprintf("tcp_header_len: non-IPv4 packet.\n"); return (0); } } /* * Return the requested port number in network order. */ static in_port_t tcp_report_ports(uint16_t *tcphp, enum Ports request) { if (request == SOURCE) return (*(uint16_t *)(((tcph_t *)tcphp)->th_lport)); return (*(uint16_t *)(((tcph_t *)tcphp)->th_fport)); } /* * Because inetboot is not interrupt driven, TCP can only poll. This * means that there can be packets stuck in the NIC buffer waiting to * be processed. Thus we need to drain them before, for example, sending * anything because an ACK may actually be stuck there. * * The timeout arguments determine how long we should wait for draining. */ static int tcp_drain_input(tcp_t *tcp, int sock_id, int timeout) { struct inetgram *in_gram; struct inetgram *old_in_gram; int old_timeout; mblk_t *mp; int i; dprintf("tcp_drain_input(%d): %s\n", sock_id, tcp_display(tcp, NULL, DISP_ADDR_AND_PORT)); /* * Since the driver uses the in_timeout value in the socket * structure to determine the timeout value, we need to save * the original one so that we can restore that after draining. */ old_timeout = sockets[sock_id].in_timeout; sockets[sock_id].in_timeout = timeout; /* * We do this because the input queue may have some user * data already. */ old_in_gram = sockets[sock_id].inq; sockets[sock_id].inq = NULL; /* Go out and check the wire */ for (i = MEDIA_LVL; i < TRANSPORT_LVL; i++) { if (sockets[sock_id].input[i] != NULL) { if (sockets[sock_id].input[i](sock_id) < 0) { sockets[sock_id].in_timeout = old_timeout; if (sockets[sock_id].inq != NULL) nuke_grams(&sockets[sock_id].inq); sockets[sock_id].inq = old_in_gram; return (-1); } } } #if DEBUG printf("tcp_drain_input: done with checking packets\n"); #endif while ((in_gram = sockets[sock_id].inq) != NULL) { /* Remove unknown inetgrams from the head of inq. */ if (in_gram->igm_level != TRANSPORT_LVL) { #if DEBUG printf("tcp_drain_input: unexpected packet " "level %d frame found\n", in_gram->igm_level); #endif del_gram(&sockets[sock_id].inq, in_gram, B_TRUE); continue; } mp = in_gram->igm_mp; del_gram(&sockets[sock_id].inq, in_gram, B_FALSE); bkmem_free((caddr_t)in_gram, sizeof (struct inetgram)); tcp_rput_data(tcp, mp, sock_id); sockets[sock_id].in_timeout = old_timeout; /* * The other side may have closed this connection or * RST us. But we need to continue to process other * packets in the socket's queue because they may be * belong to another TCP connections. */ if (sockets[sock_id].pcb == NULL) tcp = NULL; } if (tcp == NULL || sockets[sock_id].pcb == NULL) { if (sockets[sock_id].so_error != 0) return (-1); else return (0); } #if DEBUG printf("tcp_drain_input: done with processing packets\n"); #endif sockets[sock_id].in_timeout = old_timeout; sockets[sock_id].inq = old_in_gram; /* * Data may have been received so indicate it is available */ tcp_drain_needed(sock_id, tcp); return (0); } /* * The receive entry point for upper layer to call to get data. Note * that this follows the current architecture that lower layer receive * routines have been called already. Thus if the inq of socket is * not NULL, the packets must be for us. */ static int tcp_input(int sock_id) { struct inetgram *in_gram; mblk_t *mp; tcp_t *tcp; TCP_RUN_TIME_WAIT_COLLECTOR(); if ((tcp = sockets[sock_id].pcb) == NULL) return (-1); while ((in_gram = sockets[sock_id].inq) != NULL) { /* Remove unknown inetgrams from the head of inq. */ if (in_gram->igm_level != TRANSPORT_LVL) { #ifdef DEBUG printf("tcp_input: unexpected packet " "level %d frame found\n", in_gram->igm_level); #endif del_gram(&sockets[sock_id].inq, in_gram, B_TRUE); continue; } mp = in_gram->igm_mp; del_gram(&sockets[sock_id].inq, in_gram, B_FALSE); bkmem_free((caddr_t)in_gram, sizeof (struct inetgram)); tcp_rput_data(tcp, mp, sock_id); /* The TCP may be gone because it gets a RST. */ if (sockets[sock_id].pcb == NULL) return (-1); } /* Flush the receive list. */ if (tcp->tcp_rcv_list != NULL) { tcp_rcv_drain(sock_id, tcp); } else { /* The other side has closed the connection, report this up. */ if (tcp->tcp_state == TCPS_CLOSE_WAIT) { sockets[sock_id].so_state |= SS_CANTRCVMORE; return (0); } } return (0); } /* * The send entry point for upper layer to call to send data. In order * to minimize changes to the core TCP code, we need to put the * data into mblks. */ int tcp_send(int sock_id, tcp_t *tcp, const void *msg, int len) { mblk_t *mp; mblk_t *head = NULL; mblk_t *tail; int mss = tcp->tcp_mss; int cnt = 0; int win_size; char *buf = (char *)msg; TCP_RUN_TIME_WAIT_COLLECTOR(); /* We don't want to append 0 size mblk. */ if (len == 0) return (0); while (len > 0) { if (len < mss) { mss = len; } /* * If we cannot allocate more buffer, stop here and * the number of bytes buffered will be returned. * * Note that we follow the core TCP optimization that * each mblk contains only MSS bytes data. */ if ((mp = allocb(mss + tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra, 0)) == NULL) { break; } mp->b_rptr += tcp->tcp_hdr_len + tcp_wroff_xtra; bcopy(buf, mp->b_rptr, mss); mp->b_wptr = mp->b_rptr + mss; buf += mss; cnt += mss; len -= mss; if (head == NULL) { head = mp; tail = mp; } else { tail->b_cont = mp; tail = mp; } } /* * Since inetboot is not interrupt driven, there may be * some ACKs in the MAC's buffer. Drain them first, * otherwise, we may not be able to send. * * We expect an ACK in two cases: * * 1) We have un-ACK'ed data. * * 2) All ACK's have been received and the sender's window has been * closed. We need an ACK back to open the window so that we can * send. In this case, call tcp_drain_input() if the window size is * less than 2 * MSS. */ /* window size = MIN(swnd, cwnd) - unacked bytes */ win_size = (tcp->tcp_swnd > tcp->tcp_cwnd) ? tcp->tcp_cwnd : tcp->tcp_swnd; win_size -= tcp->tcp_snxt; win_size += tcp->tcp_suna; if (win_size < (2 * tcp->tcp_mss)) if (tcp_drain_input(tcp, sock_id, 5) < 0) return (-1); tcp_wput_data(tcp, head, sock_id); /* * errno should be reset here as it may be * set to ETIMEDOUT. This may be set by * the MAC driver in case it has timed out * waiting for ARP reply. Any segment which * was not transmitted because of ARP timeout * will be retransmitted by TCP. */ if (errno == ETIMEDOUT) errno = 0; return (cnt); } /* Free up all TCP related stuff */ static void tcp_free(tcp_t *tcp) { if (tcp->tcp_iphc != NULL) { bkmem_free((caddr_t)tcp->tcp_iphc, tcp->tcp_iphc_len); tcp->tcp_iphc = NULL; } if (tcp->tcp_xmit_head != NULL) { freemsg(tcp->tcp_xmit_head); tcp->tcp_xmit_head = NULL; } if (tcp->tcp_rcv_list != NULL) { freemsg(tcp->tcp_rcv_list); tcp->tcp_rcv_list = NULL; } if (tcp->tcp_reass_head != NULL) { freemsg(tcp->tcp_reass_head); tcp->tcp_reass_head = NULL; } if (tcp->tcp_sack_info != NULL) { bkmem_free((caddr_t)tcp->tcp_sack_info, sizeof (tcp_sack_info_t)); tcp->tcp_sack_info = NULL; } } static void tcp_close_detached(tcp_t *tcp) { if (tcp->tcp_listener != NULL) tcp_eager_unlink(tcp); tcp_free(tcp); bkmem_free((caddr_t)tcp, sizeof (tcp_t)); } /* * If we are an eager connection hanging off a listener that hasn't * formally accepted the connection yet, get off its list and blow off * any data that we have accumulated. */ static void tcp_eager_unlink(tcp_t *tcp) { tcp_t *listener = tcp->tcp_listener; assert(listener != NULL); if (tcp->tcp_eager_next_q0 != NULL) { assert(tcp->tcp_eager_prev_q0 != NULL); /* Remove the eager tcp from q0 */ tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = tcp->tcp_eager_prev_q0; tcp->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp->tcp_eager_next_q0; listener->tcp_conn_req_cnt_q0--; } else { tcp_t **tcpp = &listener->tcp_eager_next_q; tcp_t *prev = NULL; for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) { if (tcpp[0] == tcp) { if (listener->tcp_eager_last_q == tcp) { /* * If we are unlinking the last * element on the list, adjust * tail pointer. Set tail pointer * to nil when list is empty. */ assert(tcp->tcp_eager_next_q == NULL); if (listener->tcp_eager_last_q == listener->tcp_eager_next_q) { listener->tcp_eager_last_q = NULL; } else { /* * We won't get here if there * is only one eager in the * list. */ assert(prev != NULL); listener->tcp_eager_last_q = prev; } } tcpp[0] = tcp->tcp_eager_next_q; tcp->tcp_eager_next_q = NULL; tcp->tcp_eager_last_q = NULL; listener->tcp_conn_req_cnt_q--; break; } prev = tcpp[0]; } } tcp->tcp_listener = NULL; } /* * Reset any eager connection hanging off this listener * and then reclaim it's resources. */ static void tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only, int sock_id) { tcp_t *eager; if (!q0_only) { /* First cleanup q */ while ((eager = listener->tcp_eager_next_q) != NULL) { assert(listener->tcp_eager_last_q != NULL); tcp_xmit_ctl("tcp_eager_cleanup, can't wait", eager, NULL, eager->tcp_snxt, 0, TH_RST, 0, sock_id); tcp_close_detached(eager); } assert(listener->tcp_eager_last_q == NULL); } /* Then cleanup q0 */ while ((eager = listener->tcp_eager_next_q0) != listener) { tcp_xmit_ctl("tcp_eager_cleanup, can't wait", eager, NULL, eager->tcp_snxt, 0, TH_RST, 0, sock_id); tcp_close_detached(eager); } } /* * To handle the shutdown request. Called from shutdown() */ int tcp_shutdown(int sock_id) { tcp_t *tcp; DEBUG_1("tcp_shutdown: sock_id %x\n", sock_id); if ((tcp = sockets[sock_id].pcb) == NULL) { return (-1); } /* * Since inetboot is not interrupt driven, there may be * some ACKs in the MAC's buffer. Drain them first, * otherwise, we may not be able to send. */ if (tcp_drain_input(tcp, sock_id, 5) < 0) { /* * If we return now without freeing TCP, there will be * a memory leak. */ if (sockets[sock_id].pcb != NULL) tcp_clean_death(sock_id, tcp, 0); return (-1); } DEBUG_1("tcp_shutdown: tcp_state %x\n", tcp->tcp_state); switch (tcp->tcp_state) { case TCPS_SYN_RCVD: /* * Shutdown during the connect 3-way handshake */ case TCPS_ESTABLISHED: /* * Transmit the FIN * wait for the FIN to be ACKed, * then remain in FIN_WAIT_2 */ dprintf("tcp_shutdown: sending fin\n"); if (tcp_xmit_end(tcp, sock_id) == 0 && tcp_state_wait(sock_id, tcp, TCPS_FIN_WAIT_2) < 0) { /* During the wait, TCP may be gone... */ if (sockets[sock_id].pcb == NULL) return (-1); } dprintf("tcp_shutdown: done\n"); break; default: break; } return (0); } /* To handle closing of the socket */ static int tcp_close(int sock_id) { char *msg; tcp_t *tcp; int error = 0; if ((tcp = sockets[sock_id].pcb) == NULL) { return (-1); } TCP_RUN_TIME_WAIT_COLLECTOR(); /* * Since inetboot is not interrupt driven, there may be * some ACKs in the MAC's buffer. Drain them first, * otherwise, we may not be able to send. */ if (tcp_drain_input(tcp, sock_id, 5) < 0) { /* * If we return now without freeing TCP, there will be * a memory leak. */ if (sockets[sock_id].pcb != NULL) tcp_clean_death(sock_id, tcp, 0); return (-1); } if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) { /* Cleanup for listener */ tcp_eager_cleanup(tcp, 0, sock_id); } msg = NULL; switch (tcp->tcp_state) { case TCPS_CLOSED: case TCPS_IDLE: case TCPS_BOUND: case TCPS_LISTEN: break; case TCPS_SYN_SENT: msg = "tcp_close, during connect"; break; case TCPS_SYN_RCVD: /* * Close during the connect 3-way handshake * but here there may or may not be pending data * already on queue. Process almost same as in * the ESTABLISHED state. */ /* FALLTHRU */ default: /* * If SO_LINGER has set a zero linger time, abort the * connection with a reset. */ if (tcp->tcp_linger && tcp->tcp_lingertime == 0) { msg = "tcp_close, zero lingertime"; break; } /* * Abort connection if there is unread data queued. */ if (tcp->tcp_rcv_list != NULL || tcp->tcp_reass_head != NULL) { msg = "tcp_close, unread data"; break; } if (tcp->tcp_state <= TCPS_LISTEN) break; /* * Transmit the FIN before detaching the tcp_t. * After tcp_detach returns this queue/perimeter * no longer owns the tcp_t thus others can modify it. * The TCP could be closed in tcp_state_wait called by * tcp_wput_data called by tcp_xmit_end. */ (void) tcp_xmit_end(tcp, sock_id); if (sockets[sock_id].pcb == NULL) return (0); /* * If lingering on close then wait until the fin is acked, * the SO_LINGER time passes, or a reset is sent/received. */ if (tcp->tcp_linger && tcp->tcp_lingertime > 0 && !(tcp->tcp_fin_acked) && tcp->tcp_state >= TCPS_ESTABLISHED) { uint32_t stoptime; /* in ms */ tcp->tcp_client_errno = 0; stoptime = prom_gettime() + (tcp->tcp_lingertime * 1000); while (!(tcp->tcp_fin_acked) && tcp->tcp_state >= TCPS_ESTABLISHED && tcp->tcp_client_errno == 0 && ((int32_t)(stoptime - prom_gettime()) > 0)) { if (tcp_drain_input(tcp, sock_id, 5) < 0) { if (sockets[sock_id].pcb != NULL) { tcp_clean_death(sock_id, tcp, 0); } return (-1); } } tcp->tcp_client_errno = 0; } if (tcp_state_wait(sock_id, tcp, TCPS_TIME_WAIT) < 0) { /* During the wait, TCP may be gone... */ if (sockets[sock_id].pcb == NULL) return (0); msg = "tcp_close, couldn't detach"; } else { return (0); } break; } /* Something went wrong... Send a RST and report the error */ if (msg != NULL) { if (tcp->tcp_state == TCPS_ESTABLISHED || tcp->tcp_state == TCPS_CLOSE_WAIT) BUMP_MIB(tcp_mib.tcpEstabResets); if (tcp->tcp_state == TCPS_SYN_SENT || tcp->tcp_state == TCPS_SYN_RCVD) BUMP_MIB(tcp_mib.tcpAttemptFails); tcp_xmit_ctl(msg, tcp, NULL, tcp->tcp_snxt, 0, TH_RST, 0, sock_id); } tcp_free(tcp); bkmem_free((caddr_t)tcp, sizeof (tcp_t)); sockets[sock_id].pcb = NULL; return (error); } /* To make an endpoint a listener. */ int tcp_listen(int sock_id, int backlog) { tcp_t *tcp; if ((tcp = (tcp_t *)(sockets[sock_id].pcb)) == NULL) { errno = EINVAL; return (-1); } /* We allow calling listen() multiple times to change the backlog. */ if (tcp->tcp_state > TCPS_LISTEN || tcp->tcp_state < TCPS_BOUND) { errno = EOPNOTSUPP; return (-1); } /* The following initialization should only be done once. */ if (tcp->tcp_state != TCPS_LISTEN) { tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp; tcp->tcp_eager_next_q = NULL; tcp->tcp_state = TCPS_LISTEN; tcp->tcp_second_ctimer_threshold = tcp_ip_abort_linterval; } if ((tcp->tcp_conn_req_max = backlog) > tcp_conn_req_max_q) { tcp->tcp_conn_req_max = tcp_conn_req_max_q; } if (tcp->tcp_conn_req_max < tcp_conn_req_min) { tcp->tcp_conn_req_max = tcp_conn_req_min; } return (0); } /* To accept connections. */ int tcp_accept(int sock_id, struct sockaddr *addr, socklen_t *addr_len) { tcp_t *listener; tcp_t *eager; int sd, new_sock_id; struct sockaddr_in *new_addr = (struct sockaddr_in *)addr; int timeout; /* Sanity check. */ if ((listener = (tcp_t *)(sockets[sock_id].pcb)) == NULL || new_addr == NULL || addr_len == NULL || *addr_len < sizeof (struct sockaddr_in) || listener->tcp_state != TCPS_LISTEN) { errno = EINVAL; return (-1); } if (sockets[sock_id].in_timeout > tcp_accept_timeout) timeout = prom_gettime() + sockets[sock_id].in_timeout; else timeout = prom_gettime() + tcp_accept_timeout; while (listener->tcp_eager_next_q == NULL && timeout > prom_gettime()) { #if DEBUG printf("tcp_accept: Waiting in tcp_accept()\n"); #endif if (tcp_drain_input(listener, sock_id, 5) < 0) { return (-1); } } /* If there is an eager, don't timeout... */ if (timeout <= prom_gettime() && listener->tcp_eager_next_q == NULL) { #if DEBUG printf("tcp_accept: timeout\n"); #endif errno = ETIMEDOUT; return (-1); } #if DEBUG printf("tcp_accept: got a connection\n"); #endif /* Now create the socket for this new TCP. */ if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { return (-1); } if ((new_sock_id = so_check_fd(sd, &errno)) == -1) /* This should not happen! */ prom_panic("so_check_fd() fails in tcp_accept()"); /* Free the TCP PCB in the original socket. */ bkmem_free((caddr_t)(sockets[new_sock_id].pcb), sizeof (tcp_t)); /* Dequeue the eager and attach it to the socket. */ eager = listener->tcp_eager_next_q; listener->tcp_eager_next_q = eager->tcp_eager_next_q; if (listener->tcp_eager_last_q == eager) listener->tcp_eager_last_q = NULL; eager->tcp_eager_next_q = NULL; sockets[new_sock_id].pcb = eager; listener->tcp_conn_req_cnt_q--; /* Copy in the address info. */ bcopy(&eager->tcp_remote, &new_addr->sin_addr.s_addr, sizeof (in_addr_t)); bcopy(&eager->tcp_fport, &new_addr->sin_port, sizeof (in_port_t)); new_addr->sin_family = AF_INET; #ifdef DEBUG printf("tcp_accept(), new sock_id: %d\n", sd); #endif return (sd); } /* Update the next anonymous port to use. */ static in_port_t tcp_update_next_port(in_port_t port) { /* Don't allow the port to fall out of the anonymous port range. */ if (port < tcp_smallest_anon_port || port > tcp_largest_anon_port) port = (in_port_t)tcp_smallest_anon_port; if (port < tcp_smallest_nonpriv_port) port = (in_port_t)tcp_smallest_nonpriv_port; return (port); } /* To check whether a bind to a port is allowed. */ static in_port_t tcp_bindi(in_port_t port, in_addr_t *addr, boolean_t reuseaddr, boolean_t bind_to_req_port_only) { int i, count; tcp_t *tcp; count = tcp_largest_anon_port - tcp_smallest_anon_port; try_again: for (i = 0; i < MAXSOCKET; i++) { if (sockets[i].type != INETBOOT_STREAM || ((tcp = (tcp_t *)sockets[i].pcb) == NULL) || ntohs(tcp->tcp_lport) != port) { continue; } /* * Both TCPs have the same port. If SO_REUSEDADDR is * set and the bound TCP has a state greater than * TCPS_LISTEN, it is fine. */ if (reuseaddr && tcp->tcp_state > TCPS_LISTEN) { continue; } if (tcp->tcp_bound_source != INADDR_ANY && *addr != INADDR_ANY && tcp->tcp_bound_source != *addr) { continue; } if (bind_to_req_port_only) { return (0); } if (--count > 0) { port = tcp_update_next_port(++port); goto try_again; } else { return (0); } } return (port); } /* To handle the bind request. */ int tcp_bind(int sock_id) { tcp_t *tcp; in_port_t requested_port, allocated_port; boolean_t bind_to_req_port_only; boolean_t reuseaddr; if ((tcp = (tcp_t *)sockets[sock_id].pcb) == NULL) { errno = EINVAL; return (-1); } if (tcp->tcp_state >= TCPS_BOUND) { /* We don't allow multiple bind(). */ errno = EPROTO; return (-1); } requested_port = ntohs(sockets[sock_id].bind.sin_port); /* The bound source can be INADDR_ANY. */ tcp->tcp_bound_source = sockets[sock_id].bind.sin_addr.s_addr; tcp->tcp_ipha->ip_src.s_addr = tcp->tcp_bound_source; /* Verify the port is available. */ if (requested_port == 0) bind_to_req_port_only = B_FALSE; else /* T_BIND_REQ and requested_port != 0 */ bind_to_req_port_only = B_TRUE; if (requested_port == 0) { requested_port = tcp_update_next_port(++tcp_next_port_to_try); } reuseaddr = sockets[sock_id].so_opt & SO_REUSEADDR; allocated_port = tcp_bindi(requested_port, &(tcp->tcp_bound_source), reuseaddr, bind_to_req_port_only); if (allocated_port == 0) { errno = EADDRINUSE; return (-1); } tcp->tcp_lport = htons(allocated_port); *(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport; sockets[sock_id].bind.sin_port = tcp->tcp_lport; tcp->tcp_state = TCPS_BOUND; return (0); } /* * Check for duplicate TCP connections. */ static int tcp_conn_check(tcp_t *tcp) { int i; tcp_t *tmp_tcp; for (i = 0; i < MAXSOCKET; i++) { if (sockets[i].type != INETBOOT_STREAM) continue; /* Socket may not be closed but the TCP can be gone. */ if ((tmp_tcp = (tcp_t *)sockets[i].pcb) == NULL) continue; /* We only care about TCP in states later than SYN_SENT. */ if (tmp_tcp->tcp_state < TCPS_SYN_SENT) continue; if (tmp_tcp->tcp_lport != tcp->tcp_lport || tmp_tcp->tcp_fport != tcp->tcp_fport || tmp_tcp->tcp_bound_source != tcp->tcp_bound_source || tmp_tcp->tcp_remote != tcp->tcp_remote) { continue; } else { return (-1); } } return (0); } /* To handle a connect request. */ int tcp_connect(int sock_id) { tcp_t *tcp; in_addr_t dstaddr; in_port_t dstport; tcph_t *tcph; int mss; mblk_t *syn_mp; if ((tcp = (tcp_t *)(sockets[sock_id].pcb)) == NULL) { errno = EINVAL; return (-1); } TCP_RUN_TIME_WAIT_COLLECTOR(); dstaddr = sockets[sock_id].remote.sin_addr.s_addr; dstport = sockets[sock_id].remote.sin_port; /* * Check for attempt to connect to INADDR_ANY or non-unicast addrress. * We don't have enough info to check for broadcast addr, except * for the all 1 broadcast. */ if (dstaddr == INADDR_ANY || IN_CLASSD(ntohl(dstaddr)) || dstaddr == INADDR_BROADCAST) { /* * SunOS 4.x and 4.3 BSD allow an application * to connect a TCP socket to INADDR_ANY. * When they do this, the kernel picks the * address of one interface and uses it * instead. The kernel usually ends up * picking the address of the loopback * interface. This is an undocumented feature. * However, we provide the same thing here * in order to have source and binary * compatibility with SunOS 4.x. * Update the T_CONN_REQ (sin/sin6) since it is used to * generate the T_CONN_CON. * * Fail this for inetboot TCP. */ errno = EINVAL; return (-1); } /* It is not bound to any address yet... */ if (tcp->tcp_bound_source == INADDR_ANY) { ipv4_getipaddr(&(sockets[sock_id].bind.sin_addr)); /* We don't have an address! */ if (ntohl(sockets[sock_id].bind.sin_addr.s_addr) == INADDR_ANY) { errno = EPROTO; return (-1); } tcp->tcp_bound_source = sockets[sock_id].bind.sin_addr.s_addr; tcp->tcp_ipha->ip_src.s_addr = tcp->tcp_bound_source; } /* * Don't let an endpoint connect to itself. */ if (dstaddr == tcp->tcp_ipha->ip_src.s_addr && dstport == tcp->tcp_lport) { errno = EINVAL; return (-1); } tcp->tcp_ipha->ip_dst.s_addr = dstaddr; tcp->tcp_remote = dstaddr; tcph = tcp->tcp_tcph; *(uint16_t *)tcph->th_fport = dstport; tcp->tcp_fport = dstport; /* * Don't allow this connection to completely duplicate * an existing connection. */ if (tcp_conn_check(tcp) < 0) { errno = EADDRINUSE; return (-1); } /* * Just make sure our rwnd is at * least tcp_recv_hiwat_mss * MSS * large, and round up to the nearest * MSS. * * We do the round up here because * we need to get the interface * MTU first before we can do the * round up. */ mss = tcp->tcp_mss - tcp->tcp_hdr_len; tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss), tcp_recv_hiwat_minmss * mss); tcp->tcp_rwnd_max = tcp->tcp_rwnd; SET_WS_VALUE(tcp); U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws), tcp->tcp_tcph->th_win); if (tcp->tcp_rcv_ws > 0 || tcp_wscale_always) tcp->tcp_snd_ws_ok = B_TRUE; /* * Set tcp_snd_ts_ok to true * so that tcp_xmit_mp will * include the timestamp * option in the SYN segment. */ if (tcp_tstamp_always || (tcp->tcp_rcv_ws && tcp_tstamp_if_wscale)) { tcp->tcp_snd_ts_ok = B_TRUE; } if (tcp_sack_permitted == 2 || tcp->tcp_snd_sack_ok) { assert(tcp->tcp_sack_info == NULL); if ((tcp->tcp_sack_info = (tcp_sack_info_t *)bkmem_zalloc( sizeof (tcp_sack_info_t))) == NULL) { tcp->tcp_snd_sack_ok = B_FALSE; } else { tcp->tcp_snd_sack_ok = B_TRUE; } } /* * Should we use ECN? Note that the current * default value (SunOS 5.9) of tcp_ecn_permitted * is 2. The reason for doing this is that there * are equipments out there that will drop ECN * enabled IP packets. Setting it to 1 avoids * compatibility problems. */ if (tcp_ecn_permitted == 2) tcp->tcp_ecn_ok = B_TRUE; tcp_iss_init(tcp); TCP_TIMER_RESTART(tcp, tcp->tcp_rto); tcp->tcp_active_open = B_TRUE; tcp->tcp_state = TCPS_SYN_SENT; syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE); if (syn_mp != NULL) { int ret; /* Dump the packet when debugging. */ TCP_DUMP_PACKET("tcp_connect", syn_mp); /* Send out the SYN packet. */ ret = ipv4_tcp_output(sock_id, syn_mp); freeb(syn_mp); /* * errno ETIMEDOUT is set by the mac driver * in case it is not able to receive ARP reply. * TCP will retransmit this segment so we can * ignore the ARP timeout. */ if ((ret < 0) && (errno != ETIMEDOUT)) { return (-1); } /* tcp_state_wait() will finish the 3 way handshake. */ return (tcp_state_wait(sock_id, tcp, TCPS_ESTABLISHED)); } else { errno = ENOBUFS; return (-1); } } /* * Common accept code. Called by tcp_conn_request. * cr_pkt is the SYN packet. */ static int tcp_accept_comm(tcp_t *listener, tcp_t *acceptor, mblk_t *cr_pkt, uint_t ip_hdr_len) { tcph_t *tcph; #ifdef DEBUG printf("tcp_accept_comm #######################\n"); #endif /* * When we get here, we know that the acceptor header template * has already been initialized. * However, it may not match the listener if the listener * includes options... * It may also not match the listener if the listener is v6 and * and the acceptor is v4 */ acceptor->tcp_lport = listener->tcp_lport; if (listener->tcp_ipversion == acceptor->tcp_ipversion) { if (acceptor->tcp_iphc_len != listener->tcp_iphc_len) { /* * Listener had options of some sort; acceptor inherits. * Free up the acceptor template and allocate one * of the right size. */ bkmem_free(acceptor->tcp_iphc, acceptor->tcp_iphc_len); acceptor->tcp_iphc = bkmem_zalloc( listener->tcp_iphc_len); if (acceptor->tcp_iphc == NULL) { acceptor->tcp_iphc_len = 0; return (ENOMEM); } acceptor->tcp_iphc_len = listener->tcp_iphc_len; } acceptor->tcp_hdr_len = listener->tcp_hdr_len; acceptor->tcp_ip_hdr_len = listener->tcp_ip_hdr_len; acceptor->tcp_tcp_hdr_len = listener->tcp_tcp_hdr_len; /* * Copy the IP+TCP header template from listener to acceptor */ bcopy(listener->tcp_iphc, acceptor->tcp_iphc, listener->tcp_hdr_len); acceptor->tcp_ipha = (struct ip *)acceptor->tcp_iphc; acceptor->tcp_tcph = (tcph_t *)(acceptor->tcp_iphc + acceptor->tcp_ip_hdr_len); } else { prom_panic("tcp_accept_comm: version not equal"); } /* Copy our new dest and fport from the connection request packet */ if (acceptor->tcp_ipversion == IPV4_VERSION) { struct ip *ipha; ipha = (struct ip *)cr_pkt->b_rptr; acceptor->tcp_ipha->ip_dst = ipha->ip_src; acceptor->tcp_remote = ipha->ip_src.s_addr; acceptor->tcp_ipha->ip_src = ipha->ip_dst; acceptor->tcp_bound_source = ipha->ip_dst.s_addr; tcph = (tcph_t *)&cr_pkt->b_rptr[ip_hdr_len]; } else { prom_panic("tcp_accept_comm: not IPv4"); } bcopy(tcph->th_lport, acceptor->tcp_tcph->th_fport, sizeof (in_port_t)); bcopy(acceptor->tcp_tcph->th_fport, &acceptor->tcp_fport, sizeof (in_port_t)); /* * For an all-port proxy listener, the local port is determined by * the port number field in the SYN packet. */ if (listener->tcp_lport == 0) { acceptor->tcp_lport = *(in_port_t *)tcph->th_fport; bcopy(tcph->th_fport, acceptor->tcp_tcph->th_lport, sizeof (in_port_t)); } /* Inherit various TCP parameters from the listener */ acceptor->tcp_naglim = listener->tcp_naglim; acceptor->tcp_first_timer_threshold = listener->tcp_first_timer_threshold; acceptor->tcp_second_timer_threshold = listener->tcp_second_timer_threshold; acceptor->tcp_first_ctimer_threshold = listener->tcp_first_ctimer_threshold; acceptor->tcp_second_ctimer_threshold = listener->tcp_second_ctimer_threshold; acceptor->tcp_xmit_hiwater = listener->tcp_xmit_hiwater; acceptor->tcp_state = TCPS_LISTEN; tcp_iss_init(acceptor); /* Process all TCP options. */ tcp_process_options(acceptor, tcph); /* Is the other end ECN capable? */ if (tcp_ecn_permitted >= 1 && (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) { acceptor->tcp_ecn_ok = B_TRUE; } /* * listener->tcp_rq->q_hiwat should be the default window size or a * window size changed via SO_RCVBUF option. First round up the * acceptor's tcp_rwnd to the nearest MSS. Then find out the window * scale option value if needed. Call tcp_rwnd_set() to finish the * setting. * * Note if there is a rpipe metric associated with the remote host, * we should not inherit receive window size from listener. */ acceptor->tcp_rwnd = MSS_ROUNDUP( (acceptor->tcp_rwnd == 0 ? listener->tcp_rwnd_max : acceptor->tcp_rwnd), acceptor->tcp_mss); if (acceptor->tcp_snd_ws_ok) SET_WS_VALUE(acceptor); /* * Note that this is the only place tcp_rwnd_set() is called for * accepting a connection. We need to call it here instead of * after the 3-way handshake because we need to tell the other * side our rwnd in the SYN-ACK segment. */ (void) tcp_rwnd_set(acceptor, acceptor->tcp_rwnd); return (0); } /* * Defense for the SYN attack - * 1. When q0 is full, drop from the tail (tcp_eager_prev_q0) the oldest * one that doesn't have the dontdrop bit set. * 2. Don't drop a SYN request before its first timeout. This gives every * request at least til the first timeout to complete its 3-way handshake. * 3. The current threshold is - # of timeout > q0len/4 => SYN alert on * # of timeout drops back to <= q0len/32 => SYN alert off */ static boolean_t tcp_drop_q0(tcp_t *tcp) { tcp_t *eager; assert(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0); /* * New one is added after next_q0 so prev_q0 points to the oldest * Also do not drop any established connections that are deferred on * q0 due to q being full */ eager = tcp->tcp_eager_prev_q0; while (eager->tcp_dontdrop || eager->tcp_conn_def_q0) { /* XXX should move the eager to the head */ eager = eager->tcp_eager_prev_q0; if (eager == tcp) { eager = tcp->tcp_eager_prev_q0; break; } } dprintf("tcp_drop_q0: listen half-open queue (max=%d) overflow" " (%d pending) on %s, drop one", tcp_conn_req_max_q0, tcp->tcp_conn_req_cnt_q0, tcp_display(tcp, NULL, DISP_PORT_ONLY)); BUMP_MIB(tcp_mib.tcpHalfOpenDrop); bkmem_free((caddr_t)eager, sizeof (tcp_t)); return (B_TRUE); } /* ARGSUSED */ static tcp_t * tcp_conn_request(tcp_t *tcp, mblk_t *mp, uint_t sock_id, uint_t ip_hdr_len) { tcp_t *eager; struct ip *ipha; int err; #ifdef DEBUG printf("tcp_conn_request ###################\n"); #endif if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) { BUMP_MIB(tcp_mib.tcpListenDrop); dprintf("tcp_conn_request: listen backlog (max=%d) " "overflow (%d pending) on %s", tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q, tcp_display(tcp, NULL, DISP_PORT_ONLY)); return (NULL); } assert(OK_32PTR(mp->b_rptr)); if (tcp->tcp_conn_req_cnt_q0 >= tcp->tcp_conn_req_max + tcp_conn_req_max_q0) { /* * Q0 is full. Drop a pending half-open req from the queue * to make room for the new SYN req. Also mark the time we * drop a SYN. */ tcp->tcp_last_rcv_lbolt = prom_gettime(); if (!tcp_drop_q0(tcp)) { freemsg(mp); BUMP_MIB(tcp_mib.tcpListenDropQ0); dprintf("tcp_conn_request: listen half-open queue " "(max=%d) full (%d pending) on %s", tcp_conn_req_max_q0, tcp->tcp_conn_req_cnt_q0, tcp_display(tcp, NULL, DISP_PORT_ONLY)); return (NULL); } } ipha = (struct ip *)mp->b_rptr; if (IN_CLASSD(ntohl(ipha->ip_src.s_addr)) || ipha->ip_src.s_addr == INADDR_BROADCAST || ipha->ip_src.s_addr == INADDR_ANY || ipha->ip_dst.s_addr == INADDR_BROADCAST) { freemsg(mp); return (NULL); } /* * We allow the connection to proceed * by generating a detached tcp state vector and put it in * the eager queue. When an accept happens, it will be * dequeued sequentially. */ if ((eager = (tcp_t *)bkmem_alloc(sizeof (tcp_t))) == NULL) { freemsg(mp); errno = ENOBUFS; return (NULL); } if ((errno = tcp_init_values(eager, NULL)) != 0) { freemsg(mp); bkmem_free((caddr_t)eager, sizeof (tcp_t)); return (NULL); } /* * Eager connection inherits address form from its listener, * but its packet form comes from the version of the received * SYN segment. */ eager->tcp_family = tcp->tcp_family; err = tcp_accept_comm(tcp, eager, mp, ip_hdr_len); if (err) { bkmem_free((caddr_t)eager, sizeof (tcp_t)); return (NULL); } tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager; eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0; tcp->tcp_eager_next_q0 = eager; eager->tcp_eager_prev_q0 = tcp; /* Set tcp_listener before adding it to tcp_conn_fanout */ eager->tcp_listener = tcp; tcp->tcp_conn_req_cnt_q0++; return (eager); } /* * To get around the non-interrupt problem of inetboot. * Keep on processing packets until a certain state is reached or the * TCP is destroyed because of getting a RST packet. */ static int tcp_state_wait(int sock_id, tcp_t *tcp, int state) { int i; struct inetgram *in_gram; mblk_t *mp; int timeout; boolean_t changed = B_FALSE; /* * We need to make sure that the MAC does not wait longer * than RTO for any packet so that TCP can do retransmission. * But if the MAC timeout is less than tcp_rto, we are fine * and do not need to change it. */ timeout = sockets[sock_id].in_timeout; if (timeout > tcp->tcp_rto) { sockets[sock_id].in_timeout = tcp->tcp_rto; changed = B_TRUE; } retry: if (sockets[sock_id].inq == NULL) { /* Go out and check the wire */ for (i = MEDIA_LVL; i < TRANSPORT_LVL; i++) { if (sockets[sock_id].input[i] != NULL) { if (sockets[sock_id].input[i](sock_id) < 0) { if (changed) { sockets[sock_id].in_timeout = timeout; } return (-1); } } } } while ((in_gram = sockets[sock_id].inq) != NULL) { if (tcp->tcp_state == state) break; /* Remove unknown inetgrams from the head of inq. */ if (in_gram->igm_level != TRANSPORT_LVL) { #ifdef DEBUG printf("tcp_state_wait for state %d: unexpected " "packet level %d frame found\n", state, in_gram->igm_level); #endif del_gram(&sockets[sock_id].inq, in_gram, B_TRUE); continue; } mp = in_gram->igm_mp; del_gram(&sockets[sock_id].inq, in_gram, B_FALSE); bkmem_free((caddr_t)in_gram, sizeof (struct inetgram)); tcp_rput_data(tcp, mp, sock_id); /* * The other side may have closed this connection or * RST us. But we need to continue to process other * packets in the socket's queue because they may be * belong to another TCP connections. */ if (sockets[sock_id].pcb == NULL) { tcp = NULL; } } /* If the other side has closed the connection, just return. */ if (tcp == NULL || sockets[sock_id].pcb == NULL) { #ifdef DEBUG printf("tcp_state_wait other side dead: state %d " "error %d\n", state, sockets[sock_id].so_error); #endif if (sockets[sock_id].so_error != 0) return (-1); else return (0); } /* * TCPS_ALL_ACKED is not a valid TCP state, it is just used as an * indicator to tcp_state_wait to mean that it is being called * to wait till we have received acks for all the new segments sent. */ if ((state == TCPS_ALL_ACKED) && (tcp->tcp_suna == tcp->tcp_snxt)) { goto done; } if (tcp->tcp_state != state) { if (prom_gettime() > tcp->tcp_rto_timeout) tcp_timer(tcp, sock_id); goto retry; } done: if (changed) sockets[sock_id].in_timeout = timeout; tcp_drain_needed(sock_id, tcp); return (0); } /* Verify the checksum of a segment. */ static int tcp_verify_cksum(mblk_t *mp) { struct ip *iph; tcpha_t *tcph; int len; uint16_t old_sum; iph = (struct ip *)mp->b_rptr; tcph = (tcpha_t *)(iph + 1); len = ntohs(iph->ip_len); /* * Calculate the TCP checksum. Need to include the psuedo header, * which is similar to the real IP header starting at the TTL field. */ iph->ip_sum = htons(len - IP_SIMPLE_HDR_LENGTH); old_sum = tcph->tha_sum; tcph->tha_sum = 0; iph->ip_ttl = 0; if (old_sum == tcp_cksum((uint16_t *)&(iph->ip_ttl), len - IP_SIMPLE_HDR_LENGTH + 12)) { return (0); } else { tcp_cksum_errors++; return (-1); } } /* To find a TCP connection matching the incoming segment. */ static tcp_t * tcp_lookup_ipv4(struct ip *iph, tcpha_t *tcph, int min_state, int *sock_id) { int i; tcp_t *tcp; for (i = 0; i < MAXSOCKET; i++) { if (sockets[i].type == INETBOOT_STREAM && (tcp = (tcp_t *)sockets[i].pcb) != NULL) { if (tcph->tha_lport == tcp->tcp_fport && tcph->tha_fport == tcp->tcp_lport && iph->ip_src.s_addr == tcp->tcp_remote && iph->ip_dst.s_addr == tcp->tcp_bound_source && tcp->tcp_state >= min_state) { *sock_id = i; return (tcp); } } } /* Find it in the time wait list. */ for (tcp = tcp_time_wait_head; tcp != NULL; tcp = tcp->tcp_time_wait_next) { if (tcph->tha_lport == tcp->tcp_fport && tcph->tha_fport == tcp->tcp_lport && iph->ip_src.s_addr == tcp->tcp_remote && iph->ip_dst.s_addr == tcp->tcp_bound_source && tcp->tcp_state >= min_state) { *sock_id = -1; return (tcp); } } return (NULL); } /* To find a TCP listening connection matching the incoming segment. */ static tcp_t * tcp_lookup_listener_ipv4(in_addr_t addr, in_port_t port, int *sock_id) { int i; tcp_t *tcp; for (i = 0; i < MAXSOCKET; i++) { if (sockets[i].type == INETBOOT_STREAM && (tcp = (tcp_t *)sockets[i].pcb) != NULL) { if (tcp->tcp_lport == port && (tcp->tcp_bound_source == addr || tcp->tcp_bound_source == INADDR_ANY)) { *sock_id = i; return (tcp); } } } return (NULL); } /* To find a TCP eager matching the incoming segment. */ static tcp_t * tcp_lookup_eager_ipv4(tcp_t *listener, struct ip *iph, tcpha_t *tcph) { tcp_t *tcp; #ifdef DEBUG printf("tcp_lookup_eager_ipv4 ###############\n"); #endif for (tcp = listener->tcp_eager_next_q; tcp != NULL; tcp = tcp->tcp_eager_next_q) { if (tcph->tha_lport == tcp->tcp_fport && tcph->tha_fport == tcp->tcp_lport && iph->ip_src.s_addr == tcp->tcp_remote && iph->ip_dst.s_addr == tcp->tcp_bound_source) { return (tcp); } } for (tcp = listener->tcp_eager_next_q0; tcp != listener; tcp = tcp->tcp_eager_next_q0) { if (tcph->tha_lport == tcp->tcp_fport && tcph->tha_fport == tcp->tcp_lport && iph->ip_src.s_addr == tcp->tcp_remote && iph->ip_dst.s_addr == tcp->tcp_bound_source) { return (tcp); } } #ifdef DEBUG printf("No eager found\n"); #endif return (NULL); } /* To destroy a TCP control block. */ static void tcp_clean_death(int sock_id, tcp_t *tcp, int err) { tcp_free(tcp); if (tcp->tcp_state == TCPS_TIME_WAIT) tcp_time_wait_remove(tcp); if (sock_id >= 0) { sockets[sock_id].pcb = NULL; if (err != 0) sockets[sock_id].so_error = err; } bkmem_free((caddr_t)tcp, sizeof (tcp_t)); } /* * tcp_rwnd_set() is called to adjust the receive window to a desired value. * We do not allow the receive window to shrink. After setting rwnd, * set the flow control hiwat of the stream. * * This function is called in 2 cases: * * 1) Before data transfer begins, in tcp_accept_comm() for accepting a * connection (passive open) and in tcp_rput_data() for active connect. * This is called after tcp_mss_set() when the desired MSS value is known. * This makes sure that our window size is a mutiple of the other side's * MSS. * 2) Handling SO_RCVBUF option. * * It is ASSUMED that the requested size is a multiple of the current MSS. * * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the * user requests so. */ static int tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd) { uint32_t mss = tcp->tcp_mss; uint32_t old_max_rwnd; uint32_t max_transmittable_rwnd; if (tcp->tcp_rwnd_max != 0) old_max_rwnd = tcp->tcp_rwnd_max; else old_max_rwnd = tcp->tcp_rwnd; /* * Insist on a receive window that is at least * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid * funny TCP interactions of Nagle algorithm, SWS avoidance * and delayed acknowledgement. */ rwnd = MAX(rwnd, tcp_recv_hiwat_minmss * mss); /* * If window size info has already been exchanged, TCP should not * shrink the window. Shrinking window is doable if done carefully. * We may add that support later. But so far there is not a real * need to do that. */ if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) { /* MSS may have changed, do a round up again. */ rwnd = MSS_ROUNDUP(old_max_rwnd, mss); } /* * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check * can be applied even before the window scale option is decided. */ max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws; if (rwnd > max_transmittable_rwnd) { rwnd = max_transmittable_rwnd - (max_transmittable_rwnd % mss); if (rwnd < mss) rwnd = max_transmittable_rwnd; /* * If we're over the limit we may have to back down tcp_rwnd. * The increment below won't work for us. So we set all three * here and the increment below will have no effect. */ tcp->tcp_rwnd = old_max_rwnd = rwnd; } /* * Increment the current rwnd by the amount the maximum grew (we * can not overwrite it since we might be in the middle of a * connection.) */ tcp->tcp_rwnd += rwnd - old_max_rwnd; U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win); if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max) tcp->tcp_cwnd_max = rwnd; tcp->tcp_rwnd_max = rwnd; return (rwnd); } /* * Extract option values from a tcp header. We put any found values into the * tcpopt struct and return a bitmask saying which options were found. */ static int tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt) { uchar_t *endp; int len; uint32_t mss; uchar_t *up = (uchar_t *)tcph; int found = 0; int32_t sack_len; tcp_seq sack_begin, sack_end; tcp_t *tcp; endp = up + TCP_HDR_LENGTH(tcph); up += TCP_MIN_HEADER_LENGTH; while (up < endp) { len = endp - up; switch (*up) { case TCPOPT_EOL: break; case TCPOPT_NOP: up++; continue; case TCPOPT_MAXSEG: if (len < TCPOPT_MAXSEG_LEN || up[1] != TCPOPT_MAXSEG_LEN) break; mss = BE16_TO_U16(up+2); /* Caller must handle tcp_mss_min and tcp_mss_max_* */ tcpopt->tcp_opt_mss = mss; found |= TCP_OPT_MSS_PRESENT; up += TCPOPT_MAXSEG_LEN; continue; case TCPOPT_WSCALE: if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN) break; if (up[2] > TCP_MAX_WINSHIFT) tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT; else tcpopt->tcp_opt_wscale = up[2]; found |= TCP_OPT_WSCALE_PRESENT; up += TCPOPT_WS_LEN; continue; case TCPOPT_SACK_PERMITTED: if (len < TCPOPT_SACK_OK_LEN || up[1] != TCPOPT_SACK_OK_LEN) break; found |= TCP_OPT_SACK_OK_PRESENT; up += TCPOPT_SACK_OK_LEN; continue; case TCPOPT_SACK: if (len <= 2 || up[1] <= 2 || len < up[1]) break; /* If TCP is not interested in SACK blks... */ if ((tcp = tcpopt->tcp) == NULL) { up += up[1]; continue; } sack_len = up[1] - TCPOPT_HEADER_LEN; up += TCPOPT_HEADER_LEN; /* * If the list is empty, allocate one and assume * nothing is sack'ed. */ assert(tcp->tcp_sack_info != NULL); if (tcp->tcp_notsack_list == NULL) { tcp_notsack_update(&(tcp->tcp_notsack_list), tcp->tcp_suna, tcp->tcp_snxt, &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list)); /* * Make sure tcp_notsack_list is not NULL. * This happens when kmem_alloc(KM_NOSLEEP) * returns NULL. */ if (tcp->tcp_notsack_list == NULL) { up += sack_len; continue; } tcp->tcp_fack = tcp->tcp_suna; } while (sack_len > 0) { if (up + 8 > endp) { up = endp; break; } sack_begin = BE32_TO_U32(up); up += 4; sack_end = BE32_TO_U32(up); up += 4; sack_len -= 8; /* * Bounds checking. Make sure the SACK * info is within tcp_suna and tcp_snxt. * If this SACK blk is out of bound, ignore * it but continue to parse the following * blks. */ if (SEQ_LEQ(sack_end, sack_begin) || SEQ_LT(sack_begin, tcp->tcp_suna) || SEQ_GT(sack_end, tcp->tcp_snxt)) { continue; } tcp_notsack_insert(&(tcp->tcp_notsack_list), sack_begin, sack_end, &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list)); if (SEQ_GT(sack_end, tcp->tcp_fack)) { tcp->tcp_fack = sack_end; } } found |= TCP_OPT_SACK_PRESENT; continue; case TCPOPT_TSTAMP: if (len < TCPOPT_TSTAMP_LEN || up[1] != TCPOPT_TSTAMP_LEN) break; tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2); tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6); found |= TCP_OPT_TSTAMP_PRESENT; up += TCPOPT_TSTAMP_LEN; continue; default: if (len <= 1 || len < (int)up[1] || up[1] == 0) break; up += up[1]; continue; } break; } return (found); } /* * Set the mss associated with a particular tcp based on its current value, * and a new one passed in. Observe minimums and maximums, and reset * other state variables that we want to view as multiples of mss. * * This function is called in various places mainly because * 1) Various stuffs, tcp_mss, tcp_cwnd, ... need to be adjusted when the * other side's SYN/SYN-ACK packet arrives. * 2) PMTUd may get us a new MSS. * 3) If the other side stops sending us timestamp option, we need to * increase the MSS size to use the extra bytes available. */ static void tcp_mss_set(tcp_t *tcp, uint32_t mss) { uint32_t mss_max; mss_max = tcp_mss_max_ipv4; if (mss < tcp_mss_min) mss = tcp_mss_min; if (mss > mss_max) mss = mss_max; /* * Unless naglim has been set by our client to * a non-mss value, force naglim to track mss. * This can help to aggregate small writes. */ if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim) tcp->tcp_naglim = mss; /* * TCP should be able to buffer at least 4 MSS data for obvious * performance reason. */ if ((mss << 2) > tcp->tcp_xmit_hiwater) tcp->tcp_xmit_hiwater = mss << 2; tcp->tcp_mss = mss; /* * Initialize cwnd according to draft-floyd-incr-init-win-01.txt. * Previously, we use tcp_slow_start_initial to control the size * of the initial cwnd. Now, when tcp_slow_start_initial * mss * is smaller than the cwnd calculated from the formula suggested in * the draft, we use tcp_slow_start_initial * mss as the cwnd. * Otherwise, use the cwnd from the draft's formula. The default * of tcp_slow_start_initial is 2. */ tcp->tcp_cwnd = MIN(tcp_slow_start_initial * mss, MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss))); tcp->tcp_cwnd_cnt = 0; } /* * Process all TCP option in SYN segment. * * This function sets up the correct tcp_mss value according to the * MSS option value and our header size. It also sets up the window scale * and timestamp values, and initialize SACK info blocks. But it does not * change receive window size after setting the tcp_mss value. The caller * should do the appropriate change. */ void tcp_process_options(tcp_t *tcp, tcph_t *tcph) { int options; tcp_opt_t tcpopt; uint32_t mss_max; char *tmp_tcph; tcpopt.tcp = NULL; options = tcp_parse_options(tcph, &tcpopt); /* * Process MSS option. Note that MSS option value does not account * for IP or TCP options. This means that it is equal to MTU - minimum * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for * IPv6. */ if (!(options & TCP_OPT_MSS_PRESENT)) { tcpopt.tcp_opt_mss = tcp_mss_def_ipv4; } else { if (tcp->tcp_ipversion == IPV4_VERSION) mss_max = tcp_mss_max_ipv4; if (tcpopt.tcp_opt_mss < tcp_mss_min) tcpopt.tcp_opt_mss = tcp_mss_min; else if (tcpopt.tcp_opt_mss > mss_max) tcpopt.tcp_opt_mss = mss_max; } /* Process Window Scale option. */ if (options & TCP_OPT_WSCALE_PRESENT) { tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale; tcp->tcp_snd_ws_ok = B_TRUE; } else { tcp->tcp_snd_ws = B_FALSE; tcp->tcp_snd_ws_ok = B_FALSE; tcp->tcp_rcv_ws = B_FALSE; } /* Process Timestamp option. */ if ((options & TCP_OPT_TSTAMP_PRESENT) && (tcp->tcp_snd_ts_ok || !tcp->tcp_active_open)) { tmp_tcph = (char *)tcp->tcp_tcph; tcp->tcp_snd_ts_ok = B_TRUE; tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val; tcp->tcp_last_rcv_lbolt = prom_gettime(); assert(OK_32PTR(tmp_tcph)); assert(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH); /* Fill in our template header with basic timestamp option. */ tmp_tcph += tcp->tcp_tcp_hdr_len; tmp_tcph[0] = TCPOPT_NOP; tmp_tcph[1] = TCPOPT_NOP; tmp_tcph[2] = TCPOPT_TSTAMP; tmp_tcph[3] = TCPOPT_TSTAMP_LEN; tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN; tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN; tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4); } else { tcp->tcp_snd_ts_ok = B_FALSE; } /* * Process SACK options. If SACK is enabled for this connection, * then allocate the SACK info structure. */ if ((options & TCP_OPT_SACK_OK_PRESENT) && (tcp->tcp_snd_sack_ok || (tcp_sack_permitted != 0 && !tcp->tcp_active_open))) { /* This should be true only in the passive case. */ if (tcp->tcp_sack_info == NULL) { tcp->tcp_sack_info = (tcp_sack_info_t *)bkmem_zalloc( sizeof (tcp_sack_info_t)); } if (tcp->tcp_sack_info == NULL) { tcp->tcp_snd_sack_ok = B_FALSE; } else { tcp->tcp_snd_sack_ok = B_TRUE; if (tcp->tcp_snd_ts_ok) { tcp->tcp_max_sack_blk = 3; } else { tcp->tcp_max_sack_blk = 4; } } } else { /* * Resetting tcp_snd_sack_ok to B_FALSE so that * no SACK info will be used for this * connection. This assumes that SACK usage * permission is negotiated. This may need * to be changed once this is clarified. */ if (tcp->tcp_sack_info != NULL) { bkmem_free((caddr_t)tcp->tcp_sack_info, sizeof (tcp_sack_info_t)); tcp->tcp_sack_info = NULL; } tcp->tcp_snd_sack_ok = B_FALSE; } /* * Now we know the exact TCP/IP header length, subtract * that from tcp_mss to get our side's MSS. */ tcp->tcp_mss -= tcp->tcp_hdr_len; /* * Here we assume that the other side's header size will be equal to * our header size. We calculate the real MSS accordingly. Need to * take into additional stuffs IPsec puts in. * * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header) */ tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len - (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH); /* * Set MSS to the smaller one of both ends of the connection. * We should not have called tcp_mss_set() before, but our * side of the MSS should have been set to a proper value * by tcp_adapt_ire(). tcp_mss_set() will also set up the * STREAM head parameters properly. * * If we have a larger-than-16-bit window but the other side * didn't want to do window scale, tcp_rwnd_set() will take * care of that. */ tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss)); } /* * This function does PAWS protection check. Returns B_TRUE if the * segment passes the PAWS test, else returns B_FALSE. */ boolean_t tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp) { uint8_t flags; int options; uint8_t *up; flags = (unsigned int)tcph->th_flags[0] & 0xFF; /* * If timestamp option is aligned nicely, get values inline, * otherwise call general routine to parse. Only do that * if timestamp is the only option. */ if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH + TCPOPT_REAL_TS_LEN && OK_32PTR((up = ((uint8_t *)tcph) + TCP_MIN_HEADER_LENGTH)) && *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) { tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4)); tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8)); options = TCP_OPT_TSTAMP_PRESENT; } else { if (tcp->tcp_snd_sack_ok) { tcpoptp->tcp = tcp; } else { tcpoptp->tcp = NULL; } options = tcp_parse_options(tcph, tcpoptp); } if (options & TCP_OPT_TSTAMP_PRESENT) { /* * Do PAWS per RFC 1323 section 4.2. Accept RST * regardless of the timestamp, page 18 RFC 1323.bis. */ if ((flags & TH_RST) == 0 && TSTMP_LT(tcpoptp->tcp_opt_ts_val, tcp->tcp_ts_recent)) { if (TSTMP_LT(prom_gettime(), tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) { /* This segment is not acceptable. */ return (B_FALSE); } else { /* * Connection has been idle for * too long. Reset the timestamp * and assume the segment is valid. */ tcp->tcp_ts_recent = tcpoptp->tcp_opt_ts_val; } } } else { /* * If we don't get a timestamp on every packet, we * figure we can't really trust 'em, so we stop sending * and parsing them. */ tcp->tcp_snd_ts_ok = B_FALSE; tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN; tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN; tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4); tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN); if (tcp->tcp_snd_sack_ok) { assert(tcp->tcp_sack_info != NULL); tcp->tcp_max_sack_blk = 4; } } return (B_TRUE); } /* * tcp_get_seg_mp() is called to get the pointer to a segment in the * send queue which starts at the given seq. no. * * Parameters: * tcp_t *tcp: the tcp instance pointer. * uint32_t seq: the starting seq. no of the requested segment. * int32_t *off: after the execution, *off will be the offset to * the returned mblk which points to the requested seq no. * * Return: * A mblk_t pointer pointing to the requested segment in send queue. */ static mblk_t * tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off) { int32_t cnt; mblk_t *mp; /* Defensive coding. Make sure we don't send incorrect data. */ if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt) || off == NULL) { return (NULL); } cnt = seq - tcp->tcp_suna; mp = tcp->tcp_xmit_head; while (cnt > 0 && mp) { cnt -= mp->b_wptr - mp->b_rptr; if (cnt < 0) { cnt += mp->b_wptr - mp->b_rptr; break; } mp = mp->b_cont; } assert(mp != NULL); *off = cnt; return (mp); } /* * This function handles all retransmissions if SACK is enabled for this * connection. First it calculates how many segments can be retransmitted * based on tcp_pipe. Then it goes thru the notsack list to find eligible * segments. A segment is eligible if sack_cnt for that segment is greater * than or equal tcp_dupack_fast_retransmit. After it has retransmitted * all eligible segments, it checks to see if TCP can send some new segments * (fast recovery). If it can, it returns 1. Otherwise it returns 0. * * Parameters: * tcp_t *tcp: the tcp structure of the connection. * * Return: * 1 if the pipe is not full (new data can be sent), 0 otherwise */ static int32_t tcp_sack_rxmit(tcp_t *tcp, int sock_id) { notsack_blk_t *notsack_blk; int32_t usable_swnd; int32_t mss; uint32_t seg_len; mblk_t *xmit_mp; assert(tcp->tcp_sack_info != NULL); assert(tcp->tcp_notsack_list != NULL); assert(tcp->tcp_rexmit == B_FALSE); /* Defensive coding in case there is a bug... */ if (tcp->tcp_notsack_list == NULL) { return (0); } notsack_blk = tcp->tcp_notsack_list; mss = tcp->tcp_mss; /* * Limit the num of outstanding data in the network to be * tcp_cwnd_ssthresh, which is half of the original congestion wnd. */ usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe; /* At least retransmit 1 MSS of data. */ if (usable_swnd <= 0) { usable_swnd = mss; } /* Make sure no new RTT samples will be taken. */ tcp->tcp_csuna = tcp->tcp_snxt; notsack_blk = tcp->tcp_notsack_list; while (usable_swnd > 0) { mblk_t *snxt_mp, *tmp_mp; tcp_seq begin = tcp->tcp_sack_snxt; tcp_seq end; int32_t off; for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) { if (SEQ_GT(notsack_blk->end, begin) && (notsack_blk->sack_cnt >= tcp_dupack_fast_retransmit)) { end = notsack_blk->end; if (SEQ_LT(begin, notsack_blk->begin)) { begin = notsack_blk->begin; } break; } } /* * All holes are filled. Manipulate tcp_cwnd to send more * if we can. Note that after the SACK recovery, tcp_cwnd is * set to tcp_cwnd_ssthresh. */ if (notsack_blk == NULL) { usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe; if (usable_swnd <= 0) { tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna; assert(tcp->tcp_cwnd > 0); return (0); } else { usable_swnd = usable_swnd / mss; tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna + MAX(usable_swnd * mss, mss); return (1); } } /* * Note that we may send more than usable_swnd allows here * because of round off, but no more than 1 MSS of data. */ seg_len = end - begin; if (seg_len > mss) seg_len = mss; snxt_mp = tcp_get_seg_mp(tcp, begin, &off); assert(snxt_mp != NULL); /* This should not happen. Defensive coding again... */ if (snxt_mp == NULL) { return (0); } xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off, &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE); if (xmit_mp == NULL) return (0); usable_swnd -= seg_len; tcp->tcp_pipe += seg_len; tcp->tcp_sack_snxt = begin + seg_len; TCP_DUMP_PACKET("tcp_sack_rxmit", xmit_mp); (void) ipv4_tcp_output(sock_id, xmit_mp); freeb(xmit_mp); /* * Update the send timestamp to avoid false retransmission. * Note. use uintptr_t to suppress the gcc warning. */ snxt_mp->b_prev = (mblk_t *)(uintptr_t)prom_gettime(); BUMP_MIB(tcp_mib.tcpRetransSegs); UPDATE_MIB(tcp_mib.tcpRetransBytes, seg_len); BUMP_MIB(tcp_mib.tcpOutSackRetransSegs); /* * Update tcp_rexmit_max to extend this SACK recovery phase. * This happens when new data sent during fast recovery is * also lost. If TCP retransmits those new data, it needs * to extend SACK recover phase to avoid starting another * fast retransmit/recovery unnecessarily. */ if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) { tcp->tcp_rexmit_max = tcp->tcp_sack_snxt; } } return (0); } static void tcp_rput_data(tcp_t *tcp, mblk_t *mp, int sock_id) { uchar_t *rptr; struct ip *iph; tcp_t *tcp1; tcpha_t *tcph; uint32_t seg_ack; int seg_len; uint_t ip_hdr_len; uint32_t seg_seq; mblk_t *mp1; uint_t flags; uint32_t new_swnd = 0; int mss; boolean_t ofo_seg = B_FALSE; /* Out of order segment */ int32_t gap; int32_t rgap; tcp_opt_t tcpopt; int32_t bytes_acked; int npkt; uint32_t cwnd; uint32_t add; #ifdef DEBUG printf("tcp_rput_data sock %d mp %x mp_datap %x #################\n", sock_id, mp, mp->b_datap); #endif /* Dump the packet when debugging. */ TCP_DUMP_PACKET("tcp_rput_data", mp); assert(OK_32PTR(mp->b_rptr)); rptr = mp->b_rptr; iph = (struct ip *)rptr; ip_hdr_len = IPH_HDR_LENGTH(rptr); if (ip_hdr_len != IP_SIMPLE_HDR_LENGTH) { #ifdef DEBUG printf("Not simple IP header\n"); #endif /* We cannot handle IP option yet... */ tcp_drops++; freeb(mp); return; } /* The TCP header must be aligned. */ tcph = (tcpha_t *)&rptr[ip_hdr_len]; seg_seq = ntohl(tcph->tha_seq); seg_ack = ntohl(tcph->tha_ack); assert((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX); seg_len = (int)(mp->b_wptr - rptr) - (ip_hdr_len + TCP_HDR_LENGTH(((tcph_t *)tcph))); /* In inetboot, b_cont should always be NULL. */ assert(mp->b_cont == NULL); /* Verify the checksum. */ if (tcp_verify_cksum(mp) < 0) { #ifdef DEBUG printf("tcp_rput_data: wrong cksum\n"); #endif freemsg(mp); return; } /* * This segment is not for us, try to find its * intended receiver. */ if (tcp == NULL || tcph->tha_lport != tcp->tcp_fport || tcph->tha_fport != tcp->tcp_lport || iph->ip_src.s_addr != tcp->tcp_remote || iph->ip_dst.s_addr != tcp->tcp_bound_source) { #ifdef DEBUG printf("tcp_rput_data: not for us, state %d\n", tcp->tcp_state); #endif /* * First try to find a established connection. If none * is found, look for a listener. * * If a listener is found, we need to check to see if the * incoming segment is for one of its eagers. If it is, * give it to the eager. If not, listener should take care * of it. */ if ((tcp1 = tcp_lookup_ipv4(iph, tcph, TCPS_SYN_SENT, &sock_id)) != NULL || (tcp1 = tcp_lookup_listener_ipv4(iph->ip_dst.s_addr, tcph->tha_fport, &sock_id)) != NULL) { if (tcp1->tcp_state == TCPS_LISTEN) { if ((tcp = tcp_lookup_eager_ipv4(tcp1, iph, tcph)) == NULL) { /* No eager... sent to listener */ #ifdef DEBUG printf("found the listener: %s\n", tcp_display(tcp1, NULL, DISP_ADDR_AND_PORT)); #endif tcp = tcp1; } #ifdef DEBUG else { printf("found the eager: %s\n", tcp_display(tcp, NULL, DISP_ADDR_AND_PORT)); } #endif } else { /* Non listener found... */ #ifdef DEBUG printf("found the connection: %s\n", tcp_display(tcp1, NULL, DISP_ADDR_AND_PORT)); #endif tcp = tcp1; } } else { /* * No connection for this segment... * Send a RST to the other side. */ tcp_xmit_listeners_reset(sock_id, mp, ip_hdr_len); return; } } flags = tcph->tha_flags & 0xFF; BUMP_MIB(tcp_mib.tcpInSegs); if (tcp->tcp_state == TCPS_TIME_WAIT) { tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack, seg_len, (tcph_t *)tcph, sock_id); return; } /* * From this point we can assume that the tcp is not compressed, * since we would have branched off to tcp_time_wait_processing() * in such a case. */ assert(tcp != NULL && tcp->tcp_state != TCPS_TIME_WAIT); /* * After this point, we know we have the correct TCP, so update * the receive time. */ tcp->tcp_last_recv_time = prom_gettime(); /* In inetboot, we do not handle urgent pointer... */ if (flags & TH_URG) { freemsg(mp); DEBUG_1("tcp_rput_data(%d): received segment with urgent " "pointer\n", sock_id); tcp_drops++; return; } switch (tcp->tcp_state) { case TCPS_LISTEN: if ((flags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) { if (flags & TH_RST) { freemsg(mp); return; } if (flags & TH_ACK) { tcp_xmit_early_reset("TCPS_LISTEN-TH_ACK", sock_id, mp, seg_ack, 0, TH_RST, ip_hdr_len); return; } if (!(flags & TH_SYN)) { freemsg(mp); return; } printf("tcp_rput_data: %d\n", __LINE__); prom_panic("inetboot"); } if (tcp->tcp_conn_req_max > 0) { tcp = tcp_conn_request(tcp, mp, sock_id, ip_hdr_len); if (tcp == NULL) { freemsg(mp); return; } #ifdef DEBUG printf("tcp_rput_data: new tcp created\n"); #endif } tcp->tcp_irs = seg_seq; tcp->tcp_rack = seg_seq; tcp->tcp_rnxt = seg_seq + 1; U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack); BUMP_MIB(tcp_mib.tcpPassiveOpens); goto syn_rcvd; case TCPS_SYN_SENT: if (flags & TH_ACK) { /* * Note that our stack cannot send data before a * connection is established, therefore the * following check is valid. Otherwise, it has * to be changed. */ if (SEQ_LEQ(seg_ack, tcp->tcp_iss) || SEQ_GT(seg_ack, tcp->tcp_snxt)) { if (flags & TH_RST) { freemsg(mp); return; } tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq", tcp, mp, seg_ack, 0, TH_RST, ip_hdr_len, sock_id); return; } assert(tcp->tcp_suna + 1 == seg_ack); } if (flags & TH_RST) { freemsg(mp); if (flags & TH_ACK) { tcp_clean_death(sock_id, tcp, ECONNREFUSED); } return; } if (!(flags & TH_SYN)) { freemsg(mp); return; } /* Process all TCP options. */ tcp_process_options(tcp, (tcph_t *)tcph); /* * The following changes our rwnd to be a multiple of the * MIN(peer MSS, our MSS) for performance reason. */ (void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rwnd, tcp->tcp_mss)); /* Is the other end ECN capable? */ if (tcp->tcp_ecn_ok) { if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) { tcp->tcp_ecn_ok = B_FALSE; } } /* * Clear ECN flags because it may interfere with later * processing. */ flags &= ~(TH_ECE|TH_CWR); tcp->tcp_irs = seg_seq; tcp->tcp_rack = seg_seq; tcp->tcp_rnxt = seg_seq + 1; U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack); if (flags & TH_ACK) { /* One for the SYN */ tcp->tcp_suna = tcp->tcp_iss + 1; tcp->tcp_valid_bits &= ~TCP_ISS_VALID; tcp->tcp_state = TCPS_ESTABLISHED; /* * If SYN was retransmitted, need to reset all * retransmission info. This is because this * segment will be treated as a dup ACK. */ if (tcp->tcp_rexmit) { tcp->tcp_rexmit = B_FALSE; tcp->tcp_rexmit_nxt = tcp->tcp_snxt; tcp->tcp_rexmit_max = tcp->tcp_snxt; tcp->tcp_snd_burst = TCP_CWND_NORMAL; /* * Set tcp_cwnd back to 1 MSS, per * recommendation from * draft-floyd-incr-init-win-01.txt, * Increasing TCP's Initial Window. */ tcp->tcp_cwnd = tcp->tcp_mss; } tcp->tcp_swl1 = seg_seq; tcp->tcp_swl2 = seg_ack; new_swnd = BE16_TO_U16(((tcph_t *)tcph)->th_win); tcp->tcp_swnd = new_swnd; if (new_swnd > tcp->tcp_max_swnd) tcp->tcp_max_swnd = new_swnd; /* * Always send the three-way handshake ack immediately * in order to make the connection complete as soon as * possible on the accepting host. */ flags |= TH_ACK_NEEDED; /* * Check to see if there is data to be sent. If * yes, set the transmit flag. Then check to see * if received data processing needs to be done. * If not, go straight to xmit_check. This short * cut is OK as we don't support T/TCP. */ if (tcp->tcp_unsent) flags |= TH_XMIT_NEEDED; if (seg_len == 0) { freemsg(mp); goto xmit_check; } flags &= ~TH_SYN; seg_seq++; break; } syn_rcvd: tcp->tcp_state = TCPS_SYN_RCVD; mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss, NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE); if (mp1 != NULL) { TCP_DUMP_PACKET("tcp_rput_data replying SYN", mp1); (void) ipv4_tcp_output(sock_id, mp1); TCP_TIMER_RESTART(tcp, tcp->tcp_rto); freeb(mp1); /* * Let's wait till our SYN has been ACKED since we * don't have a timer. */ if (tcp_state_wait(sock_id, tcp, TCPS_ALL_ACKED) < 0) { freemsg(mp); return; } } freemsg(mp); return; default: break; } mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH((tcph_t *)tcph); new_swnd = ntohs(tcph->tha_win) << ((flags & TH_SYN) ? 0 : tcp->tcp_snd_ws); mss = tcp->tcp_mss; if (tcp->tcp_snd_ts_ok) { if (!tcp_paws_check(tcp, (tcph_t *)tcph, &tcpopt)) { /* * This segment is not acceptable. * Drop it and send back an ACK. */ freemsg(mp); flags |= TH_ACK_NEEDED; goto ack_check; } } else if (tcp->tcp_snd_sack_ok) { assert(tcp->tcp_sack_info != NULL); tcpopt.tcp = tcp; /* * SACK info in already updated in tcp_parse_options. Ignore * all other TCP options... */ (void) tcp_parse_options((tcph_t *)tcph, &tcpopt); } try_again:; gap = seg_seq - tcp->tcp_rnxt; rgap = tcp->tcp_rwnd - (gap + seg_len); /* * gap is the amount of sequence space between what we expect to see * and what we got for seg_seq. A positive value for gap means * something got lost. A negative value means we got some old stuff. */ if (gap < 0) { /* Old stuff present. Is the SYN in there? */ if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) && (seg_len != 0)) { flags &= ~TH_SYN; seg_seq++; /* Recompute the gaps after noting the SYN. */ goto try_again; } BUMP_MIB(tcp_mib.tcpInDataDupSegs); UPDATE_MIB(tcp_mib.tcpInDataDupBytes, (seg_len > -gap ? -gap : seg_len)); /* Remove the old stuff from seg_len. */ seg_len += gap; /* * Anything left? * Make sure to check for unack'd FIN when rest of data * has been previously ack'd. */ if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) { /* * Resets are only valid if they lie within our offered * window. If the RST bit is set, we just ignore this * segment. */ if (flags & TH_RST) { freemsg(mp); return; } /* * This segment is "unacceptable". None of its * sequence space lies within our advertized window. * * Adjust seg_len to the original value for tracing. */ seg_len -= gap; #ifdef DEBUG printf("tcp_rput: unacceptable, gap %d, rgap " "%d, flags 0x%x, seg_seq %u, seg_ack %u, " "seg_len %d, rnxt %u, snxt %u, %s", gap, rgap, flags, seg_seq, seg_ack, seg_len, tcp->tcp_rnxt, tcp->tcp_snxt, tcp_display(tcp, NULL, DISP_ADDR_AND_PORT)); #endif /* * Arrange to send an ACK in response to the * unacceptable segment per RFC 793 page 69. There * is only one small difference between ours and the * acceptability test in the RFC - we accept ACK-only * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK * will be generated. * * Note that we have to ACK an ACK-only packet at least * for stacks that send 0-length keep-alives with * SEG.SEQ = SND.NXT-1 as recommended by RFC1122, * section 4.2.3.6. As long as we don't ever generate * an unacceptable packet in response to an incoming * packet that is unacceptable, it should not cause * "ACK wars". */ flags |= TH_ACK_NEEDED; /* * Continue processing this segment in order to use the * ACK information it contains, but skip all other * sequence-number processing. Processing the ACK * information is necessary in order to * re-synchronize connections that may have lost * synchronization. * * We clear seg_len and flag fields related to * sequence number processing as they are not * to be trusted for an unacceptable segment. */ seg_len = 0; flags &= ~(TH_SYN | TH_FIN | TH_URG); goto process_ack; } /* Fix seg_seq, and chew the gap off the front. */ seg_seq = tcp->tcp_rnxt; do { mblk_t *mp2; assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)UINT_MAX); gap += (uint_t)(mp->b_wptr - mp->b_rptr); if (gap > 0) { mp->b_rptr = mp->b_wptr - gap; break; } mp2 = mp; mp = mp->b_cont; freeb(mp2); } while (gap < 0); } /* * rgap is the amount of stuff received out of window. A negative * value is the amount out of window. */ if (rgap < 0) { mblk_t *mp2; if (tcp->tcp_rwnd == 0) BUMP_MIB(tcp_mib.tcpInWinProbe); else { BUMP_MIB(tcp_mib.tcpInDataPastWinSegs); UPDATE_MIB(tcp_mib.tcpInDataPastWinBytes, -rgap); } /* * seg_len does not include the FIN, so if more than * just the FIN is out of window, we act like we don't * see it. (If just the FIN is out of window, rgap * will be zero and we will go ahead and acknowledge * the FIN.) */ flags &= ~TH_FIN; /* Fix seg_len and make sure there is something left. */ seg_len += rgap; if (seg_len <= 0) { /* * Resets are only valid if they lie within our offered * window. If the RST bit is set, we just ignore this * segment. */ if (flags & TH_RST) { freemsg(mp); return; } /* Per RFC 793, we need to send back an ACK. */ flags |= TH_ACK_NEEDED; /* * If this is a zero window probe, continue to * process the ACK part. But we need to set seg_len * to 0 to avoid data processing. Otherwise just * drop the segment and send back an ACK. */ if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) { flags &= ~(TH_SYN | TH_URG); seg_len = 0; /* Let's see if we can update our rwnd */ tcp_rcv_drain(sock_id, tcp); goto process_ack; } else { freemsg(mp); goto ack_check; } } /* Pitch out of window stuff off the end. */ rgap = seg_len; mp2 = mp; do { assert((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <= (uintptr_t)INT_MAX); rgap -= (int)(mp2->b_wptr - mp2->b_rptr); if (rgap < 0) { mp2->b_wptr += rgap; if ((mp1 = mp2->b_cont) != NULL) { mp2->b_cont = NULL; freemsg(mp1); } break; } } while ((mp2 = mp2->b_cont) != NULL); } ok:; /* * TCP should check ECN info for segments inside the window only. * Therefore the check should be done here. */ if (tcp->tcp_ecn_ok) { uchar_t tos = ((struct ip *)rptr)->ip_tos; if (flags & TH_CWR) { tcp->tcp_ecn_echo_on = B_FALSE; } /* * Note that both ECN_CE and CWR can be set in the * same segment. In this case, we once again turn * on ECN_ECHO. */ if ((tos & IPH_ECN_CE) == IPH_ECN_CE) { tcp->tcp_ecn_echo_on = B_TRUE; } } /* * Check whether we can update tcp_ts_recent. This test is * NOT the one in RFC 1323 3.4. It is from Braden, 1993, "TCP * Extensions for High Performance: An Update", Internet Draft. */ if (tcp->tcp_snd_ts_ok && TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) && SEQ_LEQ(seg_seq, tcp->tcp_rack)) { tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val; tcp->tcp_last_rcv_lbolt = prom_gettime(); } if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) { /* * FIN in an out of order segment. We record this in * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq. * Clear the FIN so that any check on FIN flag will fail. * Remember that FIN also counts in the sequence number * space. So we need to ack out of order FIN only segments. */ if (flags & TH_FIN) { tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID; tcp->tcp_ofo_fin_seq = seg_seq + seg_len; flags &= ~TH_FIN; flags |= TH_ACK_NEEDED; } if (seg_len > 0) { /* Fill in the SACK blk list. */ if (tcp->tcp_snd_sack_ok) { assert(tcp->tcp_sack_info != NULL); tcp_sack_insert(tcp->tcp_sack_list, seg_seq, seg_seq + seg_len, &(tcp->tcp_num_sack_blk)); } /* * Attempt reassembly and see if we have something * ready to go. */ mp = tcp_reass(tcp, mp, seg_seq); /* Always ack out of order packets */ flags |= TH_ACK_NEEDED | TH_PUSH; if (mp != NULL) { assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX); seg_len = mp->b_cont ? msgdsize(mp) : (int)(mp->b_wptr - mp->b_rptr); seg_seq = tcp->tcp_rnxt; /* * A gap is filled and the seq num and len * of the gap match that of a previously * received FIN, put the FIN flag back in. */ if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) && seg_seq + seg_len == tcp->tcp_ofo_fin_seq) { flags |= TH_FIN; tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID; } } else { /* * Keep going even with NULL mp. * There may be a useful ACK or something else * we don't want to miss. * * But TCP should not perform fast retransmit * because of the ack number. TCP uses * seg_len == 0 to determine if it is a pure * ACK. And this is not a pure ACK. */ seg_len = 0; ofo_seg = B_TRUE; } } } else if (seg_len > 0) { BUMP_MIB(tcp_mib.tcpInDataInorderSegs); UPDATE_MIB(tcp_mib.tcpInDataInorderBytes, seg_len); /* * If an out of order FIN was received before, and the seq * num and len of the new segment match that of the FIN, * put the FIN flag back in. */ if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) && seg_seq + seg_len == tcp->tcp_ofo_fin_seq) { flags |= TH_FIN; tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID; } } if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) { if (flags & TH_RST) { freemsg(mp); switch (tcp->tcp_state) { case TCPS_SYN_RCVD: (void) tcp_clean_death(sock_id, tcp, ECONNREFUSED); break; case TCPS_ESTABLISHED: case TCPS_FIN_WAIT_1: case TCPS_FIN_WAIT_2: case TCPS_CLOSE_WAIT: (void) tcp_clean_death(sock_id, tcp, ECONNRESET); break; case TCPS_CLOSING: case TCPS_LAST_ACK: (void) tcp_clean_death(sock_id, tcp, 0); break; default: assert(tcp->tcp_state != TCPS_TIME_WAIT); (void) tcp_clean_death(sock_id, tcp, ENXIO); break; } return; } if (flags & TH_SYN) { /* * See RFC 793, Page 71 * * The seq number must be in the window as it should * be "fixed" above. If it is outside window, it should * be already rejected. Note that we allow seg_seq to be * rnxt + rwnd because we want to accept 0 window probe. */ assert(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) && SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd)); freemsg(mp); /* * If the ACK flag is not set, just use our snxt as the * seq number of the RST segment. */ if (!(flags & TH_ACK)) { seg_ack = tcp->tcp_snxt; } tcp_xmit_ctl("TH_SYN", tcp, NULL, seg_ack, seg_seq + 1, TH_RST|TH_ACK, 0, sock_id); assert(tcp->tcp_state != TCPS_TIME_WAIT); (void) tcp_clean_death(sock_id, tcp, ECONNRESET); return; } process_ack: if (!(flags & TH_ACK)) { #ifdef DEBUG printf("No ack in segment, dropped it, seq:%x\n", seg_seq); #endif freemsg(mp); goto xmit_check; } } bytes_acked = (int)(seg_ack - tcp->tcp_suna); if (tcp->tcp_state == TCPS_SYN_RCVD) { tcp_t *listener = tcp->tcp_listener; #ifdef DEBUG printf("Done with eager 3-way handshake\n"); #endif /* * NOTE: RFC 793 pg. 72 says this should be 'bytes_acked < 0' * but that would mean we have an ack that ignored our SYN. */ if (bytes_acked < 1 || SEQ_GT(seg_ack, tcp->tcp_snxt)) { freemsg(mp); tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack", tcp, NULL, seg_ack, 0, TH_RST, 0, sock_id); return; } /* * if the conn_req_q is full defer processing * until space is availabe after accept() * processing */ if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) { tcp_t *tail; listener->tcp_conn_req_cnt_q0--; listener->tcp_conn_req_cnt_q++; /* Move from SYN_RCVD to ESTABLISHED list */ tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = tcp->tcp_eager_prev_q0; tcp->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp->tcp_eager_next_q0; tcp->tcp_eager_prev_q0 = NULL; tcp->tcp_eager_next_q0 = NULL; /* * Insert at end of the queue because sockfs * sends down T_CONN_RES in chronological * order. Leaving the older conn indications * at front of the queue helps reducing search * time. */ tail = listener->tcp_eager_last_q; if (tail != NULL) { tail->tcp_eager_next_q = tcp; } else { listener->tcp_eager_next_q = tcp; } listener->tcp_eager_last_q = tcp; tcp->tcp_eager_next_q = NULL; } else { /* * Defer connection on q0 and set deferred * connection bit true */ tcp->tcp_conn_def_q0 = B_TRUE; /* take tcp out of q0 ... */ tcp->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp->tcp_eager_next_q0; tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = tcp->tcp_eager_prev_q0; /* ... and place it at the end of q0 */ tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0; tcp->tcp_eager_next_q0 = listener; listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp; listener->tcp_eager_prev_q0 = tcp; } tcp->tcp_suna = tcp->tcp_iss + 1; /* One for the SYN */ bytes_acked--; /* * If SYN was retransmitted, need to reset all * retransmission info as this segment will be * treated as a dup ACK. */ if (tcp->tcp_rexmit) { tcp->tcp_rexmit = B_FALSE; tcp->tcp_rexmit_nxt = tcp->tcp_snxt; tcp->tcp_rexmit_max = tcp->tcp_snxt; tcp->tcp_snd_burst = TCP_CWND_NORMAL; tcp->tcp_ms_we_have_waited = 0; tcp->tcp_cwnd = mss; } /* * We set the send window to zero here. * This is needed if there is data to be * processed already on the queue. * Later (at swnd_update label), the * "new_swnd > tcp_swnd" condition is satisfied * the XMIT_NEEDED flag is set in the current * (SYN_RCVD) state. This ensures tcp_wput_data() is * called if there is already data on queue in * this state. */ tcp->tcp_swnd = 0; if (new_swnd > tcp->tcp_max_swnd) tcp->tcp_max_swnd = new_swnd; tcp->tcp_swl1 = seg_seq; tcp->tcp_swl2 = seg_ack; tcp->tcp_state = TCPS_ESTABLISHED; tcp->tcp_valid_bits &= ~TCP_ISS_VALID; } /* This code follows 4.4BSD-Lite2 mostly. */ if (bytes_acked < 0) goto est; /* * If TCP is ECN capable and the congestion experience bit is * set, reduce tcp_cwnd and tcp_ssthresh. But this should only be * done once per window (or more loosely, per RTT). */ if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max)) tcp->tcp_cwr = B_FALSE; if (tcp->tcp_ecn_ok && (flags & TH_ECE)) { if (!tcp->tcp_cwr) { npkt = (MIN(tcp->tcp_cwnd, tcp->tcp_swnd) >> 1) / mss; tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss; tcp->tcp_cwnd = npkt * mss; /* * If the cwnd is 0, use the timer to clock out * new segments. This is required by the ECN spec. */ if (npkt == 0) { TCP_TIMER_RESTART(tcp, tcp->tcp_rto); /* * This makes sure that when the ACK comes * back, we will increase tcp_cwnd by 1 MSS. */ tcp->tcp_cwnd_cnt = 0; } tcp->tcp_cwr = B_TRUE; /* * This marks the end of the current window of in * flight data. That is why we don't use * tcp_suna + tcp_swnd. Only data in flight can * provide ECN info. */ tcp->tcp_cwr_snd_max = tcp->tcp_snxt; tcp->tcp_ecn_cwr_sent = B_FALSE; } } mp1 = tcp->tcp_xmit_head; if (bytes_acked == 0) { if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) { int dupack_cnt; BUMP_MIB(tcp_mib.tcpInDupAck); /* * Fast retransmit. When we have seen exactly three * identical ACKs while we have unacked data * outstanding we take it as a hint that our peer * dropped something. * * If TCP is retransmitting, don't do fast retransmit. */ if (mp1 != NULL && tcp->tcp_suna != tcp->tcp_snxt && ! tcp->tcp_rexmit) { /* Do Limited Transmit */ if ((dupack_cnt = ++tcp->tcp_dupack_cnt) < tcp_dupack_fast_retransmit) { /* * RFC 3042 * * What we need to do is temporarily * increase tcp_cwnd so that new * data can be sent if it is allowed * by the receive window (tcp_rwnd). * tcp_wput_data() will take care of * the rest. * * If the connection is SACK capable, * only do limited xmit when there * is SACK info. * * Note how tcp_cwnd is incremented. * The first dup ACK will increase * it by 1 MSS. The second dup ACK * will increase it by 2 MSS. This * means that only 1 new segment will * be sent for each dup ACK. */ if (tcp->tcp_unsent > 0 && (!tcp->tcp_snd_sack_ok || (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL))) { tcp->tcp_cwnd += mss << (tcp->tcp_dupack_cnt - 1); flags |= TH_LIMIT_XMIT; } } else if (dupack_cnt == tcp_dupack_fast_retransmit) { BUMP_MIB(tcp_mib.tcpOutFastRetrans); /* * If we have reduced tcp_ssthresh * because of ECN, do not reduce it again * unless it is already one window of data * away. After one window of data, tcp_cwr * should then be cleared. Note that * for non ECN capable connection, tcp_cwr * should always be false. * * Adjust cwnd since the duplicate * ack indicates that a packet was * dropped (due to congestion.) */ if (!tcp->tcp_cwr) { npkt = (MIN(tcp->tcp_cwnd, tcp->tcp_swnd) >> 1) / mss; if (npkt < 2) npkt = 2; tcp->tcp_cwnd_ssthresh = npkt * mss; tcp->tcp_cwnd = (npkt + tcp->tcp_dupack_cnt) * mss; } if (tcp->tcp_ecn_ok) { tcp->tcp_cwr = B_TRUE; tcp->tcp_cwr_snd_max = tcp->tcp_snxt; tcp->tcp_ecn_cwr_sent = B_FALSE; } /* * We do Hoe's algorithm. Refer to her * paper "Improving the Start-up Behavior * of a Congestion Control Scheme for TCP," * appeared in SIGCOMM'96. * * Save highest seq no we have sent so far. * Be careful about the invisible FIN byte. */ if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0)) { tcp->tcp_rexmit_max = tcp->tcp_fss; } else { tcp->tcp_rexmit_max = tcp->tcp_snxt; } /* * Do not allow bursty traffic during. * fast recovery. Refer to Fall and Floyd's * paper "Simulation-based Comparisons of * Tahoe, Reno and SACK TCP" (in CCR ??) * This is a best current practise. */ tcp->tcp_snd_burst = TCP_CWND_SS; /* * For SACK: * Calculate tcp_pipe, which is the * estimated number of bytes in * network. * * tcp_fack is the highest sack'ed seq num * TCP has received. * * tcp_pipe is explained in the above quoted * Fall and Floyd's paper. tcp_fack is * explained in Mathis and Mahdavi's * "Forward Acknowledgment: Refining TCP * Congestion Control" in SIGCOMM '96. */ if (tcp->tcp_snd_sack_ok) { assert(tcp->tcp_sack_info != NULL); if (tcp->tcp_notsack_list != NULL) { tcp->tcp_pipe = tcp->tcp_snxt - tcp->tcp_fack; tcp->tcp_sack_snxt = seg_ack; flags |= TH_NEED_SACK_REXMIT; } else { /* * Always initialize tcp_pipe * even though we don't have * any SACK info. If later * we get SACK info and * tcp_pipe is not initialized, * funny things will happen. */ tcp->tcp_pipe = tcp->tcp_cwnd_ssthresh; } } else { flags |= TH_REXMIT_NEEDED; } /* tcp_snd_sack_ok */ } else { /* * Here we perform congestion * avoidance, but NOT slow start. * This is known as the Fast * Recovery Algorithm. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) { flags |= TH_NEED_SACK_REXMIT; tcp->tcp_pipe -= mss; if (tcp->tcp_pipe < 0) tcp->tcp_pipe = 0; } else { /* * We know that one more packet has * left the pipe thus we can update * cwnd. */ cwnd = tcp->tcp_cwnd + mss; if (cwnd > tcp->tcp_cwnd_max) cwnd = tcp->tcp_cwnd_max; tcp->tcp_cwnd = cwnd; flags |= TH_XMIT_NEEDED; } } } } else if (tcp->tcp_zero_win_probe) { /* * If the window has opened, need to arrange * to send additional data. */ if (new_swnd != 0) { /* tcp_suna != tcp_snxt */ /* Packet contains a window update */ BUMP_MIB(tcp_mib.tcpInWinUpdate); tcp->tcp_zero_win_probe = 0; tcp->tcp_timer_backoff = 0; tcp->tcp_ms_we_have_waited = 0; /* * Transmit starting with tcp_suna since * the one byte probe is not ack'ed. * If TCP has sent more than one identical * probe, tcp_rexmit will be set. That means * tcp_ss_rexmit() will send out the one * byte along with new data. Otherwise, * fake the retransmission. */ flags |= TH_XMIT_NEEDED; if (!tcp->tcp_rexmit) { tcp->tcp_rexmit = B_TRUE; tcp->tcp_dupack_cnt = 0; tcp->tcp_rexmit_nxt = tcp->tcp_suna; tcp->tcp_rexmit_max = tcp->tcp_suna + 1; } } } goto swnd_update; } /* * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73. * If the ACK value acks something that we have not yet sent, it might * be an old duplicate segment. Send an ACK to re-synchronize the * other side. * Note: reset in response to unacceptable ACK in SYN_RECEIVE * state is handled above, so we can always just drop the segment and * send an ACK here. * * Should we send ACKs in response to ACK only segments? */ if (SEQ_GT(seg_ack, tcp->tcp_snxt)) { BUMP_MIB(tcp_mib.tcpInAckUnsent); /* drop the received segment */ freemsg(mp); /* Send back an ACK. */ mp = tcp_ack_mp(tcp); if (mp == NULL) { return; } BUMP_MIB(tcp_mib.tcpOutAck); (void) ipv4_tcp_output(sock_id, mp); freeb(mp); return; } /* * TCP gets a new ACK, update the notsack'ed list to delete those * blocks that are covered by this ACK. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) { tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack, &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list)); } /* * If we got an ACK after fast retransmit, check to see * if it is a partial ACK. If it is not and the congestion * window was inflated to account for the other side's * cached packets, retract it. If it is, do Hoe's algorithm. */ if (tcp->tcp_dupack_cnt >= tcp_dupack_fast_retransmit) { assert(tcp->tcp_rexmit == B_FALSE); if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) { tcp->tcp_dupack_cnt = 0; /* * Restore the orig tcp_cwnd_ssthresh after * fast retransmit phase. */ if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) { tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh; } tcp->tcp_rexmit_max = seg_ack; tcp->tcp_cwnd_cnt = 0; tcp->tcp_snd_burst = TCP_CWND_NORMAL; /* * Remove all notsack info to avoid confusion with * the next fast retrasnmit/recovery phase. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) { TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list); } } else { if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) { flags |= TH_NEED_SACK_REXMIT; tcp->tcp_pipe -= mss; if (tcp->tcp_pipe < 0) tcp->tcp_pipe = 0; } else { /* * Hoe's algorithm: * * Retransmit the unack'ed segment and * restart fast recovery. Note that we * need to scale back tcp_cwnd to the * original value when we started fast * recovery. This is to prevent overly * aggressive behaviour in sending new * segments. */ tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh + tcp_dupack_fast_retransmit * mss; tcp->tcp_cwnd_cnt = tcp->tcp_cwnd; BUMP_MIB(tcp_mib.tcpOutFastRetrans); flags |= TH_REXMIT_NEEDED; } } } else { tcp->tcp_dupack_cnt = 0; if (tcp->tcp_rexmit) { /* * TCP is retranmitting. If the ACK ack's all * outstanding data, update tcp_rexmit_max and * tcp_rexmit_nxt. Otherwise, update tcp_rexmit_nxt * to the correct value. * * Note that SEQ_LEQ() is used. This is to avoid * unnecessary fast retransmit caused by dup ACKs * received when TCP does slow start retransmission * after a time out. During this phase, TCP may * send out segments which are already received. * This causes dup ACKs to be sent back. */ if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) { if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) { tcp->tcp_rexmit_nxt = seg_ack; } if (seg_ack != tcp->tcp_rexmit_max) { flags |= TH_XMIT_NEEDED; } } else { tcp->tcp_rexmit = B_FALSE; tcp->tcp_rexmit_nxt = tcp->tcp_snxt; tcp->tcp_snd_burst = TCP_CWND_NORMAL; } tcp->tcp_ms_we_have_waited = 0; } } BUMP_MIB(tcp_mib.tcpInAckSegs); UPDATE_MIB(tcp_mib.tcpInAckBytes, bytes_acked); tcp->tcp_suna = seg_ack; if (tcp->tcp_zero_win_probe != 0) { tcp->tcp_zero_win_probe = 0; tcp->tcp_timer_backoff = 0; } /* * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed. * Note that it cannot be the SYN being ack'ed. The code flow * will not reach here. */ if (mp1 == NULL) { goto fin_acked; } /* * Update the congestion window. * * If TCP is not ECN capable or TCP is ECN capable but the * congestion experience bit is not set, increase the tcp_cwnd as * usual. */ if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) { cwnd = tcp->tcp_cwnd; add = mss; if (cwnd >= tcp->tcp_cwnd_ssthresh) { /* * This is to prevent an increase of less than 1 MSS of * tcp_cwnd. With partial increase, tcp_wput_data() * may send out tinygrams in order to preserve mblk * boundaries. * * By initializing tcp_cwnd_cnt to new tcp_cwnd and * decrementing it by 1 MSS for every ACKs, tcp_cwnd is * increased by 1 MSS for every RTTs. */ if (tcp->tcp_cwnd_cnt <= 0) { tcp->tcp_cwnd_cnt = cwnd + add; } else { tcp->tcp_cwnd_cnt -= add; add = 0; } } tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max); } /* Can we update the RTT estimates? */ if (tcp->tcp_snd_ts_ok) { /* Ignore zero timestamp echo-reply. */ if (tcpopt.tcp_opt_ts_ecr != 0) { tcp_set_rto(tcp, (int32_t)(prom_gettime() - tcpopt.tcp_opt_ts_ecr)); } /* If needed, restart the timer. */ if (tcp->tcp_set_timer == 1) { TCP_TIMER_RESTART(tcp, tcp->tcp_rto); tcp->tcp_set_timer = 0; } /* * Update tcp_csuna in case the other side stops sending * us timestamps. */ tcp->tcp_csuna = tcp->tcp_snxt; } else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) { /* * An ACK sequence we haven't seen before, so get the RTT * and update the RTO. * Note. use uintptr_t to suppress the gcc warning. */ tcp_set_rto(tcp, (int32_t)(prom_gettime() - (uint32_t)(uintptr_t)mp1->b_prev)); /* Remeber the last sequence to be ACKed */ tcp->tcp_csuna = seg_ack; if (tcp->tcp_set_timer == 1) { TCP_TIMER_RESTART(tcp, tcp->tcp_rto); tcp->tcp_set_timer = 0; } } else { BUMP_MIB(tcp_mib.tcpRttNoUpdate); } /* Eat acknowledged bytes off the xmit queue. */ for (;;) { mblk_t *mp2; uchar_t *wptr; wptr = mp1->b_wptr; assert((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX); bytes_acked -= (int)(wptr - mp1->b_rptr); if (bytes_acked < 0) { mp1->b_rptr = wptr + bytes_acked; break; } mp1->b_prev = NULL; mp2 = mp1; mp1 = mp1->b_cont; freeb(mp2); if (bytes_acked == 0) { if (mp1 == NULL) { /* Everything is ack'ed, clear the tail. */ tcp->tcp_xmit_tail = NULL; goto pre_swnd_update; } if (mp2 != tcp->tcp_xmit_tail) break; tcp->tcp_xmit_tail = mp1; assert((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX); tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr - mp1->b_rptr); break; } if (mp1 == NULL) { /* * More was acked but there is nothing more * outstanding. This means that the FIN was * just acked or that we're talking to a clown. */ fin_acked: assert(tcp->tcp_fin_sent); tcp->tcp_xmit_tail = NULL; if (tcp->tcp_fin_sent) { tcp->tcp_fin_acked = B_TRUE; } else { /* * We should never got here because * we have already checked that the * number of bytes ack'ed should be * smaller than or equal to what we * have sent so far (it is the * acceptability check of the ACK). * We can only get here if the send * queue is corrupted. * * Terminate the connection and * panic the system. It is better * for us to panic instead of * continuing to avoid other disaster. */ tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt, tcp->tcp_rnxt, TH_RST|TH_ACK, 0, sock_id); printf("Memory corruption " "detected for connection %s.\n", tcp_display(tcp, NULL, DISP_ADDR_AND_PORT)); /* We should never get here... */ prom_panic("tcp_rput_data"); } goto pre_swnd_update; } assert(mp2 != tcp->tcp_xmit_tail); } if (tcp->tcp_unsent) { flags |= TH_XMIT_NEEDED; } pre_swnd_update: tcp->tcp_xmit_head = mp1; swnd_update: /* * The following check is different from most other implementations. * For bi-directional transfer, when segments are dropped, the * "normal" check will not accept a window update in those * retransmitted segemnts. Failing to do that, TCP may send out * segments which are outside receiver's window. As TCP accepts * the ack in those retransmitted segments, if the window update in * the same segment is not accepted, TCP will incorrectly calculates * that it can send more segments. This can create a deadlock * with the receiver if its window becomes zero. */ if (SEQ_LT(tcp->tcp_swl2, seg_ack) || SEQ_LT(tcp->tcp_swl1, seg_seq) || (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) { /* * The criteria for update is: * * 1. the segment acknowledges some data. Or * 2. the segment is new, i.e. it has a higher seq num. Or * 3. the segment is not old and the advertised window is * larger than the previous advertised window. */ if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd) flags |= TH_XMIT_NEEDED; tcp->tcp_swnd = new_swnd; if (new_swnd > tcp->tcp_max_swnd) tcp->tcp_max_swnd = new_swnd; tcp->tcp_swl1 = seg_seq; tcp->tcp_swl2 = seg_ack; } est: if (tcp->tcp_state > TCPS_ESTABLISHED) { switch (tcp->tcp_state) { case TCPS_FIN_WAIT_1: if (tcp->tcp_fin_acked) { tcp->tcp_state = TCPS_FIN_WAIT_2; /* * We implement the non-standard BSD/SunOS * FIN_WAIT_2 flushing algorithm. * If there is no user attached to this * TCP endpoint, then this TCP struct * could hang around forever in FIN_WAIT_2 * state if the peer forgets to send us * a FIN. To prevent this, we wait only * 2*MSL (a convenient time value) for * the FIN to arrive. If it doesn't show up, * we flush the TCP endpoint. This algorithm, * though a violation of RFC-793, has worked * for over 10 years in BSD systems. * Note: SunOS 4.x waits 675 seconds before * flushing the FIN_WAIT_2 connection. */ TCP_TIMER_RESTART(tcp, tcp_fin_wait_2_flush_interval); } break; case TCPS_FIN_WAIT_2: break; /* Shutdown hook? */ case TCPS_LAST_ACK: freemsg(mp); if (tcp->tcp_fin_acked) { (void) tcp_clean_death(sock_id, tcp, 0); return; } goto xmit_check; case TCPS_CLOSING: if (tcp->tcp_fin_acked) { tcp->tcp_state = TCPS_TIME_WAIT; tcp_time_wait_append(tcp); TCP_TIMER_RESTART(tcp, tcp_time_wait_interval); } /*FALLTHRU*/ case TCPS_CLOSE_WAIT: freemsg(mp); goto xmit_check; default: assert(tcp->tcp_state != TCPS_TIME_WAIT); break; } } if (flags & TH_FIN) { /* Make sure we ack the fin */ flags |= TH_ACK_NEEDED; if (!tcp->tcp_fin_rcvd) { tcp->tcp_fin_rcvd = B_TRUE; tcp->tcp_rnxt++; U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack); switch (tcp->tcp_state) { case TCPS_SYN_RCVD: case TCPS_ESTABLISHED: tcp->tcp_state = TCPS_CLOSE_WAIT; /* Keepalive? */ break; case TCPS_FIN_WAIT_1: if (!tcp->tcp_fin_acked) { tcp->tcp_state = TCPS_CLOSING; break; } /* FALLTHRU */ case TCPS_FIN_WAIT_2: tcp->tcp_state = TCPS_TIME_WAIT; tcp_time_wait_append(tcp); TCP_TIMER_RESTART(tcp, tcp_time_wait_interval); if (seg_len) { /* * implies data piggybacked on FIN. * break to handle data. */ break; } freemsg(mp); goto ack_check; } } } if (mp == NULL) goto xmit_check; if (seg_len == 0) { freemsg(mp); goto xmit_check; } if (mp->b_rptr == mp->b_wptr) { /* * The header has been consumed, so we remove the * zero-length mblk here. */ mp1 = mp; mp = mp->b_cont; freeb(mp1); } /* * ACK every other segments, unless the input queue is empty * as we don't have a timer available. */ if (++tcp->tcp_rack_cnt == 2 || sockets[sock_id].inq == NULL) { flags |= TH_ACK_NEEDED; tcp->tcp_rack_cnt = 0; } tcp->tcp_rnxt += seg_len; U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack); /* Update SACK list */ if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) { tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt, &(tcp->tcp_num_sack_blk)); } if (tcp->tcp_listener) { /* * Side queue inbound data until the accept happens. * tcp_accept/tcp_rput drains this when the accept happens. */ tcp_rcv_enqueue(tcp, mp, seg_len); } else { /* Just queue the data until the app calls read. */ tcp_rcv_enqueue(tcp, mp, seg_len); /* * Make sure the timer is running if we have data waiting * for a push bit. This provides resiliency against * implementations that do not correctly generate push bits. */ if (tcp->tcp_rcv_list != NULL) flags |= TH_TIMER_NEEDED; } xmit_check: /* Is there anything left to do? */ if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED| TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_TIMER_NEEDED)) == 0) return; /* Any transmit work to do and a non-zero window? */ if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT| TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) { if (flags & TH_REXMIT_NEEDED) { uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna; if (snd_size > mss) snd_size = mss; if (snd_size > tcp->tcp_swnd) snd_size = tcp->tcp_swnd; mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size, NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size, B_TRUE); if (mp1 != NULL) { /* use uintptr_t to suppress the gcc warning */ tcp->tcp_xmit_head->b_prev = (mblk_t *)(uintptr_t)prom_gettime(); tcp->tcp_csuna = tcp->tcp_snxt; BUMP_MIB(tcp_mib.tcpRetransSegs); UPDATE_MIB(tcp_mib.tcpRetransBytes, snd_size); (void) ipv4_tcp_output(sock_id, mp1); freeb(mp1); } } if (flags & TH_NEED_SACK_REXMIT) { if (tcp_sack_rxmit(tcp, sock_id) != 0) { flags |= TH_XMIT_NEEDED; } } /* * For TH_LIMIT_XMIT, tcp_wput_data() is called to send * out new segment. Note that tcp_rexmit should not be * set, otherwise TH_LIMIT_XMIT should not be set. */ if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) { if (!tcp->tcp_rexmit) { tcp_wput_data(tcp, NULL, sock_id); } else { tcp_ss_rexmit(tcp, sock_id); } /* * The TCP could be closed in tcp_state_wait via * tcp_wput_data (tcp_ss_rexmit could call * tcp_wput_data as well). */ if (sockets[sock_id].pcb == NULL) return; } /* * Adjust tcp_cwnd back to normal value after sending * new data segments. */ if (flags & TH_LIMIT_XMIT) { tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1); } /* Anything more to do? */ if ((flags & (TH_ACK_NEEDED|TH_TIMER_NEEDED)) == 0) return; } ack_check: if (flags & TH_ACK_NEEDED) { /* * Time to send an ack for some reason. */ if ((mp1 = tcp_ack_mp(tcp)) != NULL) { TCP_DUMP_PACKET("tcp_rput_data: ack mp", mp1); (void) ipv4_tcp_output(sock_id, mp1); BUMP_MIB(tcp_mib.tcpOutAck); freeb(mp1); } } } /* * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start * retransmission after a timeout. * * To limit the number of duplicate segments, we limit the number of segment * to be sent in one time to tcp_snd_burst, the burst variable. */ static void tcp_ss_rexmit(tcp_t *tcp, int sock_id) { uint32_t snxt; uint32_t smax; int32_t win; int32_t mss; int32_t off; int32_t burst = tcp->tcp_snd_burst; mblk_t *snxt_mp; /* * Note that tcp_rexmit can be set even though TCP has retransmitted * all unack'ed segments. */ if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) { smax = tcp->tcp_rexmit_max; snxt = tcp->tcp_rexmit_nxt; if (SEQ_LT(snxt, tcp->tcp_suna)) { snxt = tcp->tcp_suna; } win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd); win -= snxt - tcp->tcp_suna; mss = tcp->tcp_mss; snxt_mp = tcp_get_seg_mp(tcp, snxt, &off); while (SEQ_LT(snxt, smax) && (win > 0) && (burst > 0) && (snxt_mp != NULL)) { mblk_t *xmit_mp; mblk_t *old_snxt_mp = snxt_mp; uint32_t cnt = mss; if (win < cnt) { cnt = win; } if (SEQ_GT(snxt + cnt, smax)) { cnt = smax - snxt; } xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off, &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE); if (xmit_mp == NULL) return; (void) ipv4_tcp_output(sock_id, xmit_mp); freeb(xmit_mp); snxt += cnt; win -= cnt; /* * Update the send timestamp to avoid false * retransmission. * Note. use uintptr_t to suppress the gcc warning. */ old_snxt_mp->b_prev = (mblk_t *)(uintptr_t)prom_gettime(); BUMP_MIB(tcp_mib.tcpRetransSegs); UPDATE_MIB(tcp_mib.tcpRetransBytes, cnt); tcp->tcp_rexmit_nxt = snxt; burst--; } /* * If we have transmitted all we have at the time * we started the retranmission, we can leave * the rest of the job to tcp_wput_data(). But we * need to check the send window first. If the * win is not 0, go on with tcp_wput_data(). */ if (SEQ_LT(snxt, smax) || win == 0) { return; } } /* Only call tcp_wput_data() if there is data to be sent. */ if (tcp->tcp_unsent) { tcp_wput_data(tcp, NULL, sock_id); } } /* * tcp_timer is the timer service routine. It handles all timer events for * a tcp instance except keepalives. It figures out from the state of the * tcp instance what kind of action needs to be done at the time it is called. */ static void tcp_timer(tcp_t *tcp, int sock_id) { mblk_t *mp; uint32_t first_threshold; uint32_t second_threshold; uint32_t ms; uint32_t mss; first_threshold = tcp->tcp_first_timer_threshold; second_threshold = tcp->tcp_second_timer_threshold; switch (tcp->tcp_state) { case TCPS_IDLE: case TCPS_BOUND: case TCPS_LISTEN: return; case TCPS_SYN_RCVD: case TCPS_SYN_SENT: first_threshold = tcp->tcp_first_ctimer_threshold; second_threshold = tcp->tcp_second_ctimer_threshold; break; case TCPS_ESTABLISHED: case TCPS_FIN_WAIT_1: case TCPS_CLOSING: case TCPS_CLOSE_WAIT: case TCPS_LAST_ACK: /* If we have data to rexmit */ if (tcp->tcp_suna != tcp->tcp_snxt) { int32_t time_to_wait; BUMP_MIB(tcp_mib.tcpTimRetrans); if (tcp->tcp_xmit_head == NULL) break; /* use uintptr_t to suppress the gcc warning */ time_to_wait = (int32_t)(prom_gettime() - (uint32_t)(uintptr_t)tcp->tcp_xmit_head->b_prev); time_to_wait = tcp->tcp_rto - time_to_wait; if (time_to_wait > 0) { /* * Timer fired too early, so restart it. */ TCP_TIMER_RESTART(tcp, time_to_wait); return; } /* * When we probe zero windows, we force the swnd open. * If our peer acks with a closed window swnd will be * set to zero by tcp_rput(). As long as we are * receiving acks tcp_rput will * reset 'tcp_ms_we_have_waited' so as not to trip the * first and second interval actions. NOTE: the timer * interval is allowed to continue its exponential * backoff. */ if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) { DEBUG_1("tcp_timer (%d): zero win", sock_id); break; } else { /* * After retransmission, we need to do * slow start. Set the ssthresh to one * half of current effective window and * cwnd to one MSS. Also reset * tcp_cwnd_cnt. * * Note that if tcp_ssthresh is reduced because * of ECN, do not reduce it again unless it is * already one window of data away (tcp_cwr * should then be cleared) or this is a * timeout for a retransmitted segment. */ uint32_t npkt; if (!tcp->tcp_cwr || tcp->tcp_rexmit) { npkt = (MIN((tcp->tcp_timer_backoff ? tcp->tcp_cwnd_ssthresh : tcp->tcp_cwnd), tcp->tcp_swnd) >> 1) / tcp->tcp_mss; if (npkt < 2) npkt = 2; tcp->tcp_cwnd_ssthresh = npkt * tcp->tcp_mss; } tcp->tcp_cwnd = tcp->tcp_mss; tcp->tcp_cwnd_cnt = 0; if (tcp->tcp_ecn_ok) { tcp->tcp_cwr = B_TRUE; tcp->tcp_cwr_snd_max = tcp->tcp_snxt; tcp->tcp_ecn_cwr_sent = B_FALSE; } } break; } /* * We have something to send yet we cannot send. The * reason can be: * * 1. Zero send window: we need to do zero window probe. * 2. Zero cwnd: because of ECN, we need to "clock out * segments. * 3. SWS avoidance: receiver may have shrunk window, * reset our knowledge. * * Note that condition 2 can happen with either 1 or * 3. But 1 and 3 are exclusive. */ if (tcp->tcp_unsent != 0) { if (tcp->tcp_cwnd == 0) { /* * Set tcp_cwnd to 1 MSS so that a * new segment can be sent out. We * are "clocking out" new data when * the network is really congested. */ assert(tcp->tcp_ecn_ok); tcp->tcp_cwnd = tcp->tcp_mss; } if (tcp->tcp_swnd == 0) { /* Extend window for zero window probe */ tcp->tcp_swnd++; tcp->tcp_zero_win_probe = B_TRUE; BUMP_MIB(tcp_mib.tcpOutWinProbe); } else { /* * Handle timeout from sender SWS avoidance. * Reset our knowledge of the max send window * since the receiver might have reduced its * receive buffer. Avoid setting tcp_max_swnd * to one since that will essentially disable * the SWS checks. * * Note that since we don't have a SWS * state variable, if the timeout is set * for ECN but not for SWS, this * code will also be executed. This is * fine as tcp_max_swnd is updated * constantly and it will not affect * anything. */ tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2); } tcp_wput_data(tcp, NULL, sock_id); return; } /* Is there a FIN that needs to be to re retransmitted? */ if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && !tcp->tcp_fin_acked) break; /* Nothing to do, return without restarting timer. */ return; case TCPS_FIN_WAIT_2: /* * User closed the TCP endpoint and peer ACK'ed our FIN. * We waited some time for for peer's FIN, but it hasn't * arrived. We flush the connection now to avoid * case where the peer has rebooted. */ /* FALLTHRU */ case TCPS_TIME_WAIT: (void) tcp_clean_death(sock_id, tcp, 0); return; default: DEBUG_3("tcp_timer (%d): strange state (%d) %s", sock_id, tcp->tcp_state, tcp_display(tcp, NULL, DISP_PORT_ONLY)); return; } if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) { /* * For zero window probe, we need to send indefinitely, * unless we have not heard from the other side for some * time... */ if ((tcp->tcp_zero_win_probe == 0) || ((prom_gettime() - tcp->tcp_last_recv_time) > second_threshold)) { BUMP_MIB(tcp_mib.tcpTimRetransDrop); /* * If TCP is in SYN_RCVD state, send back a * RST|ACK as BSD does. Note that tcp_zero_win_probe * should be zero in TCPS_SYN_RCVD state. */ if (tcp->tcp_state == TCPS_SYN_RCVD) { tcp_xmit_ctl("tcp_timer: RST sent on timeout " "in SYN_RCVD", tcp, NULL, tcp->tcp_snxt, tcp->tcp_rnxt, TH_RST | TH_ACK, 0, sock_id); } (void) tcp_clean_death(sock_id, tcp, tcp->tcp_client_errno ? tcp->tcp_client_errno : ETIMEDOUT); return; } else { /* * Set tcp_ms_we_have_waited to second_threshold * so that in next timeout, we will do the above * check (lbolt - tcp_last_recv_time). This is * also to avoid overflow. * * We don't need to decrement tcp_timer_backoff * to avoid overflow because it will be decremented * later if new timeout value is greater than * tcp_rexmit_interval_max. In the case when * tcp_rexmit_interval_max is greater than * second_threshold, it means that we will wait * longer than second_threshold to send the next * window probe. */ tcp->tcp_ms_we_have_waited = second_threshold; } } else if (ms > first_threshold && tcp->tcp_rtt_sa != 0) { /* * We have been retransmitting for too long... The RTT * we calculated is probably incorrect. Reinitialize it. * Need to compensate for 0 tcp_rtt_sa. Reset * tcp_rtt_update so that we won't accidentally cache a * bad value. But only do this if this is not a zero * window probe. */ if (tcp->tcp_zero_win_probe == 0) { tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) + (tcp->tcp_rtt_sa >> 5); tcp->tcp_rtt_sa = 0; tcp->tcp_rtt_update = 0; } } tcp->tcp_timer_backoff++; if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd + tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) < tcp_rexmit_interval_min) { /* * This means the original RTO is tcp_rexmit_interval_min. * So we will use tcp_rexmit_interval_min as the RTO value * and do the backoff. */ ms = tcp_rexmit_interval_min << tcp->tcp_timer_backoff; } else { ms <<= tcp->tcp_timer_backoff; } if (ms > tcp_rexmit_interval_max) { ms = tcp_rexmit_interval_max; /* * ms is at max, decrement tcp_timer_backoff to avoid * overflow. */ tcp->tcp_timer_backoff--; } tcp->tcp_ms_we_have_waited += ms; if (tcp->tcp_zero_win_probe == 0) { tcp->tcp_rto = ms; } TCP_TIMER_RESTART(tcp, ms); /* * This is after a timeout and tcp_rto is backed off. Set * tcp_set_timer to 1 so that next time RTO is updated, we will * restart the timer with a correct value. */ tcp->tcp_set_timer = 1; mss = tcp->tcp_snxt - tcp->tcp_suna; if (mss > tcp->tcp_mss) mss = tcp->tcp_mss; if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0) mss = tcp->tcp_swnd; if ((mp = tcp->tcp_xmit_head) != NULL) { /* use uintptr_t to suppress the gcc warning */ mp->b_prev = (mblk_t *)(uintptr_t)prom_gettime(); } mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss, B_TRUE); if (mp == NULL) return; tcp->tcp_csuna = tcp->tcp_snxt; BUMP_MIB(tcp_mib.tcpRetransSegs); UPDATE_MIB(tcp_mib.tcpRetransBytes, mss); /* Dump the packet when debugging. */ TCP_DUMP_PACKET("tcp_timer", mp); (void) ipv4_tcp_output(sock_id, mp); freeb(mp); /* * When slow start after retransmission begins, start with * this seq no. tcp_rexmit_max marks the end of special slow * start phase. tcp_snd_burst controls how many segments * can be sent because of an ack. */ tcp->tcp_rexmit_nxt = tcp->tcp_suna; tcp->tcp_snd_burst = TCP_CWND_SS; if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0)) { tcp->tcp_rexmit_max = tcp->tcp_fss; } else { tcp->tcp_rexmit_max = tcp->tcp_snxt; } tcp->tcp_rexmit = B_TRUE; tcp->tcp_dupack_cnt = 0; /* * Remove all rexmit SACK blk to start from fresh. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) { TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list); tcp->tcp_num_notsack_blk = 0; tcp->tcp_cnt_notsack_list = 0; } } /* * The TCP normal data output path. * NOTE: the logic of the fast path is duplicated from this function. */ static void tcp_wput_data(tcp_t *tcp, mblk_t *mp, int sock_id) { int len; mblk_t *local_time; mblk_t *mp1; uchar_t *rptr; uint32_t snxt; int tail_unsent; int tcpstate; int usable = 0; mblk_t *xmit_tail; int32_t num_burst_seg; int32_t mss; int32_t num_sack_blk = 0; int32_t tcp_hdr_len; ipaddr_t *dst; ipaddr_t *src; #ifdef DEBUG printf("tcp_wput_data(%d) ##############################\n", sock_id); #endif tcpstate = tcp->tcp_state; if (mp == NULL) { /* Really tacky... but we need this for detached closes. */ len = tcp->tcp_unsent; goto data_null; } /* * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ, * or before a connection attempt has begun. * * The following should not happen in inetboot.... */ if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT || (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) { if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) { printf("tcp_wput_data: data after ordrel, %s\n", tcp_display(tcp, NULL, DISP_ADDR_AND_PORT)); } freemsg(mp); return; } /* Strip empties */ for (;;) { assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX); len = (int)(mp->b_wptr - mp->b_rptr); if (len > 0) break; mp1 = mp; mp = mp->b_cont; freeb(mp1); if (mp == NULL) { return; } } /* If we are the first on the list ... */ if (tcp->tcp_xmit_head == NULL) { tcp->tcp_xmit_head = mp; tcp->tcp_xmit_tail = mp; tcp->tcp_xmit_tail_unsent = len; } else { tcp->tcp_xmit_last->b_cont = mp; len += tcp->tcp_unsent; } /* Tack on however many more positive length mblks we have */ if ((mp1 = mp->b_cont) != NULL) { do { int tlen; assert((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX); tlen = (int)(mp1->b_wptr - mp1->b_rptr); if (tlen <= 0) { mp->b_cont = mp1->b_cont; freeb(mp1); } else { len += tlen; mp = mp1; } } while ((mp1 = mp->b_cont) != NULL); } tcp->tcp_xmit_last = mp; tcp->tcp_unsent = len; data_null: snxt = tcp->tcp_snxt; xmit_tail = tcp->tcp_xmit_tail; tail_unsent = tcp->tcp_xmit_tail_unsent; /* * Note that tcp_mss has been adjusted to take into account the * timestamp option if applicable. Because SACK options do not * appear in every TCP segments and they are of variable lengths, * they cannot be included in tcp_mss. Thus we need to calculate * the actual segment length when we need to send a segment which * includes SACK options. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) { int32_t opt_len; num_sack_blk = MIN(tcp->tcp_max_sack_blk, tcp->tcp_num_sack_blk); opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN; mss = tcp->tcp_mss - opt_len; tcp_hdr_len = tcp->tcp_hdr_len + opt_len; } else { mss = tcp->tcp_mss; tcp_hdr_len = tcp->tcp_hdr_len; } if ((tcp->tcp_suna == snxt) && (prom_gettime() - tcp->tcp_last_recv_time) >= tcp->tcp_rto) { tcp->tcp_cwnd = MIN(tcp_slow_start_after_idle * mss, MIN(4 * mss, MAX(2 * mss, 4380 / mss * mss))); } if (tcpstate == TCPS_SYN_RCVD) { /* * The three-way connection establishment handshake is not * complete yet. We want to queue the data for transmission * after entering ESTABLISHED state (RFC793). Setting usable to * zero cause a jump to "done" label effectively leaving data * on the queue. */ usable = 0; } else { int usable_r = tcp->tcp_swnd; /* * In the special case when cwnd is zero, which can only * happen if the connection is ECN capable, return now. * New segments is sent using tcp_timer(). The timer * is set in tcp_rput_data(). */ if (tcp->tcp_cwnd == 0) { /* * Note that tcp_cwnd is 0 before 3-way handshake is * finished. */ assert(tcp->tcp_ecn_ok || tcp->tcp_state < TCPS_ESTABLISHED); return; } /* usable = MIN(swnd, cwnd) - unacked_bytes */ if (usable_r > tcp->tcp_cwnd) usable_r = tcp->tcp_cwnd; /* NOTE: trouble if xmitting while SYN not acked? */ usable_r -= snxt; usable_r += tcp->tcp_suna; /* usable = MIN(usable, unsent) */ if (usable_r > len) usable_r = len; /* usable = MAX(usable, {1 for urgent, 0 for data}) */ if (usable_r != 0) usable = usable_r; } /* use uintptr_t to suppress the gcc warning */ local_time = (mblk_t *)(uintptr_t)prom_gettime(); /* * "Our" Nagle Algorithm. This is not the same as in the old * BSD. This is more in line with the true intent of Nagle. * * The conditions are: * 1. The amount of unsent data (or amount of data which can be * sent, whichever is smaller) is less than Nagle limit. * 2. The last sent size is also less than Nagle limit. * 3. There is unack'ed data. * 4. Urgent pointer is not set. Send urgent data ignoring the * Nagle algorithm. This reduces the probability that urgent * bytes get "merged" together. * 5. The app has not closed the connection. This eliminates the * wait time of the receiving side waiting for the last piece of * (small) data. * * If all are satisified, exit without sending anything. Note * that Nagle limit can be smaller than 1 MSS. Nagle limit is * the smaller of 1 MSS and global tcp_naglim_def (default to be * 4095). */ if (usable < (int)tcp->tcp_naglim && tcp->tcp_naglim > tcp->tcp_last_sent_len && snxt != tcp->tcp_suna && !(tcp->tcp_valid_bits & TCP_URG_VALID)) goto done; num_burst_seg = tcp->tcp_snd_burst; for (;;) { tcph_t *tcph; mblk_t *new_mp; if (num_burst_seg-- == 0) goto done; len = mss; if (len > usable) { len = usable; if (len <= 0) { /* Terminate the loop */ goto done; } /* * Sender silly-window avoidance. * Ignore this if we are going to send a * zero window probe out. * * TODO: force data into microscopic window ?? * ==> (!pushed || (unsent > usable)) */ if (len < (tcp->tcp_max_swnd >> 1) && (tcp->tcp_unsent - (snxt - tcp->tcp_snxt)) > len && !((tcp->tcp_valid_bits & TCP_URG_VALID) && len == 1) && (! tcp->tcp_zero_win_probe)) { /* * If the retransmit timer is not running * we start it so that we will retransmit * in the case when the the receiver has * decremented the window. */ if (snxt == tcp->tcp_snxt && snxt == tcp->tcp_suna) { /* * We are not supposed to send * anything. So let's wait a little * bit longer before breaking SWS * avoidance. * * What should the value be? * Suggestion: MAX(init rexmit time, * tcp->tcp_rto) */ TCP_TIMER_RESTART(tcp, tcp->tcp_rto); } goto done; } } tcph = tcp->tcp_tcph; usable -= len; /* Approximate - can be adjusted later */ if (usable > 0) tcph->th_flags[0] = TH_ACK; else tcph->th_flags[0] = (TH_ACK | TH_PUSH); U32_TO_ABE32(snxt, tcph->th_seq); if (tcp->tcp_valid_bits) { uchar_t *prev_rptr = xmit_tail->b_rptr; uint32_t prev_snxt = tcp->tcp_snxt; if (tail_unsent == 0) { assert(xmit_tail->b_cont != NULL); xmit_tail = xmit_tail->b_cont; prev_rptr = xmit_tail->b_rptr; tail_unsent = (int)(xmit_tail->b_wptr - xmit_tail->b_rptr); } else { xmit_tail->b_rptr = xmit_tail->b_wptr - tail_unsent; } mp = tcp_xmit_mp(tcp, xmit_tail, len, NULL, NULL, snxt, B_FALSE, (uint32_t *)&len, B_FALSE); /* Restore tcp_snxt so we get amount sent right. */ tcp->tcp_snxt = prev_snxt; if (prev_rptr == xmit_tail->b_rptr) xmit_tail->b_prev = local_time; else xmit_tail->b_rptr = prev_rptr; if (mp == NULL) break; mp1 = mp->b_cont; snxt += len; tcp->tcp_last_sent_len = (ushort_t)len; while (mp1->b_cont) { xmit_tail = xmit_tail->b_cont; xmit_tail->b_prev = local_time; mp1 = mp1->b_cont; } tail_unsent = xmit_tail->b_wptr - mp1->b_wptr; BUMP_MIB(tcp_mib.tcpOutDataSegs); UPDATE_MIB(tcp_mib.tcpOutDataBytes, len); /* Dump the packet when debugging. */ TCP_DUMP_PACKET("tcp_wput_data (valid bits)", mp); (void) ipv4_tcp_output(sock_id, mp); freeb(mp); continue; } snxt += len; /* Adjust later if we don't send all of len */ BUMP_MIB(tcp_mib.tcpOutDataSegs); UPDATE_MIB(tcp_mib.tcpOutDataBytes, len); if (tail_unsent) { /* Are the bytes above us in flight? */ rptr = xmit_tail->b_wptr - tail_unsent; if (rptr != xmit_tail->b_rptr) { tail_unsent -= len; len += tcp_hdr_len; tcp->tcp_ipha->ip_len = htons(len); mp = dupb(xmit_tail); if (!mp) break; mp->b_rptr = rptr; goto must_alloc; } } else { xmit_tail = xmit_tail->b_cont; assert((uintptr_t)(xmit_tail->b_wptr - xmit_tail->b_rptr) <= (uintptr_t)INT_MAX); tail_unsent = (int)(xmit_tail->b_wptr - xmit_tail->b_rptr); } tail_unsent -= len; tcp->tcp_last_sent_len = (ushort_t)len; len += tcp_hdr_len; if (tcp->tcp_ipversion == IPV4_VERSION) tcp->tcp_ipha->ip_len = htons(len); xmit_tail->b_prev = local_time; mp = dupb(xmit_tail); if (mp == NULL) goto out_of_mem; len = tcp_hdr_len; /* * There are four reasons to allocate a new hdr mblk: * 1) The bytes above us are in use by another packet * 2) We don't have good alignment * 3) The mblk is being shared * 4) We don't have enough room for a header */ rptr = mp->b_rptr - len; if (!OK_32PTR(rptr) || rptr < mp->b_datap) { /* NOTE: we assume allocb returns an OK_32PTR */ must_alloc:; mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra, 0); if (mp1 == NULL) { freemsg(mp); goto out_of_mem; } mp1->b_cont = mp; mp = mp1; /* Leave room for Link Level header */ len = tcp_hdr_len; rptr = &mp->b_rptr[tcp_wroff_xtra]; mp->b_wptr = &rptr[len]; } if (tcp->tcp_snd_ts_ok) { /* use uintptr_t to suppress the gcc warning */ U32_TO_BE32((uint32_t)(uintptr_t)local_time, (char *)tcph+TCP_MIN_HEADER_LENGTH+4); U32_TO_BE32(tcp->tcp_ts_recent, (char *)tcph+TCP_MIN_HEADER_LENGTH+8); } else { assert(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH); } mp->b_rptr = rptr; /* Copy the template header. */ dst = (ipaddr_t *)rptr; src = (ipaddr_t *)tcp->tcp_iphc; dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; dst[8] = src[8]; dst[9] = src[9]; len = tcp->tcp_hdr_len; if (len -= 40) { len >>= 2; dst += 10; src += 10; do { *dst++ = *src++; } while (--len); } /* * Set tcph to point to the header of the outgoing packet, * not to the template header. */ tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len); /* * Set the ECN info in the TCP header if it is not a zero * window probe. Zero window probe is only sent in * tcp_wput_data() and tcp_timer(). */ if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) { SET_ECT(tcp, rptr); if (tcp->tcp_ecn_echo_on) tcph->th_flags[0] |= TH_ECE; if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) { tcph->th_flags[0] |= TH_CWR; tcp->tcp_ecn_cwr_sent = B_TRUE; } } /* Fill in SACK options */ if (num_sack_blk > 0) { uchar_t *wptr = rptr + tcp->tcp_hdr_len; sack_blk_t *tmp; int32_t i; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_NOP; wptr[2] = TCPOPT_SACK; wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk * sizeof (sack_blk_t); wptr += TCPOPT_REAL_SACK_LEN; tmp = tcp->tcp_sack_list; for (i = 0; i < num_sack_blk; i++) { U32_TO_BE32(tmp[i].begin, wptr); wptr += sizeof (tcp_seq); U32_TO_BE32(tmp[i].end, wptr); wptr += sizeof (tcp_seq); } tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4); } if (tail_unsent) { mp1 = mp->b_cont; if (mp1 == NULL) mp1 = mp; /* * If we're a little short, tack on more mblks * as long as we don't need to split an mblk. */ while (tail_unsent < 0 && tail_unsent + (int)(xmit_tail->b_cont->b_wptr - xmit_tail->b_cont->b_rptr) <= 0) { xmit_tail = xmit_tail->b_cont; /* Stash for rtt use later */ xmit_tail->b_prev = local_time; mp1->b_cont = dupb(xmit_tail); mp1 = mp1->b_cont; assert((uintptr_t)(xmit_tail->b_wptr - xmit_tail->b_rptr) <= (uintptr_t)INT_MAX); tail_unsent += (int)(xmit_tail->b_wptr - xmit_tail->b_rptr); if (mp1 == NULL) { freemsg(mp); goto out_of_mem; } } /* Trim back any surplus on the last mblk */ if (tail_unsent > 0) mp1->b_wptr -= tail_unsent; if (tail_unsent < 0) { uint32_t ip_len; /* * We did not send everything we could in * order to preserve mblk boundaries. */ usable -= tail_unsent; snxt += tail_unsent; tcp->tcp_last_sent_len += tail_unsent; UPDATE_MIB(tcp_mib.tcpOutDataBytes, tail_unsent); /* Adjust the IP length field. */ ip_len = ntohs(((struct ip *)rptr)->ip_len) + tail_unsent; ((struct ip *)rptr)->ip_len = htons(ip_len); tail_unsent = 0; } } if (mp == NULL) goto out_of_mem; /* * Performance hit! We need to pullup the whole message * in order to do checksum and for the MAC output routine. */ if (mp->b_cont != NULL) { int mp_size; #ifdef DEBUG printf("Multiple mblk %d\n", msgdsize(mp)); #endif new_mp = allocb(msgdsize(mp) + tcp_wroff_xtra, 0); new_mp->b_rptr += tcp_wroff_xtra; new_mp->b_wptr = new_mp->b_rptr; while (mp != NULL) { mp_size = mp->b_wptr - mp->b_rptr; bcopy(mp->b_rptr, new_mp->b_wptr, mp_size); new_mp->b_wptr += mp_size; mp = mp->b_cont; } freemsg(mp); mp = new_mp; } tcp_set_cksum(mp); ((struct ip *)mp->b_rptr)->ip_ttl = (uint8_t)tcp_ipv4_ttl; TCP_DUMP_PACKET("tcp_wput_data", mp); (void) ipv4_tcp_output(sock_id, mp); freemsg(mp); } out_of_mem:; /* Pretend that all we were trying to send really got sent */ if (tail_unsent < 0) { do { xmit_tail = xmit_tail->b_cont; xmit_tail->b_prev = local_time; assert((uintptr_t)(xmit_tail->b_wptr - xmit_tail->b_rptr) <= (uintptr_t)INT_MAX); tail_unsent += (int)(xmit_tail->b_wptr - xmit_tail->b_rptr); } while (tail_unsent < 0); } done:; tcp->tcp_xmit_tail = xmit_tail; tcp->tcp_xmit_tail_unsent = tail_unsent; len = tcp->tcp_snxt - snxt; if (len) { /* * If new data was sent, need to update the notsack * list, which is, afterall, data blocks that have * not been sack'ed by the receiver. New data is * not sack'ed. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) { /* len is a negative value. */ tcp->tcp_pipe -= len; tcp_notsack_update(&(tcp->tcp_notsack_list), tcp->tcp_snxt, snxt, &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list)); } tcp->tcp_snxt = snxt + tcp->tcp_fin_sent; tcp->tcp_rack = tcp->tcp_rnxt; tcp->tcp_rack_cnt = 0; if ((snxt + len) == tcp->tcp_suna) { TCP_TIMER_RESTART(tcp, tcp->tcp_rto); } /* * Note that len is the amount we just sent but with a negative * sign. We update tcp_unsent here since we may come back to * tcp_wput_data from tcp_state_wait. */ len += tcp->tcp_unsent; tcp->tcp_unsent = len; /* * Let's wait till all the segments have been acked, since we * don't have a timer. */ (void) tcp_state_wait(sock_id, tcp, TCPS_ALL_ACKED); return; } else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) { /* * Didn't send anything. Make sure the timer is running * so that we will probe a zero window. */ TCP_TIMER_RESTART(tcp, tcp->tcp_rto); } /* Note that len is the amount we just sent but with a negative sign */ len += tcp->tcp_unsent; tcp->tcp_unsent = len; } static void tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcph_t *tcph, int sock_id) { int32_t bytes_acked; int32_t gap; int32_t rgap; tcp_opt_t tcpopt; uint_t flags; uint32_t new_swnd = 0; #ifdef DEBUG printf("Time wait processing called ###############3\n"); #endif /* Just make sure we send the right sock_id to tcp_clean_death */ if ((sockets[sock_id].pcb == NULL) || (sockets[sock_id].pcb != tcp)) sock_id = -1; flags = (unsigned int)tcph->th_flags[0] & 0xFF; new_swnd = BE16_TO_U16(tcph->th_win) << ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws); if (tcp->tcp_snd_ts_ok) { if (!tcp_paws_check(tcp, tcph, &tcpopt)) { freemsg(mp); tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK, 0, -1); return; } } gap = seg_seq - tcp->tcp_rnxt; rgap = tcp->tcp_rwnd - (gap + seg_len); if (gap < 0) { BUMP_MIB(tcp_mib.tcpInDataDupSegs); UPDATE_MIB(tcp_mib.tcpInDataDupBytes, (seg_len > -gap ? -gap : seg_len)); seg_len += gap; if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) { if (flags & TH_RST) { freemsg(mp); return; } if ((flags & TH_FIN) && seg_len == -1) { /* * When TCP receives a duplicate FIN in * TIME_WAIT state, restart the 2 MSL timer. * See page 73 in RFC 793. Make sure this TCP * is already on the TIME_WAIT list. If not, * just restart the timer. */ tcp_time_wait_remove(tcp); tcp_time_wait_append(tcp); TCP_TIMER_RESTART(tcp, tcp_time_wait_interval); tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK, 0, -1); freemsg(mp); return; } flags |= TH_ACK_NEEDED; seg_len = 0; goto process_ack; } /* Fix seg_seq, and chew the gap off the front. */ seg_seq = tcp->tcp_rnxt; } if ((flags & TH_SYN) && gap > 0 && rgap < 0) { /* * Make sure that when we accept the connection, pick * an ISS greater than (tcp_snxt + ISS_INCR/2) for the * old connection. * * The next ISS generated is equal to tcp_iss_incr_extra * + ISS_INCR/2 + other components depending on the * value of tcp_strong_iss. We pre-calculate the new * ISS here and compare with tcp_snxt to determine if * we need to make adjustment to tcp_iss_incr_extra. * * Note that since we are now in the global queue * perimeter and need to do a lateral_put() to the * listener queue, there can be other connection requests/ * attempts while the lateral_put() is going on. That * means what we calculate here may not be correct. This * is extremely difficult to solve unless TCP and IP * modules are merged and there is no perimeter, but just * locks. The above calculation is ugly and is a * waste of CPU cycles... */ uint32_t new_iss = tcp_iss_incr_extra; int32_t adj; /* Add time component and min random (i.e. 1). */ new_iss += (prom_gettime() >> ISS_NSEC_SHT) + 1; if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) { /* * New ISS not guaranteed to be ISS_INCR/2 * ahead of the current tcp_snxt, so add the * difference to tcp_iss_incr_extra. */ tcp_iss_incr_extra += adj; } tcp_clean_death(sock_id, tcp, 0); /* * This is a passive open. Right now we do not * do anything... */ freemsg(mp); return; } /* * rgap is the amount of stuff received out of window. A negative * value is the amount out of window. */ if (rgap < 0) { BUMP_MIB(tcp_mib.tcpInDataPastWinSegs); UPDATE_MIB(tcp_mib.tcpInDataPastWinBytes, -rgap); /* Fix seg_len and make sure there is something left. */ seg_len += rgap; if (seg_len <= 0) { if (flags & TH_RST) { freemsg(mp); return; } flags |= TH_ACK_NEEDED; seg_len = 0; goto process_ack; } } /* * Check whether we can update tcp_ts_recent. This test is * NOT the one in RFC 1323 3.4. It is from Braden, 1993, "TCP * Extensions for High Performance: An Update", Internet Draft. */ if (tcp->tcp_snd_ts_ok && TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) && SEQ_LEQ(seg_seq, tcp->tcp_rack)) { tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val; tcp->tcp_last_rcv_lbolt = prom_gettime(); } if (seg_seq != tcp->tcp_rnxt && seg_len > 0) { /* Always ack out of order packets */ flags |= TH_ACK_NEEDED; seg_len = 0; } else if (seg_len > 0) { BUMP_MIB(tcp_mib.tcpInDataInorderSegs); UPDATE_MIB(tcp_mib.tcpInDataInorderBytes, seg_len); } if (flags & TH_RST) { freemsg(mp); (void) tcp_clean_death(sock_id, tcp, 0); return; } if (flags & TH_SYN) { freemsg(mp); tcp_xmit_ctl("TH_SYN", tcp, NULL, seg_ack, seg_seq + 1, TH_RST|TH_ACK, 0, -1); /* * Do not delete the TCP structure if it is in * TIME_WAIT state. Refer to RFC 1122, 4.2.2.13. */ return; } process_ack: if (flags & TH_ACK) { bytes_acked = (int)(seg_ack - tcp->tcp_suna); if (bytes_acked <= 0) { if (bytes_acked == 0 && seg_len == 0 && new_swnd == tcp->tcp_swnd) BUMP_MIB(tcp_mib.tcpInDupAck); } else { /* Acks something not sent */ flags |= TH_ACK_NEEDED; } } freemsg(mp); if (flags & TH_ACK_NEEDED) { /* * Time to send an ack for some reason. */ tcp_xmit_ctl(NULL, tcp, NULL, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK, 0, -1); } } static int tcp_init_values(tcp_t *tcp, struct inetboot_socket *isp) { int err; tcp->tcp_family = AF_INET; tcp->tcp_ipversion = IPV4_VERSION; /* * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO * will be close to tcp_rexmit_interval_initial. By doing this, we * allow the algorithm to adjust slowly to large fluctuations of RTT * during first few transmissions of a connection as seen in slow * links. */ tcp->tcp_rtt_sa = tcp_rexmit_interval_initial << 2; tcp->tcp_rtt_sd = tcp_rexmit_interval_initial >> 1; tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd + tcp_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) + tcp_conn_grace_period; if (tcp->tcp_rto < tcp_rexmit_interval_min) tcp->tcp_rto = tcp_rexmit_interval_min; tcp->tcp_timer_backoff = 0; tcp->tcp_ms_we_have_waited = 0; tcp->tcp_last_recv_time = prom_gettime(); tcp->tcp_cwnd_max = tcp_cwnd_max_; tcp->tcp_snd_burst = TCP_CWND_INFINITE; tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN; /* For Ethernet, the mtu returned is actually 1550... */ if (mac_get_type() == IFT_ETHER) { tcp->tcp_if_mtu = mac_get_mtu() - 50; } else { tcp->tcp_if_mtu = mac_get_mtu(); } tcp->tcp_mss = tcp->tcp_if_mtu; tcp->tcp_first_timer_threshold = tcp_ip_notify_interval; tcp->tcp_first_ctimer_threshold = tcp_ip_notify_cinterval; tcp->tcp_second_timer_threshold = tcp_ip_abort_interval; /* * Fix it to tcp_ip_abort_linterval later if it turns out to be a * passive open. */ tcp->tcp_second_ctimer_threshold = tcp_ip_abort_cinterval; tcp->tcp_naglim = tcp_naglim_def; /* NOTE: ISS is now set in tcp_adapt_ire(). */ /* Initialize the header template */ if (tcp->tcp_ipversion == IPV4_VERSION) { err = tcp_header_init_ipv4(tcp); } if (err) return (err); /* * Init the window scale to the max so tcp_rwnd_set() won't pare * down tcp_rwnd. tcp_adapt_ire() will set the right value later. */ tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT; tcp->tcp_xmit_lowater = tcp_xmit_lowat; if (isp != NULL) { tcp->tcp_xmit_hiwater = isp->so_sndbuf; tcp->tcp_rwnd = isp->so_rcvbuf; tcp->tcp_rwnd_max = isp->so_rcvbuf; } tcp->tcp_state = TCPS_IDLE; return (0); } /* * Initialize the IPv4 header. Loses any record of any IP options. */ static int tcp_header_init_ipv4(tcp_t *tcp) { tcph_t *tcph; /* * This is a simple initialization. If there's * already a template, it should never be too small, * so reuse it. Otherwise, allocate space for the new one. */ if (tcp->tcp_iphc != NULL) { assert(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH); bzero(tcp->tcp_iphc, tcp->tcp_iphc_len); } else { tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH; tcp->tcp_iphc = bkmem_zalloc(tcp->tcp_iphc_len); if (tcp->tcp_iphc == NULL) { tcp->tcp_iphc_len = 0; return (ENOMEM); } } tcp->tcp_ipha = (struct ip *)tcp->tcp_iphc; tcp->tcp_ipversion = IPV4_VERSION; /* * Note that it does not include TCP options yet. It will * after the connection is established. */ tcp->tcp_hdr_len = sizeof (struct ip) + sizeof (tcph_t); tcp->tcp_tcp_hdr_len = sizeof (tcph_t); tcp->tcp_ip_hdr_len = sizeof (struct ip); tcp->tcp_ipha->ip_v = IP_VERSION; /* We don't support IP options... */ tcp->tcp_ipha->ip_hl = IP_SIMPLE_HDR_LENGTH_IN_WORDS; tcp->tcp_ipha->ip_p = IPPROTO_TCP; /* We are not supposed to do PMTU discovery... */ tcp->tcp_ipha->ip_sum = 0; tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (struct ip)); tcp->tcp_tcph = tcph; tcph->th_offset_and_rsrvd[0] = (5 << 4); return (0); } /* * Send out a control packet on the tcp connection specified. This routine * is typically called where we need a simple ACK or RST generated. * * This function is called with or without a mp. */ static void tcp_xmit_ctl(char *str, tcp_t *tcp, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len, int sock_id) { uchar_t *rptr; tcph_t *tcph; struct ip *iph = NULL; int tcp_hdr_len; int tcp_ip_hdr_len; tcp_hdr_len = tcp->tcp_hdr_len; tcp_ip_hdr_len = tcp->tcp_ip_hdr_len; if (mp) { assert(ip_hdr_len != 0); rptr = mp->b_rptr; tcph = (tcph_t *)(rptr + ip_hdr_len); /* Don't reply to a RST segment. */ if (tcph->th_flags[0] & TH_RST) { freeb(mp); return; } freemsg(mp); rptr = NULL; } else { assert(ip_hdr_len == 0); } /* If a text string is passed in with the request, print it out. */ if (str != NULL) { dprintf("tcp_xmit_ctl(%d): '%s', seq 0x%x, ack 0x%x, " "ctl 0x%x\n", sock_id, str, seq, ack, ctl); } mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra, 0); if (mp == NULL) { dprintf("tcp_xmit_ctl(%d): Cannot allocate memory\n", sock_id); return; } rptr = &mp->b_rptr[tcp_wroff_xtra]; mp->b_rptr = rptr; mp->b_wptr = &rptr[tcp_hdr_len]; bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len); iph = (struct ip *)rptr; iph->ip_len = htons(tcp_hdr_len); tcph = (tcph_t *)&rptr[tcp_ip_hdr_len]; tcph->th_flags[0] = (uint8_t)ctl; if (ctl & TH_RST) { BUMP_MIB(tcp_mib.tcpOutRsts); BUMP_MIB(tcp_mib.tcpOutControl); /* * Don't send TSopt w/ TH_RST packets per RFC 1323. */ if (tcp->tcp_snd_ts_ok && tcp->tcp_state > TCPS_SYN_SENT) { mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN]; *(mp->b_wptr) = TCPOPT_EOL; iph->ip_len = htons(tcp_hdr_len - TCPOPT_REAL_TS_LEN); tcph->th_offset_and_rsrvd[0] -= (3 << 4); } } if (ctl & TH_ACK) { uint32_t now = prom_gettime(); if (tcp->tcp_snd_ts_ok) { U32_TO_BE32(now, (char *)tcph+TCP_MIN_HEADER_LENGTH+4); U32_TO_BE32(tcp->tcp_ts_recent, (char *)tcph+TCP_MIN_HEADER_LENGTH+8); } tcp->tcp_rack = ack; tcp->tcp_rack_cnt = 0; BUMP_MIB(tcp_mib.tcpOutAck); } BUMP_MIB(tcp_mib.tcpOutSegs); U32_TO_BE32(seq, tcph->th_seq); U32_TO_BE32(ack, tcph->th_ack); tcp_set_cksum(mp); iph->ip_ttl = (uint8_t)tcp_ipv4_ttl; TCP_DUMP_PACKET("tcp_xmit_ctl", mp); (void) ipv4_tcp_output(sock_id, mp); freeb(mp); } /* Generate an ACK-only (no data) segment for a TCP endpoint */ static mblk_t * tcp_ack_mp(tcp_t *tcp) { if (tcp->tcp_valid_bits) { /* * For the complex case where we have to send some * controls (FIN or SYN), let tcp_xmit_mp do it. * When sending an ACK-only segment (no data) * into a zero window, always set the seq number to * suna, since snxt will be extended past the window. * If we used snxt, the receiver might consider the ACK * unacceptable. */ return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, (tcp->tcp_zero_win_probe) ? tcp->tcp_suna : tcp->tcp_snxt, B_FALSE, NULL, B_FALSE)); } else { /* Generate a simple ACK */ uchar_t *rptr; tcph_t *tcph; mblk_t *mp1; int32_t tcp_hdr_len; int32_t num_sack_blk = 0; int32_t sack_opt_len; /* * Allocate space for TCP + IP headers * and link-level header */ if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) { num_sack_blk = MIN(tcp->tcp_max_sack_blk, tcp->tcp_num_sack_blk); sack_opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN; tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len; } else { tcp_hdr_len = tcp->tcp_hdr_len; } mp1 = allocb(tcp_hdr_len + tcp_wroff_xtra, 0); if (mp1 == NULL) return (NULL); /* copy in prototype TCP + IP header */ rptr = mp1->b_rptr + tcp_wroff_xtra; mp1->b_rptr = rptr; mp1->b_wptr = rptr + tcp_hdr_len; bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len); tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len]; /* * Set the TCP sequence number. * When sending an ACK-only segment (no data) * into a zero window, always set the seq number to * suna, since snxt will be extended past the window. * If we used snxt, the receiver might consider the ACK * unacceptable. */ U32_TO_ABE32((tcp->tcp_zero_win_probe) ? tcp->tcp_suna : tcp->tcp_snxt, tcph->th_seq); /* Set up the TCP flag field. */ tcph->th_flags[0] = (uchar_t)TH_ACK; if (tcp->tcp_ecn_echo_on) tcph->th_flags[0] |= TH_ECE; tcp->tcp_rack = tcp->tcp_rnxt; tcp->tcp_rack_cnt = 0; /* fill in timestamp option if in use */ if (tcp->tcp_snd_ts_ok) { uint32_t llbolt = (uint32_t)prom_gettime(); U32_TO_BE32(llbolt, (char *)tcph+TCP_MIN_HEADER_LENGTH+4); U32_TO_BE32(tcp->tcp_ts_recent, (char *)tcph+TCP_MIN_HEADER_LENGTH+8); } /* Fill in SACK options */ if (num_sack_blk > 0) { uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len; sack_blk_t *tmp; int32_t i; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_NOP; wptr[2] = TCPOPT_SACK; wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk * sizeof (sack_blk_t); wptr += TCPOPT_REAL_SACK_LEN; tmp = tcp->tcp_sack_list; for (i = 0; i < num_sack_blk; i++) { U32_TO_BE32(tmp[i].begin, wptr); wptr += sizeof (tcp_seq); U32_TO_BE32(tmp[i].end, wptr); wptr += sizeof (tcp_seq); } tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4); } ((struct ip *)rptr)->ip_len = htons(tcp_hdr_len); tcp_set_cksum(mp1); ((struct ip *)rptr)->ip_ttl = (uint8_t)tcp_ipv4_ttl; return (mp1); } } /* * tcp_xmit_mp is called to return a pointer to an mblk chain complete with * ip and tcp header ready to pass down to IP. If the mp passed in is * non-NULL, then up to max_to_send bytes of data will be dup'ed off that * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary * otherwise it will dup partial mblks.) * Otherwise, an appropriate ACK packet will be generated. This * routine is not usually called to send new data for the first time. It * is mostly called out of the timer for retransmits, and to generate ACKs. * * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will * be adjusted by *offset. And after dupb(), the offset and the ending mblk * of the original mblk chain will be returned in *offset and *end_mp. */ static mblk_t * tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset, mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len, boolean_t rexmit) { int data_length; int32_t off = 0; uint_t flags; mblk_t *mp1; mblk_t *mp2; mblk_t *new_mp; uchar_t *rptr; tcph_t *tcph; int32_t num_sack_blk = 0; int32_t sack_opt_len = 0; /* Allocate for our maximum TCP header + link-level */ mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcp_wroff_xtra, 0); if (mp1 == NULL) return (NULL); data_length = 0; /* * Note that tcp_mss has been adjusted to take into account the * timestamp option if applicable. Because SACK options do not * appear in every TCP segments and they are of variable lengths, * they cannot be included in tcp_mss. Thus we need to calculate * the actual segment length when we need to send a segment which * includes SACK options. */ if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) { num_sack_blk = MIN(tcp->tcp_max_sack_blk, tcp->tcp_num_sack_blk); sack_opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN; if (max_to_send + sack_opt_len > tcp->tcp_mss) max_to_send -= sack_opt_len; } if (offset != NULL) { off = *offset; /* We use offset as an indicator that end_mp is not NULL. */ *end_mp = NULL; } for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) { /* This could be faster with cooperation from downstream */ if (mp2 != mp1 && !sendall && data_length + (int)(mp->b_wptr - mp->b_rptr) > max_to_send) /* * Don't send the next mblk since the whole mblk * does not fit. */ break; mp2->b_cont = dupb(mp); mp2 = mp2->b_cont; if (mp2 == NULL) { freemsg(mp1); return (NULL); } mp2->b_rptr += off; assert((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <= (uintptr_t)INT_MAX); data_length += (int)(mp2->b_wptr - mp2->b_rptr); if (data_length > max_to_send) { mp2->b_wptr -= data_length - max_to_send; data_length = max_to_send; off = mp2->b_wptr - mp->b_rptr; break; } else { off = 0; } } if (offset != NULL) { *offset = off; *end_mp = mp; } if (seg_len != NULL) { *seg_len = data_length; } rptr = mp1->b_rptr + tcp_wroff_xtra; mp1->b_rptr = rptr; mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len; bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len); tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len]; U32_TO_ABE32(seq, tcph->th_seq); /* * Use tcp_unsent to determine if the PUSH bit should be used assumes * that this function was called from tcp_wput_data. Thus, when called * to retransmit data the setting of the PUSH bit may appear some * what random in that it might get set when it should not. This * should not pose any performance issues. */ if (data_length != 0 && (tcp->tcp_unsent == 0 || tcp->tcp_unsent == data_length)) { flags = TH_ACK | TH_PUSH; } else { flags = TH_ACK; } if (tcp->tcp_ecn_ok) { if (tcp->tcp_ecn_echo_on) flags |= TH_ECE; /* * Only set ECT bit and ECN_CWR if a segment contains new data. * There is no TCP flow control for non-data segments, and * only data segment is transmitted reliably. */ if (data_length > 0 && !rexmit) { SET_ECT(tcp, rptr); if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) { flags |= TH_CWR; tcp->tcp_ecn_cwr_sent = B_TRUE; } } } if (tcp->tcp_valid_bits) { uint32_t u1; if ((tcp->tcp_valid_bits & TCP_ISS_VALID) && seq == tcp->tcp_iss) { uchar_t *wptr; /* * Tack on the MSS option. It is always needed * for both active and passive open. */ wptr = mp1->b_wptr; wptr[0] = TCPOPT_MAXSEG; wptr[1] = TCPOPT_MAXSEG_LEN; wptr += 2; /* * MSS option value should be interface MTU - MIN * TCP/IP header. */ u1 = tcp->tcp_if_mtu - IP_SIMPLE_HDR_LENGTH - TCP_MIN_HEADER_LENGTH; U16_TO_BE16(u1, wptr); mp1->b_wptr = wptr + 2; /* Update the offset to cover the additional word */ tcph->th_offset_and_rsrvd[0] += (1 << 4); /* * Note that the following way of filling in * TCP options are not optimal. Some NOPs can * be saved. But there is no need at this time * to optimize it. When it is needed, we will * do it. */ switch (tcp->tcp_state) { case TCPS_SYN_SENT: flags = TH_SYN; if (tcp->tcp_snd_ws_ok) { wptr = mp1->b_wptr; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_WSCALE; wptr[2] = TCPOPT_WS_LEN; wptr[3] = (uchar_t)tcp->tcp_rcv_ws; mp1->b_wptr += TCPOPT_REAL_WS_LEN; tcph->th_offset_and_rsrvd[0] += (1 << 4); } if (tcp->tcp_snd_ts_ok) { uint32_t llbolt; llbolt = prom_gettime(); wptr = mp1->b_wptr; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_NOP; wptr[2] = TCPOPT_TSTAMP; wptr[3] = TCPOPT_TSTAMP_LEN; wptr += 4; U32_TO_BE32(llbolt, wptr); wptr += 4; assert(tcp->tcp_ts_recent == 0); U32_TO_BE32(0L, wptr); mp1->b_wptr += TCPOPT_REAL_TS_LEN; tcph->th_offset_and_rsrvd[0] += (3 << 4); } if (tcp->tcp_snd_sack_ok) { wptr = mp1->b_wptr; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_NOP; wptr[2] = TCPOPT_SACK_PERMITTED; wptr[3] = TCPOPT_SACK_OK_LEN; mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN; tcph->th_offset_and_rsrvd[0] += (1 << 4); } /* * Set up all the bits to tell other side * we are ECN capable. */ if (tcp->tcp_ecn_ok) { flags |= (TH_ECE | TH_CWR); } break; case TCPS_SYN_RCVD: flags |= TH_SYN; if (tcp->tcp_snd_ws_ok) { wptr = mp1->b_wptr; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_WSCALE; wptr[2] = TCPOPT_WS_LEN; wptr[3] = (uchar_t)tcp->tcp_rcv_ws; mp1->b_wptr += TCPOPT_REAL_WS_LEN; tcph->th_offset_and_rsrvd[0] += (1 << 4); } if (tcp->tcp_snd_sack_ok) { wptr = mp1->b_wptr; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_NOP; wptr[2] = TCPOPT_SACK_PERMITTED; wptr[3] = TCPOPT_SACK_OK_LEN; mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN; tcph->th_offset_and_rsrvd[0] += (1 << 4); } /* * If the other side is ECN capable, reply * that we are also ECN capable. */ if (tcp->tcp_ecn_ok) { flags |= TH_ECE; } break; default: break; } /* allocb() of adequate mblk assures space */ assert((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX); if (flags & TH_SYN) BUMP_MIB(tcp_mib.tcpOutControl); } if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (seq + data_length) == tcp->tcp_fss) { if (!tcp->tcp_fin_acked) { flags |= TH_FIN; BUMP_MIB(tcp_mib.tcpOutControl); } if (!tcp->tcp_fin_sent) { tcp->tcp_fin_sent = B_TRUE; switch (tcp->tcp_state) { case TCPS_SYN_RCVD: case TCPS_ESTABLISHED: tcp->tcp_state = TCPS_FIN_WAIT_1; break; case TCPS_CLOSE_WAIT: tcp->tcp_state = TCPS_LAST_ACK; break; } if (tcp->tcp_suna == tcp->tcp_snxt) { TCP_TIMER_RESTART(tcp, tcp->tcp_rto); } tcp->tcp_snxt = tcp->tcp_fss + 1; } } } tcph->th_flags[0] = (uchar_t)flags; tcp->tcp_rack = tcp->tcp_rnxt; tcp->tcp_rack_cnt = 0; if (tcp->tcp_snd_ts_ok) { if (tcp->tcp_state != TCPS_SYN_SENT) { uint32_t llbolt = prom_gettime(); U32_TO_BE32(llbolt, (char *)tcph+TCP_MIN_HEADER_LENGTH+4); U32_TO_BE32(tcp->tcp_ts_recent, (char *)tcph+TCP_MIN_HEADER_LENGTH+8); } } if (num_sack_blk > 0) { uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len; sack_blk_t *tmp; int32_t i; wptr[0] = TCPOPT_NOP; wptr[1] = TCPOPT_NOP; wptr[2] = TCPOPT_SACK; wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk * sizeof (sack_blk_t); wptr += TCPOPT_REAL_SACK_LEN; tmp = tcp->tcp_sack_list; for (i = 0; i < num_sack_blk; i++) { U32_TO_BE32(tmp[i].begin, wptr); wptr += sizeof (tcp_seq); U32_TO_BE32(tmp[i].end, wptr); wptr += sizeof (tcp_seq); } tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4); } assert((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX); data_length += (int)(mp1->b_wptr - rptr); if (tcp->tcp_ipversion == IPV4_VERSION) ((struct ip *)rptr)->ip_len = htons(data_length); /* * Performance hit! We need to pullup the whole message * in order to do checksum and for the MAC output routine. */ if (mp1->b_cont != NULL) { int mp_size; #ifdef DEBUG printf("Multiple mblk %d\n", msgdsize(mp1)); #endif mp2 = mp1; new_mp = allocb(msgdsize(mp1) + tcp_wroff_xtra, 0); new_mp->b_rptr += tcp_wroff_xtra; new_mp->b_wptr = new_mp->b_rptr; while (mp1 != NULL) { mp_size = mp1->b_wptr - mp1->b_rptr; bcopy(mp1->b_rptr, new_mp->b_wptr, mp_size); new_mp->b_wptr += mp_size; mp1 = mp1->b_cont; } freemsg(mp2); mp1 = new_mp; } tcp_set_cksum(mp1); /* Fill in the TTL field as it is 0 in the header template. */ ((struct ip *)mp1->b_rptr)->ip_ttl = (uint8_t)tcp_ipv4_ttl; return (mp1); } /* * Generate a "no listener here" reset in response to the * connection request contained within 'mp' */ static void tcp_xmit_listeners_reset(int sock_id, mblk_t *mp, uint_t ip_hdr_len) { uchar_t *rptr; uint32_t seg_len; tcph_t *tcph; uint32_t seg_seq; uint32_t seg_ack; uint_t flags; rptr = mp->b_rptr; tcph = (tcph_t *)&rptr[ip_hdr_len]; seg_seq = BE32_TO_U32(tcph->th_seq); seg_ack = BE32_TO_U32(tcph->th_ack); flags = tcph->th_flags[0]; seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len); if (flags & TH_RST) { freeb(mp); } else if (flags & TH_ACK) { tcp_xmit_early_reset("no tcp, reset", sock_id, mp, seg_ack, 0, TH_RST, ip_hdr_len); } else { if (flags & TH_SYN) seg_len++; tcp_xmit_early_reset("no tcp, reset/ack", sock_id, mp, 0, seg_seq + seg_len, TH_RST | TH_ACK, ip_hdr_len); } } /* Non overlapping byte exchanger */ static void tcp_xchg(uchar_t *a, uchar_t *b, int len) { uchar_t uch; while (len-- > 0) { uch = a[len]; a[len] = b[len]; b[len] = uch; } } /* * Generate a reset based on an inbound packet for which there is no active * tcp state that we can find. */ static void tcp_xmit_early_reset(char *str, int sock_id, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len) { struct ip *iph = NULL; ushort_t len; tcph_t *tcph; int i; ipaddr_t addr; mblk_t *new_mp; if (str != NULL) { dprintf("tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, " "flags 0x%x\n", str, seq, ack, ctl); } /* * We skip reversing source route here. * (for now we replace all IP options with EOL) */ iph = (struct ip *)mp->b_rptr; for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++) mp->b_rptr[i] = IPOPT_EOL; /* * Make sure that src address is not a limited broadcast * address. Not all broadcast address checking for the * src address is possible, since we don't know the * netmask of the src addr. * No check for destination address is done, since * IP will not pass up a packet with a broadcast dest address * to TCP. */ if (iph->ip_src.s_addr == INADDR_ANY || iph->ip_src.s_addr == INADDR_BROADCAST) { freemsg(mp); return; } tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len]; if (tcph->th_flags[0] & TH_RST) { freemsg(mp); return; } /* * Now copy the original header to a new buffer. The reason * for doing this is that we need to put extra room before * the header for the MAC layer address. The original mblk * does not have this extra head room. */ len = ip_hdr_len + sizeof (tcph_t); if ((new_mp = allocb(len + tcp_wroff_xtra, 0)) == NULL) { freemsg(mp); return; } new_mp->b_rptr += tcp_wroff_xtra; bcopy(mp->b_rptr, new_mp->b_rptr, len); new_mp->b_wptr = new_mp->b_rptr + len; freemsg(mp); mp = new_mp; iph = (struct ip *)mp->b_rptr; tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len]; tcph->th_offset_and_rsrvd[0] = (5 << 4); tcp_xchg(tcph->th_fport, tcph->th_lport, 2); U32_TO_BE32(ack, tcph->th_ack); U32_TO_BE32(seq, tcph->th_seq); U16_TO_BE16(0, tcph->th_win); bzero(tcph->th_sum, sizeof (int16_t)); tcph->th_flags[0] = (uint8_t)ctl; if (ctl & TH_RST) { BUMP_MIB(tcp_mib.tcpOutRsts); BUMP_MIB(tcp_mib.tcpOutControl); } iph->ip_len = htons(len); /* Swap addresses */ addr = iph->ip_src.s_addr; iph->ip_src = iph->ip_dst; iph->ip_dst.s_addr = addr; iph->ip_id = 0; iph->ip_ttl = 0; tcp_set_cksum(mp); iph->ip_ttl = (uint8_t)tcp_ipv4_ttl; /* Dump the packet when debugging. */ TCP_DUMP_PACKET("tcp_xmit_early_reset", mp); (void) ipv4_tcp_output(sock_id, mp); freemsg(mp); } static void tcp_set_cksum(mblk_t *mp) { struct ip *iph; tcpha_t *tcph; int len; iph = (struct ip *)mp->b_rptr; tcph = (tcpha_t *)(iph + 1); len = ntohs(iph->ip_len); /* * Calculate the TCP checksum. Need to include the psuedo header, * which is similar to the real IP header starting at the TTL field. */ iph->ip_sum = htons(len - IP_SIMPLE_HDR_LENGTH); tcph->tha_sum = 0; tcph->tha_sum = tcp_cksum((uint16_t *)&(iph->ip_ttl), len - IP_SIMPLE_HDR_LENGTH + 12); iph->ip_sum = 0; } static uint16_t tcp_cksum(uint16_t *buf, uint32_t len) { /* * Compute Internet Checksum for "count" bytes * beginning at location "addr". */ int32_t sum = 0; while (len > 1) { /* This is the inner loop */ sum += *buf++; len -= 2; } /* Add left-over byte, if any */ if (len > 0) sum += *(unsigned char *)buf * 256; /* Fold 32-bit sum to 16 bits */ while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); return ((uint16_t)~sum); } /* * Type three generator adapted from the random() function in 4.4 BSD: */ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* Type 3 -- x**31 + x**3 + 1 */ #define DEG_3 31 #define SEP_3 3 /* Protected by tcp_random_lock */ static int tcp_randtbl[DEG_3 + 1]; static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1]; static int *tcp_random_rptr = &tcp_randtbl[1]; static int *tcp_random_state = &tcp_randtbl[1]; static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1]; static void tcp_random_init(void) { int i; uint32_t hrt; uint32_t wallclock; uint32_t result; /* * * XXX We don't have high resolution time in standalone... The * following is just some approximation on the comment below. * * Use high-res timer and current time for seed. Gethrtime() returns * a longlong, which may contain resolution down to nanoseconds. * The current time will either be a 32-bit or a 64-bit quantity. * XOR the two together in a 64-bit result variable. * Convert the result to a 32-bit value by multiplying the high-order * 32-bits by the low-order 32-bits. * * XXX We don't have gethrtime() in prom and the wallclock.... */ hrt = prom_gettime(); wallclock = (uint32_t)time(NULL); result = wallclock ^ hrt; tcp_random_state[0] = result; for (i = 1; i < DEG_3; i++) tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1] + 12345; tcp_random_fptr = &tcp_random_state[SEP_3]; tcp_random_rptr = &tcp_random_state[0]; for (i = 0; i < 10 * DEG_3; i++) (void) tcp_random(); } /* * tcp_random: Return a random number in the range [1 - (128K + 1)]. * This range is selected to be approximately centered on TCP_ISS / 2, * and easy to compute. We get this value by generating a 32-bit random * number, selecting out the high-order 17 bits, and then adding one so * that we never return zero. */ static int tcp_random(void) { int i; *tcp_random_fptr += *tcp_random_rptr; /* * The high-order bits are more random than the low-order bits, * so we select out the high-order 17 bits and add one so that * we never return zero. */ i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1; if (++tcp_random_fptr >= tcp_random_end_ptr) { tcp_random_fptr = tcp_random_state; ++tcp_random_rptr; } else if (++tcp_random_rptr >= tcp_random_end_ptr) tcp_random_rptr = tcp_random_state; return (i); } /* * Generate ISS, taking into account NDD changes may happen halfway through. * (If the iss is not zero, set it.) */ static void tcp_iss_init(tcp_t *tcp) { tcp_iss_incr_extra += (ISS_INCR >> 1); tcp->tcp_iss = tcp_iss_incr_extra; tcp->tcp_iss += (prom_gettime() >> ISS_NSEC_SHT) + tcp_random(); tcp->tcp_valid_bits = TCP_ISS_VALID; tcp->tcp_fss = tcp->tcp_iss - 1; tcp->tcp_suna = tcp->tcp_iss; tcp->tcp_snxt = tcp->tcp_iss + 1; tcp->tcp_rexmit_nxt = tcp->tcp_snxt; tcp->tcp_csuna = tcp->tcp_snxt; } /* * Diagnostic routine used to return a string associated with the tcp state. * Note that if the caller does not supply a buffer, it will use an internal * static string. This means that if multiple threads call this function at * the same time, output can be corrupted... Note also that this function * does not check the size of the supplied buffer. The caller has to make * sure that it is big enough. */ static char * tcp_display(tcp_t *tcp, char *sup_buf, char format) { char buf1[30]; static char priv_buf[INET_ADDRSTRLEN * 2 + 80]; char *buf; char *cp; char local_addrbuf[INET_ADDRSTRLEN]; char remote_addrbuf[INET_ADDRSTRLEN]; struct in_addr addr; if (sup_buf != NULL) buf = sup_buf; else buf = priv_buf; if (tcp == NULL) return ("NULL_TCP"); switch (tcp->tcp_state) { case TCPS_CLOSED: cp = "TCP_CLOSED"; break; case TCPS_IDLE: cp = "TCP_IDLE"; break; case TCPS_BOUND: cp = "TCP_BOUND"; break; case TCPS_LISTEN: cp = "TCP_LISTEN"; break; case TCPS_SYN_SENT: cp = "TCP_SYN_SENT"; break; case TCPS_SYN_RCVD: cp = "TCP_SYN_RCVD"; break; case TCPS_ESTABLISHED: cp = "TCP_ESTABLISHED"; break; case TCPS_CLOSE_WAIT: cp = "TCP_CLOSE_WAIT"; break; case TCPS_FIN_WAIT_1: cp = "TCP_FIN_WAIT_1"; break; case TCPS_CLOSING: cp = "TCP_CLOSING"; break; case TCPS_LAST_ACK: cp = "TCP_LAST_ACK"; break; case TCPS_FIN_WAIT_2: cp = "TCP_FIN_WAIT_2"; break; case TCPS_TIME_WAIT: cp = "TCP_TIME_WAIT"; break; default: (void) sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state); cp = buf1; break; } switch (format) { case DISP_ADDR_AND_PORT: /* * Note that we use the remote address in the tcp_b * structure. This means that it will print out * the real destination address, not the next hop's * address if source routing is used. */ addr.s_addr = tcp->tcp_bound_source; bcopy(inet_ntoa(addr), local_addrbuf, sizeof (local_addrbuf)); addr.s_addr = tcp->tcp_remote; bcopy(inet_ntoa(addr), remote_addrbuf, sizeof (remote_addrbuf)); (void) snprintf(buf, sizeof (priv_buf), "[%s.%u, %s.%u] %s", local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf, ntohs(tcp->tcp_fport), cp); break; case DISP_PORT_ONLY: default: (void) snprintf(buf, sizeof (priv_buf), "[%u, %u] %s", ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp); break; } return (buf); } /* * Add a new piece to the tcp reassembly queue. If the gap at the beginning * is filled, return as much as we can. The message passed in may be * multi-part, chained using b_cont. "start" is the starting sequence * number for this piece. */ static mblk_t * tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start) { uint32_t end; mblk_t *mp1; mblk_t *mp2; mblk_t *next_mp; uint32_t u1; /* Walk through all the new pieces. */ do { assert((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX); end = start + (int)(mp->b_wptr - mp->b_rptr); next_mp = mp->b_cont; if (start == end) { /* Empty. Blast it. */ freeb(mp); continue; } mp->b_cont = NULL; TCP_REASS_SET_SEQ(mp, start); TCP_REASS_SET_END(mp, end); mp1 = tcp->tcp_reass_tail; if (!mp1) { tcp->tcp_reass_tail = mp; tcp->tcp_reass_head = mp; BUMP_MIB(tcp_mib.tcpInDataUnorderSegs); UPDATE_MIB(tcp_mib.tcpInDataUnorderBytes, end - start); continue; } /* New stuff completely beyond tail? */ if (SEQ_GEQ(start, TCP_REASS_END(mp1))) { /* Link it on end. */ mp1->b_cont = mp; tcp->tcp_reass_tail = mp; BUMP_MIB(tcp_mib.tcpInDataUnorderSegs); UPDATE_MIB(tcp_mib.tcpInDataUnorderBytes, end - start); continue; } mp1 = tcp->tcp_reass_head; u1 = TCP_REASS_SEQ(mp1); /* New stuff at the front? */ if (SEQ_LT(start, u1)) { /* Yes... Check for overlap. */ mp->b_cont = mp1; tcp->tcp_reass_head = mp; tcp_reass_elim_overlap(tcp, mp); continue; } /* * The new piece fits somewhere between the head and tail. * We find our slot, where mp1 precedes us and mp2 trails. */ for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) { u1 = TCP_REASS_SEQ(mp2); if (SEQ_LEQ(start, u1)) break; } /* Link ourselves in */ mp->b_cont = mp2; mp1->b_cont = mp; /* Trim overlap with following mblk(s) first */ tcp_reass_elim_overlap(tcp, mp); /* Trim overlap with preceding mblk */ tcp_reass_elim_overlap(tcp, mp1); } while (start = end, mp = next_mp); mp1 = tcp->tcp_reass_head; /* Anything ready to go? */ if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt) return (NULL); /* Eat what we can off the queue */ for (;;) { mp = mp1->b_cont; end = TCP_REASS_END(mp1); TCP_REASS_SET_SEQ(mp1, 0); TCP_REASS_SET_END(mp1, 0); if (!mp) { tcp->tcp_reass_tail = NULL; break; } if (end != TCP_REASS_SEQ(mp)) { mp1->b_cont = NULL; break; } mp1 = mp; } mp1 = tcp->tcp_reass_head; tcp->tcp_reass_head = mp; return (mp1); } /* Eliminate any overlap that mp may have over later mblks */ static void tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp) { uint32_t end; mblk_t *mp1; uint32_t u1; end = TCP_REASS_END(mp); while ((mp1 = mp->b_cont) != NULL) { u1 = TCP_REASS_SEQ(mp1); if (!SEQ_GT(end, u1)) break; if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) { mp->b_wptr -= end - u1; TCP_REASS_SET_END(mp, u1); BUMP_MIB(tcp_mib.tcpInDataPartDupSegs); UPDATE_MIB(tcp_mib.tcpInDataPartDupBytes, end - u1); break; } mp->b_cont = mp1->b_cont; freeb(mp1); BUMP_MIB(tcp_mib.tcpInDataDupSegs); UPDATE_MIB(tcp_mib.tcpInDataDupBytes, end - u1); } if (!mp1) tcp->tcp_reass_tail = mp; } /* * Remove a connection from the list of detached TIME_WAIT connections. */ static void tcp_time_wait_remove(tcp_t *tcp) { if (tcp->tcp_time_wait_expire == 0) { assert(tcp->tcp_time_wait_next == NULL); assert(tcp->tcp_time_wait_prev == NULL); return; } assert(tcp->tcp_state == TCPS_TIME_WAIT); if (tcp == tcp_time_wait_head) { assert(tcp->tcp_time_wait_prev == NULL); tcp_time_wait_head = tcp->tcp_time_wait_next; if (tcp_time_wait_head != NULL) { tcp_time_wait_head->tcp_time_wait_prev = NULL; } else { tcp_time_wait_tail = NULL; } } else if (tcp == tcp_time_wait_tail) { assert(tcp != tcp_time_wait_head); assert(tcp->tcp_time_wait_next == NULL); tcp_time_wait_tail = tcp->tcp_time_wait_prev; assert(tcp_time_wait_tail != NULL); tcp_time_wait_tail->tcp_time_wait_next = NULL; } else { assert(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp); assert(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp); tcp->tcp_time_wait_prev->tcp_time_wait_next = tcp->tcp_time_wait_next; tcp->tcp_time_wait_next->tcp_time_wait_prev = tcp->tcp_time_wait_prev; } tcp->tcp_time_wait_next = NULL; tcp->tcp_time_wait_prev = NULL; tcp->tcp_time_wait_expire = 0; } /* * Add a connection to the list of detached TIME_WAIT connections * and set its time to expire ... */ static void tcp_time_wait_append(tcp_t *tcp) { tcp->tcp_time_wait_expire = prom_gettime() + tcp_time_wait_interval; if (tcp->tcp_time_wait_expire == 0) tcp->tcp_time_wait_expire = 1; if (tcp_time_wait_head == NULL) { assert(tcp_time_wait_tail == NULL); tcp_time_wait_head = tcp; } else { assert(tcp_time_wait_tail != NULL); assert(tcp_time_wait_tail->tcp_state == TCPS_TIME_WAIT); tcp_time_wait_tail->tcp_time_wait_next = tcp; tcp->tcp_time_wait_prev = tcp_time_wait_tail; } tcp_time_wait_tail = tcp; /* for ndd stats about compression */ tcp_cum_timewait++; } /* * Periodic qtimeout routine run on the default queue. * Performs 2 functions. * 1. Does TIME_WAIT compression on all recently added tcps. List * traversal is done backwards from the tail. * 2. Blows away all tcps whose TIME_WAIT has expired. List traversal * is done forwards from the head. */ void tcp_time_wait_collector(void) { tcp_t *tcp; uint32_t now; /* * In order to reap time waits reliably, we should use a * source of time that is not adjustable by the user */ now = prom_gettime(); while ((tcp = tcp_time_wait_head) != NULL) { /* * Compare times using modular arithmetic, since * lbolt can wrapover. */ if ((int32_t)(now - tcp->tcp_time_wait_expire) < 0) { break; } /* * Note that the err must be 0 as there is no socket * associated with this TCP... */ (void) tcp_clean_death(-1, tcp, 0); } /* Schedule next run time. */ tcp_time_wait_runtime = prom_gettime() + 10000; } void tcp_time_wait_report(void) { tcp_t *tcp; printf("Current time %u\n", prom_gettime()); for (tcp = tcp_time_wait_head; tcp != NULL; tcp = tcp->tcp_time_wait_next) { printf("%s expires at %u\n", tcp_display(tcp, NULL, DISP_ADDR_AND_PORT), tcp->tcp_time_wait_expire); } } /* * Send up all messages queued on tcp_rcv_list. * Have to set tcp_co_norm since we use putnext. */ static void tcp_rcv_drain(int sock_id, tcp_t *tcp) { mblk_t *mp; struct inetgram *in_gram; mblk_t *in_mp; int len; /* Don't drain if the app has not finished reading all the data. */ if (sockets[sock_id].so_rcvbuf <= 0) return; /* We might have come here just to updated the rwnd */ if (tcp->tcp_rcv_list == NULL) goto win_update; if ((in_gram = (struct inetgram *)bkmem_zalloc( sizeof (struct inetgram))) == NULL) { return; } if ((in_mp = allocb(tcp->tcp_rcv_cnt, 0)) == NULL) { bkmem_free((caddr_t)in_gram, sizeof (struct inetgram)); return; } in_gram->igm_level = APP_LVL; in_gram->igm_mp = in_mp; in_gram->igm_id = 0; while ((mp = tcp->tcp_rcv_list) != NULL) { tcp->tcp_rcv_list = mp->b_cont; len = mp->b_wptr - mp->b_rptr; bcopy(mp->b_rptr, in_mp->b_wptr, len); in_mp->b_wptr += len; freeb(mp); } tcp->tcp_rcv_last_tail = NULL; tcp->tcp_rcv_cnt = 0; add_grams(&sockets[sock_id].inq, in_gram); /* This means that so_rcvbuf can be less than 0. */ sockets[sock_id].so_rcvbuf -= in_mp->b_wptr - in_mp->b_rptr; win_update: /* * Increase the receive window to max. But we need to do receiver * SWS avoidance. This means that we need to check the increase of * of receive window is at least 1 MSS. */ if (sockets[sock_id].so_rcvbuf > 0 && (tcp->tcp_rwnd_max - tcp->tcp_rwnd >= tcp->tcp_mss)) { tcp->tcp_rwnd = tcp->tcp_rwnd_max; U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win); } } /* * Wrapper for recvfrom to call */ void tcp_rcv_drain_sock(int sock_id) { tcp_t *tcp; if ((tcp = sockets[sock_id].pcb) == NULL) return; tcp_rcv_drain(sock_id, tcp); } /* * If the inq == NULL and the tcp_rcv_list != NULL, we have data that * recvfrom could read. Place a magic message in the inq to let recvfrom * know that it needs to call tcp_rcv_drain_sock to pullup the data. */ static void tcp_drain_needed(int sock_id, tcp_t *tcp) { struct inetgram *in_gram; #ifdef DEBUG printf("tcp_drain_needed: inq %x, tcp_rcv_list %x\n", sockets[sock_id].inq, tcp->tcp_rcv_list); #endif if ((sockets[sock_id].inq != NULL) || (tcp->tcp_rcv_list == NULL)) return; if ((in_gram = (struct inetgram *)bkmem_zalloc( sizeof (struct inetgram))) == NULL) return; in_gram->igm_level = APP_LVL; in_gram->igm_mp = NULL; in_gram->igm_id = TCP_CALLB_MAGIC_ID; add_grams(&sockets[sock_id].inq, in_gram); } /* * Queue data on tcp_rcv_list which is a b_next chain. * Each element of the chain is a b_cont chain. * * M_DATA messages are added to the current element. * Other messages are added as new (b_next) elements. */ static void tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len) { assert(seg_len == msgdsize(mp)); if (tcp->tcp_rcv_list == NULL) { tcp->tcp_rcv_list = mp; } else { tcp->tcp_rcv_last_tail->b_cont = mp; } while (mp->b_cont) mp = mp->b_cont; tcp->tcp_rcv_last_tail = mp; tcp->tcp_rcv_cnt += seg_len; tcp->tcp_rwnd -= seg_len; #ifdef DEBUG printf("tcp_rcv_enqueue rwnd %d\n", tcp->tcp_rwnd); #endif U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win); } /* The minimum of smoothed mean deviation in RTO calculation. */ #define TCP_SD_MIN 400 /* * Set RTO for this connection. The formula is from Jacobson and Karels' * "Congestion Avoidance and Control" in SIGCOMM '88. The variable names * are the same as those in Appendix A.2 of that paper. * * m = new measurement * sa = smoothed RTT average (8 * average estimates). * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates). */ static void tcp_set_rto(tcp_t *tcp, int32_t rtt) { int32_t m = rtt; uint32_t sa = tcp->tcp_rtt_sa; uint32_t sv = tcp->tcp_rtt_sd; uint32_t rto; BUMP_MIB(tcp_mib.tcpRttUpdate); tcp->tcp_rtt_update++; /* tcp_rtt_sa is not 0 means this is a new sample. */ if (sa != 0) { /* * Update average estimator: * new rtt = 7/8 old rtt + 1/8 Error */ /* m is now Error in estimate. */ m -= sa >> 3; if ((int32_t)(sa += m) <= 0) { /* * Don't allow the smoothed average to be negative. * We use 0 to denote reinitialization of the * variables. */ sa = 1; } /* * Update deviation estimator: * new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev) */ if (m < 0) m = -m; m -= sv >> 2; sv += m; } else { /* * This follows BSD's implementation. So the reinitialized * RTO is 3 * m. We cannot go less than 2 because if the * link is bandwidth dominated, doubling the window size * during slow start means doubling the RTT. We want to be * more conservative when we reinitialize our estimates. 3 * is just a convenient number. */ sa = m << 3; sv = m << 1; } if (sv < TCP_SD_MIN) { /* * We do not know that if sa captures the delay ACK * effect as in a long train of segments, a receiver * does not delay its ACKs. So set the minimum of sv * to be TCP_SD_MIN, which is default to 400 ms, twice * of BSD DATO. That means the minimum of mean * deviation is 100 ms. * */ sv = TCP_SD_MIN; } tcp->tcp_rtt_sa = sa; tcp->tcp_rtt_sd = sv; /* * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv) * * Add tcp_rexmit_interval extra in case of extreme environment * where the algorithm fails to work. The default value of * tcp_rexmit_interval_extra should be 0. * * As we use a finer grained clock than BSD and update * RTO for every ACKs, add in another .25 of RTT to the * deviation of RTO to accomodate burstiness of 1/4 of * window size. */ rto = (sa >> 3) + sv + tcp_rexmit_interval_extra + (sa >> 5); if (rto > tcp_rexmit_interval_max) { tcp->tcp_rto = tcp_rexmit_interval_max; } else if (rto < tcp_rexmit_interval_min) { tcp->tcp_rto = tcp_rexmit_interval_min; } else { tcp->tcp_rto = rto; } /* Now, we can reset tcp_timer_backoff to use the new RTO... */ tcp->tcp_timer_backoff = 0; } /* * Initiate closedown sequence on an active connection. * Return value zero for OK return, non-zero for error return. */ static int tcp_xmit_end(tcp_t *tcp, int sock_id) { mblk_t *mp; if (tcp->tcp_state < TCPS_SYN_RCVD || tcp->tcp_state > TCPS_CLOSE_WAIT) { /* * Invalid state, only states TCPS_SYN_RCVD, * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid */ return (-1); } tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent; tcp->tcp_valid_bits |= TCP_FSS_VALID; /* * If there is nothing more unsent, send the FIN now. * Otherwise, it will go out with the last segment. */ if (tcp->tcp_unsent == 0) { mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, tcp->tcp_fss, B_FALSE, NULL, B_FALSE); if (mp != NULL) { /* Dump the packet when debugging. */ TCP_DUMP_PACKET("tcp_xmit_end", mp); (void) ipv4_tcp_output(sock_id, mp); freeb(mp); } else { /* * Couldn't allocate msg. Pretend we got it out. * Wait for rexmit timeout. */ tcp->tcp_snxt = tcp->tcp_fss + 1; TCP_TIMER_RESTART(tcp, tcp->tcp_rto); } /* * If needed, update tcp_rexmit_snxt as tcp_snxt is * changed. */ if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) { tcp->tcp_rexmit_nxt = tcp->tcp_snxt; } } else { tcp_wput_data(tcp, NULL, B_FALSE); } return (0); } int tcp_opt_set(tcp_t *tcp, int level, int option, const void *optval, socklen_t optlen) { switch (level) { case SOL_SOCKET: { switch (option) { case SO_RCVBUF: if (optlen == sizeof (int)) { int val = *(int *)optval; if (val > tcp_max_buf) { errno = ENOBUFS; break; } /* Silently ignore zero */ if (val != 0) { val = MSS_ROUNDUP(val, tcp->tcp_mss); (void) tcp_rwnd_set(tcp, val); } } else { errno = EINVAL; } break; case SO_SNDBUF: if (optlen == sizeof (int)) { tcp->tcp_xmit_hiwater = *(int *)optval; if (tcp->tcp_xmit_hiwater > tcp_max_buf) tcp->tcp_xmit_hiwater = tcp_max_buf; } else { errno = EINVAL; } break; case SO_LINGER: if (optlen == sizeof (struct linger)) { struct linger *lgr = (struct linger *)optval; if (lgr->l_onoff) { tcp->tcp_linger = 1; tcp->tcp_lingertime = lgr->l_linger; } else { tcp->tcp_linger = 0; tcp->tcp_lingertime = 0; } } else { errno = EINVAL; } break; default: errno = ENOPROTOOPT; break; } break; } /* case SOL_SOCKET */ case IPPROTO_TCP: { switch (option) { default: errno = ENOPROTOOPT; break; } break; } /* case IPPROTO_TCP */ case IPPROTO_IP: { switch (option) { default: errno = ENOPROTOOPT; break; } break; } /* case IPPROTO_IP */ default: errno = ENOPROTOOPT; break; } /* switch (level) */ if (errno != 0) return (-1); else return (0); } /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * Copyright (c) 1982, 1986 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #ifndef _TCP_INET_H #define _TCP_INET_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include "tcp_sack.h" /* TCP states */ #define TCPS_ALL_ACKED -7 /* Internal state for retransmissions */ #define TCPS_CLOSED -6 #define TCPS_IDLE -5 /* idle (opened, but not bound) */ #define TCPS_BOUND -4 /* bound, ready to connect or accept */ #define TCPS_LISTEN -3 /* listening for connection */ #define TCPS_SYN_SENT -2 /* active, have sent syn */ #define TCPS_SYN_RCVD -1 /* have received syn (and sent ours) */ /* states < TCPS_ESTABLISHED are those where connections not established */ #define TCPS_ESTABLISHED 0 /* established */ #define TCPS_CLOSE_WAIT 1 /* rcvd fin, waiting for close */ /* states > TCPS_CLOSE_WAIT are those where user has closed */ #define TCPS_FIN_WAIT_1 2 /* have closed and sent fin */ #define TCPS_CLOSING 3 /* closed, xchd FIN, await FIN ACK */ #define TCPS_LAST_ACK 4 /* had fin and close; await FIN ACK */ /* states > TCPS_CLOSE_WAIT && < TCPS_FIN_WAIT_2 await ACK of FIN */ #define TCPS_FIN_WAIT_2 5 /* have closed, fin is acked */ #define TCPS_TIME_WAIT 6 /* in 2*msl quiet wait after close */ /* * Internal flags used in conjunction with the packet header flags. * Used in tcp_rput_data to keep track of what needs to be done. */ #define TH_LIMIT_XMIT 0x0400 /* Limited xmit is needed */ #define TH_XMIT_NEEDED 0x0800 /* Window opened - send queued data */ #define TH_REXMIT_NEEDED 0x1000 /* Time expired for unacked data */ #define TH_ACK_NEEDED 0x2000 /* Send an ack now. */ #define TH_NEED_SACK_REXMIT 0x4000 /* Use SACK info to retransmission */ #define TH_TIMER_NEEDED 0x8000 /* Start the delayed ack/push bit timer */ /* * Special Magic number used by TCP to issue a callback to recvfrom() in the * form of a dummy inetgram. */ #define TCP_CALLB_MAGIC_ID 0xFFFF /* * TCP sequence numbers are 32 bit integers operated * on with modular arithmetic. These macros can be * used to compare such integers. */ #define SEQ_LT(a, b) ((int32_t)((a)-(b)) < 0) #define SEQ_LEQ(a, b) ((int32_t)((a)-(b)) <= 0) #define SEQ_GT(a, b) ((int32_t)((a)-(b)) > 0) #define SEQ_GEQ(a, b) ((int32_t)((a)-(b)) >= 0) /* TCP Protocol header */ typedef struct tcphdr_s { uint8_t th_lport[2]; /* Source port */ uint8_t th_fport[2]; /* Destination port */ uint8_t th_seq[4]; /* Sequence number */ uint8_t th_ack[4]; /* Acknowledgement number */ uint8_t th_offset_and_rsrvd[1]; /* Offset to the packet data */ uint8_t th_flags[1]; uint8_t th_win[2]; /* Allocation number */ uint8_t th_sum[2]; /* TCP checksum */ uint8_t th_urp[2]; /* Urgent pointer */ } tcph_t; #define TCP_HDR_LENGTH(tcph) (((tcph)->th_offset_and_rsrvd[0] >>2) &(0xF << 2)) #define TCP_MAX_COMBINED_HEADER_LENGTH (60 + 60) /* Maxed out ip + tcp */ #define TCP_MAX_IP_OPTIONS_LENGTH (60 - IP_SIMPLE_HDR_LENGTH) #define TCP_MAX_HDR_LENGTH 60 #define TCP_MAX_TCP_OPTIONS_LENGTH (60 - sizeof (tcph_t)) #define TCP_MIN_HEADER_LENGTH 20 #define TCP_MAXWIN 65535 #define TCP_PORT_LEN sizeof (in_port_t) #define TCP_MAX_WINSHIFT 14 #define TCP_MAX_LARGEWIN (TCP_MAXWIN << TCP_MAX_WINSHIFT) #define TCPIP_HDR_LENGTH(mp, n) \ (n) = IPH_HDR_LENGTH((mp)->b_rptr), \ (n) += TCP_HDR_LENGTH((tcph_t *)&(mp)->b_rptr[(n)]) /* TCP Protocol header (used if the header is known to be 32-bit aligned) */ typedef struct tcphdra_s { in_port_t tha_lport; /* Source port */ in_port_t tha_fport; /* Destination port */ uint32_t tha_seq; /* Sequence number */ uint32_t tha_ack; /* Acknowledgement number */ uint8_t tha_offset_and_reserved; /* Offset to the packet data */ uint8_t tha_flags; uint16_t tha_win; /* Allocation number */ uint16_t tha_sum; /* TCP checksum */ uint16_t tha_urp; /* Urgent pointer */ } tcpha_t; typedef struct tcp_s { struct tcp_s *tcp_time_wait_next; /* Next TCP in TIME_WAIT list */ struct tcp_s *tcp_time_wait_prev; /* Prev TCP in TIME_WAIT list */ uint32_t tcp_max_swnd; /* Maximum swnd we have seen */ uint32_t tcp_suna; /* Sender unacknowledged */ uint32_t tcp_csuna; /* Clear (no rexmits in window) suna */ uint32_t tcp_snxt; /* Senders next seq num */ uint32_t tcp_swnd; /* Senders window (relative to suna) */ uint32_t tcp_mss; /* Max segment size */ uint32_t tcp_iss; /* Initial send seq num */ uint32_t tcp_rnxt; /* Seq we expect to recv next */ uint32_t tcp_rwnd; /* Current receive window */ uint32_t tcp_rwnd_max; /* Max receive window */ uint32_t tcp_irs; /* Initial recv seq num */ uint32_t tcp_fss; /* Final/fin send seq num */ uint32_t tcp_swl1; /* These help us avoid using stale */ uint32_t tcp_swl2; /* packets to update state */ uint32_t tcp_cwnd; /* Congestion window */ int32_t tcp_cwnd_cnt; /* cwnd cnt in congestion avoidance */ uint32_t tcp_cwnd_ssthresh; /* Congestion window */ uint32_t tcp_cwnd_max; int32_t tcp_snd_burst; /* Send burst factor */ int32_t tcp_state; int32_t tcp_rcv_ws; /* My window scale power */ int32_t tcp_snd_ws; /* Sender's window scale power */ uint32_t tcp_ts_recent; /* Timestamp of earliest unacked */ /* data segment */ uint32_t tcp_if_mtu; /* Outgoing interface MTU. */ uint32_t tcp_rtt_sa; /* Round trip smoothed average */ uint32_t tcp_rtt_sd; /* Round trip smoothed deviation */ uint32_t tcp_rtt_update; /* Round trip update(s) */ uint32_t tcp_ms_we_have_waited; /* Total retrans time */ uint32_t tcp_rto; /* Round trip timeout */ uint32_t tcp_rto_timeout; /* RTT timeout time */ uint32_t tcp_time_wait_expire; /* time in hz when t/w expires */ uint32_t tcp_last_rcv_lbolt; /* lbolt on last packet, used for PAWS */ int tcp_lingertime; /* Close linger time (in seconds) */ uint32_t tcp_first_timer_threshold; /* When to prod IP */ uint32_t tcp_second_timer_threshold; /* When to give up completely */ uint32_t tcp_first_ctimer_threshold; /* 1st threshold when connecting */ uint32_t tcp_second_ctimer_threshold; /* 2nd ... while connecting */ uint32_t tcp_rexmit_nxt; /* Next rexmit seq num */ uint32_t tcp_rexmit_max; /* Max retran seq num */ uint32_t tcp_naglim; /* Tunable nagle limit */ uint32_t tcp_valid_bits; #define TCP_ISS_VALID 0x1 /* Is the tcp_iss seq num active? */ #define TCP_FSS_VALID 0x2 /* Is the tcp_fss seq num active? */ #define TCP_URG_VALID 0x4 /* Is the tcp_urg seq num active? */ #define TCP_OFO_FIN_VALID 0x8 /* Has TCP received an out of order FIN? */ int32_t tcp_xmit_hiwater; /* Send buffer high water mark. */ int32_t tcp_xmit_lowater; /* Send buffer low water mark. */ uchar_t tcp_timer_backoff; /* Backoff shift count. */ uint32_t tcp_last_recv_time; /* Last time we receive a segment. */ /* Fields arranged in approximate access order along main paths */ mblk_t *tcp_xmit_head; /* Head of rexmit list */ mblk_t *tcp_xmit_last; /* last valid data seen by tcp_wput */ uint32_t tcp_unsent; /* # of bytes in hand that are unsent */ mblk_t *tcp_xmit_tail; /* Last rexmit data sent */ uint32_t tcp_xmit_tail_unsent; /* # of unsent bytes in xmit_tail */ mblk_t *tcp_rcv_list; /* Queued until push or exceed */ mblk_t *tcp_rcv_last_tail; /* tcp_rcv_push_wait. */ uint32_t tcp_rcv_cnt; /* tcp_rcv_list is b_next chain. */ uint32_t tcp_rack; /* Seq # we have acked */ uint32_t tcp_rack_cnt; /* # of bytes we have deferred ack */ mblk_t *tcp_reass_head; /* Out of order reassembly list head */ mblk_t *tcp_reass_tail; /* Out of order reassembly list tail */ tcp_sack_info_t *tcp_sack_info; #define tcp_pipe tcp_sack_info->tcp_pipe #define tcp_fack tcp_sack_info->tcp_fack #define tcp_sack_snxt tcp_sack_info->tcp_sack_snxt #define tcp_max_sack_blk tcp_sack_info->tcp_max_sack_blk #define tcp_num_sack_blk tcp_sack_info->tcp_num_sack_blk #define tcp_sack_list tcp_sack_info->tcp_sack_list #define tcp_num_notsack_blk tcp_sack_info->tcp_num_notsack_blk #define tcp_cnt_notsack_list tcp_sack_info->tcp_cnt_notsack_list #define tcp_notsack_list tcp_sack_info->tcp_notsack_list int tcp_conn_req_cnt_q0; /* # of conn reqs in SYN_RCVD */ int tcp_conn_req_cnt_q; /* # of conn reqs in ESTABLISHED */ int tcp_conn_req_max; /* # of ESTABLISHED conn reqs allowed */ int tcp_iphc_len; /* actual allocated buffer size */ int32_t tcp_hdr_len; /* Byte len of combined TCP/IP hdr */ struct ip *tcp_ipha; /* IPv4 header in the buffer */ int tcp_ip_hdr_len; /* Byte len of our current IPvx hdr */ tcph_t *tcp_tcph; /* tcp header within combined hdr */ int32_t tcp_tcp_hdr_len; /* tcp header len within combined */ uint16_t tcp_last_sent_len; /* Record length for nagle */ uint16_t tcp_dupack_cnt; /* # of consequtive duplicate acks */ /* * Address family that app wishes returned addrsses to be in. * Currently taken from address family used in T_BIND_REQ, but * should really come from family used in original socket() call. * Value can be AF_INET or AF_INET6. */ uint_t tcp_family; uint32_t tcp_ofo_fin_seq; /* Recv out of order FIN seq num */ uint32_t tcp_cwr_snd_max; uint32_t tcp_fin_acked : 1, /* Has our FIN been acked? */ tcp_fin_rcvd : 1, /* Have we seen a FIN? */ tcp_fin_sent : 1, /* Have we sent our FIN yet? */ tcp_useloopback : 1, /* SO_USELOOPBACK "socket" option. */ tcp_conn_def_q0: 1, /* move from q0 to q deferred */ tcp_zero_win_probe: 1, /* Zero win probing is in progress */ tcp_set_timer : 1, tcp_active_open: 1, /* This is a active open */ tcp_timer_running: 1, /* Retransmission timer running */ tcp_rexmit : 1, /* TCP is retransmitting */ tcp_snd_sack_ok : 1, /* Can use SACK for this connection */ tcp_ecn_ok : 1, /* Can use ECN for this connection */ tcp_ecn_echo_on : 1, /* Need to do ECN echo */ tcp_ecn_cwr_sent : 1, /* ECN_CWR has been sent */ tcp_cwr : 1, /* Cwnd has reduced recently */ tcp_snd_ts_ok : 1, tcp_snd_ws_ok : 1, tcp_linger : 1, tcp_dontdrop : 1, tcp_junk_fill_thru_bit_31 : 13; char *tcp_iphc; /* Buffer holding tcp/ip hdr template */ in_addr_t tcp_remote; /* true remote address - needed for */ /* source routing. */ in_addr_t tcp_bound_source; /* IP address in bind_req */ /* * These fields contain the same information as tcp_tcph->th_*port. * However, the lookup functions can not use the header fields * since during IP option manipulation the tcp_tcph pointer * changes. */ union { struct { in_port_t tcpu_fport; /* Remote port */ in_port_t tcpu_lport; /* Local port */ } tcpu_ports1; uint32_t tcpu_ports2; /* Rem port, */ /* local port */ /* Used for TCP_MATCH performance */ } tcp_tcpu; #define tcp_fport tcp_tcpu.tcpu_ports1.tcpu_fport #define tcp_lport tcp_tcpu.tcpu_ports1.tcpu_lport #define tcp_ports tcp_tcpu.tcpu_ports2 /* * IP format that packets transmitted from this struct should use. * Value can be IPV4_VERSION or IPV6_VERSION. Determines whether * IP+TCP header template above stores an IPv4 or IPv6 header. */ ushort_t tcp_ipversion; int tcp_client_errno; struct tcp_s *tcp_eager_next_q; /* next eager in ESTABLISHED state */ struct tcp_s *tcp_eager_last_q; /* last eager in ESTABLISHED state */ struct tcp_s *tcp_eager_next_q0; /* next eager in SYN_RCVD state */ struct tcp_s *tcp_eager_prev_q0; /* prev eager in SYN_RCVD state */ struct tcp_s *tcp_listener; /* Our listener */ } tcp_t; /* External TCP functions. */ extern void tcp_socket_init(struct inetboot_socket *); extern int tcp_connect(int); extern int tcp_listen(int, int); extern int tcp_bind(int); extern int tcp_send(int, tcp_t *, const void *, int); extern int tcp_opt_set(tcp_t *, int, int, const void *, socklen_t); extern int tcp_accept(int, struct sockaddr *, socklen_t *); extern int tcp_shutdown(int); /* Exported for recvfrom */ extern void tcp_rcv_drain_sock(int); /* Exported for stand/lib/sock/sock_test.c */ extern void tcp_time_wait_report(void); #ifdef __cplusplus } #endif #endif /* _TCP_INET_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1997-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" /* Modified to be used by inetboot. */ #include #include #include #include #include #include #include #include #include #include #include #include "tcp_inet.h" #include "tcp_sack.h" /* * To insert a new blk to the array of SACK blk in receiver. * * Parameters: * sack_blk_t *head: pointer to the array of SACK blks. * tcp_seq begin: starting seq num of the new blk. * tcp_seq end: ending seq num of the new blk. * int32_t *num: (referenced) total num of SACK blks on the list. */ void tcp_sack_insert(sack_blk_t *head, tcp_seq begin, tcp_seq end, int32_t *num) { int32_t i, j, old_num, new_num; sack_blk_t tmp[MAX_SACK_BLK - 1]; /* The array is empty, just add the new one. */ if (*num == 0) { head[0].begin = begin; head[0].end = end; *num = 1; return; } /* * Check for overlap. There are five cases. * * 1. there is no overlap with any other SACK blks. * 2. new SACK blk is completely contained in another blk. * 3. tail part of new SACK blk overlaps with another blk. * 4. head part of new SACK blk overlaps with another blk. * 5. new SACK blk completely contains another blk. * * Use tmp to hold old SACK blks. After the loop, copy them back * to head. */ old_num = *num; if (old_num > MAX_SACK_BLK - 1) { old_num = MAX_SACK_BLK - 1; } new_num = old_num; j = 0; for (i = 0; i < old_num; i++) { if (SEQ_LT(end, head[i].begin) || SEQ_GT(begin, head[i].end)) { /* Case 1: continue to check. */ tmp[j].begin = head[i].begin; tmp[j].end = head[i].end; j++; continue; } else if (SEQ_GEQ(begin, head[i].begin) && SEQ_LEQ(end, head[i].end)) { /* Case 2: re-insert the old blk to the head. */ begin = head[i].begin; end = head[i].end; } else if (SEQ_LEQ(end, head[i].end) && SEQ_GEQ(end, head[i].begin)) { /* * Case 3: Extend the new blk, remove the old one * and continue to check. */ end = head[i].end; } else if (SEQ_GEQ(begin, head[i].begin) && SEQ_LEQ(begin, head[i].end)) { /* Case 4 */ begin = head[i].begin; } /* * Common code for all cases except the first one, which * copies the original SACK blk into the tmp storage. Other * cases remove the original SACK blk by not copying into * tmp storage. */ new_num--; } head[0].begin = begin; head[0].end = end; for (i = 0; i < new_num; i++) { head[i+1].begin = tmp[i].begin; head[i+1].end = tmp[i].end; } *num = new_num + 1; } /* * To remove a SACK block. * * Parameters: * sack_blk_t *head: pointer to the array of SACK blks. * tcp_seq end: to remove all sack blk with seq num less than end. * int32_t *num: (referenced) total num of SACK blks in the array. */ void tcp_sack_remove(sack_blk_t *head, tcp_seq end, int32_t *num) { sack_blk_t tmp[MAX_SACK_BLK]; int32_t i, j, old_num, new_num; if (*num == 0) return; old_num = *num; new_num = old_num; j = 0; /* Walk thru the whole list and copy the new list to tmp[]. */ for (i = 0; i < old_num; i++) { if (SEQ_GT(end, head[i].begin)) { /* * Check to see if the old SACK blk needs to be * removed or updated. If the old blk is just * partially covered, update begin and continue. * If the old blk is completely covered, remove it * and continue to check. */ if (SEQ_GEQ(end, head[i].end)) { new_num--; continue; } else { tmp[j].begin = end; tmp[j].end = head[i].end; } } else { tmp[j].begin = head[i].begin; tmp[j].end = head[i].end; } j++; } /* Copy tmp[] back to the original list. */ for (i = 0; i < new_num; i++) { head[i].begin = tmp[i].begin; head[i].end = tmp[i].end; } *num = new_num; } /* * Use the SACK info to insert a "notsack'ed" blk. The notsack'ed blk list * contains the list of blks which have not been selectively acknowledged * by the receiver. The SACK info is a blk which is being selectively * acknowledged by the receiver. * * Parameters: * notsack_blk_t **head: address of the pointer to the list of notsack'ed * blks. * tcp_seq begin: starting seq num of the SACK info. * tcp_seq end: ending seq num of the SACK info. * int32_t *num: (referenced) total num of notsack'ed blk on the list. * uint32_t *sum: (referenced) total num of bytes of all the notsack'ed * blks. */ void tcp_notsack_insert(notsack_blk_t **head, tcp_seq begin, tcp_seq end, int32_t *num, uint32_t *sum) { notsack_blk_t *prev, *tmp, *new; uint32_t tmp_sum, tmp_num; if (*head == NULL) { return; } tmp = *head; prev = NULL; /* Find the right place of updating the list. */ while ((tmp != NULL) && SEQ_LEQ(tmp->end, begin)) { prev = tmp; (tmp->sack_cnt)++; tmp = tmp->next; } /* * This can happen only when TCP sends new data but the notsack list * is not updated. */ if (tmp == NULL) { return; } /* * This means the new SACK info covers something that is not on * the list anymore. */ if (SEQ_LEQ(end, tmp->begin)) { return; } /* The SACK info covers up to this blk. So just check for this blk. */ if (SEQ_LEQ(end, tmp->end)) { /* * Only this notsack'ed blk is completely covered. Delete * it and return. */ if (end == tmp->end && SEQ_LEQ(begin, tmp->begin)) { if (prev != NULL) { prev->next = tmp->next; } else { *head = tmp->next; } (*num)--; *sum -= tmp->end - tmp->begin; bkmem_free(tmp, sizeof (notsack_blk_t)); return; } /* This blk is partially covered. */ if (SEQ_GEQ(begin, tmp->begin)) { /* Check what needs to be updated. */ if (begin == tmp->begin) { *sum -= end - tmp->begin; tmp->begin = end; } else if (end == tmp->end) { *sum -= tmp->end - begin; tmp->end = begin; (tmp->sack_cnt)++; } else { /* Split the notsack blk. */ if ((new = (notsack_blk_t *)bkmem_alloc( sizeof (notsack_blk_t))) == NULL) { return; } new->end = tmp->end; new->begin = end; new->next = tmp->next; new->sack_cnt = 0; tmp->end = begin; tmp->next = new; (tmp->sack_cnt)++; (*num)++; *sum -= end - begin; } } else { *sum -= end - tmp->begin; tmp->begin = end; } return; } /* Need to check for coverage of this blk and later blks. */ tmp_sum = *sum; tmp_num = *num; if (SEQ_LT(tmp->begin, begin)) { tmp_sum -= tmp->end - begin; tmp->end = begin; (tmp->sack_cnt)++; prev = tmp; tmp = tmp->next; } while (tmp != NULL) { /* The coverage stops here. */ if (SEQ_GT(tmp->begin, end)) { break; } else { /* Is the blk completely or partially covered? */ if (SEQ_LEQ(tmp->end, end)) { tmp_num--; tmp_sum -= tmp->end - tmp->begin; if (prev != NULL) { prev->next = tmp->next; bkmem_free((caddr_t)tmp, sizeof (notsack_blk_t)); tmp = prev->next; } else { *head = tmp->next; bkmem_free((caddr_t)tmp, sizeof (notsack_blk_t)); tmp = *head; } } else { /* * This blk is partially covered. It also * means it should be the end of coverage. */ tmp_sum -= end - tmp->begin; tmp->begin = end; break; } } } *num = tmp_num; *sum = tmp_sum; } /* * To remove notsack'ed blks. * * Parameters: * notsack_blk_t **head: address of the pointer to the list of notsack'ed * blks. * tcp_seq end: to remove all notsack'ed blk with seq num less than end. * int32_t *num: (referenced) total num of notsack'ed blks. * uint32_t *sum: (referenced) total num of bytes of all the notsack'ed * blks. */ void tcp_notsack_remove(notsack_blk_t **head, tcp_seq end, int32_t *num, uint32_t *sum) { notsack_blk_t *prev, *tmp; uint32_t tmp_sum = *sum; if (*head == NULL) return; prev = NULL; tmp = *head; while (tmp != NULL) { /* There is nothing to discard. */ if (SEQ_GT(tmp->begin, end)) { break; } /* Is the blk completely or partially covered? */ if (SEQ_GEQ(end, tmp->end)) { (*num)--; tmp_sum -= tmp->end - tmp->begin; if (prev == NULL) { *head = tmp->next; bkmem_free((caddr_t)tmp, sizeof (notsack_blk_t)); tmp = *head; } else { prev->next = tmp->next; bkmem_free((caddr_t)tmp, sizeof (notsack_blk_t)); tmp = tmp->next; } } else { tmp_sum -= end - tmp->begin; tmp->begin = end; break; } } *sum = tmp_sum; } /* * To update the notsack'ed list when new data is sent. * * Assumption: this should only be called when new notsack blk is to be added. * * Parameters: * notsack_blk_t **head: address of the pointer to the list of notsack'ed * blks. * tcp_seq begin: beginning seq num of new data. * tcp_seq end: ending seq num of new data. * int32_t *num: (referenced) total num of notsack'ed blks. * uint32_t *sum: (referenced) total num of bytes of all the notsack'ed * blks. */ void tcp_notsack_update(notsack_blk_t **head, tcp_seq begin, tcp_seq end, int32_t *num, uint32_t *sum) { notsack_blk_t *tmp; tmp = *head; /* If the list is empty, create a new one. */ if (tmp == NULL) { if ((tmp = (notsack_blk_t *)bkmem_alloc( sizeof (notsack_blk_t))) == NULL) { return; } tmp->begin = begin; tmp->end = end; tmp->next = NULL; tmp->sack_cnt = 0; *head = tmp; *num = 1; *sum = end - begin; return; } /* * Find the place to add the new blk. This assumes that new data * is being sent, so the place to insert the new notsack blk is at * the end of the list. */ while (tmp->next != NULL) { tmp = tmp->next; } /* Does the new blk overlap with old one? */ if (SEQ_GEQ(tmp->end, begin)) { *sum += end - tmp->end; tmp->end = end; } else { /* No. Need to create a new notsack blk. */ tmp->next = (notsack_blk_t *)bkmem_alloc( sizeof (notsack_blk_t)); if (tmp->next != NULL) { tmp = tmp->next; tmp->begin = begin; tmp->end = end; tmp->next = NULL; tmp->sack_cnt = 0; (*num)++; *sum += end - begin; } } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1997, 2002-2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _INET_SACK_H #define _INET_SACK_H #pragma ident "%Z%%M% %I% %E% SMI" #include /* for tcp_seq */ #ifdef __cplusplus extern "C" { #endif /* Maximum num of receiver's SACK blocks */ #define MAX_SACK_BLK 5 /* Receiver's SACK blk structure */ typedef struct sack_blk { tcp_seq begin; tcp_seq end; } sack_blk_t; /* Sender's notsack'ed blk structure */ typedef struct notsack_blk { struct notsack_blk *next; tcp_seq begin; tcp_seq end; uint32_t sack_cnt; /* Dup SACK count */ } notsack_blk_t; /* SACK information in the tcp_t structure. */ typedef struct { int32_t tcp_pipe; /* # of bytes in network */ tcp_seq tcp_fack; /* highest sack'ed seq num */ tcp_seq tcp_sack_snxt; /* next seq num to be rexmited using SACK. */ int32_t tcp_max_sack_blk; /* max # of SACK info blk in a segment */ int32_t tcp_num_sack_blk; /* num of blks in sack list */ sack_blk_t tcp_sack_list[MAX_SACK_BLK]; /* the sack list */ /* num of blks in notsack list */ int32_t tcp_num_notsack_blk; /* # of bytes represented in blks in notsack list */ uint32_t tcp_cnt_notsack_list; /* the notsack list */ notsack_blk_t *tcp_notsack_list; } tcp_sack_info_t; extern void tcp_sack_insert(sack_blk_t *, tcp_seq, tcp_seq, int32_t *); extern void tcp_sack_remove(sack_blk_t *, tcp_seq, int32_t *); extern void tcp_notsack_insert(notsack_blk_t **, tcp_seq, tcp_seq, int32_t *, uint32_t *); extern void tcp_notsack_remove(notsack_blk_t **, tcp_seq, int32_t *, uint32_t *); extern void tcp_notsack_update(notsack_blk_t **, tcp_seq, tcp_seq, int32_t *, uint32_t *); /* * Macro to remove all the notsack'ed blks in sender. * * Param: * notsack_blk_t *head: pointer to the head of the list of notsack'ed blks. */ #define TCP_NOTSACK_REMOVE_ALL(head) \ { \ notsack_blk_t *prev, *tmp; \ tmp = (head); \ do { \ prev = tmp; \ tmp = tmp->next; \ bkmem_free((caddr_t)prev, sizeof (notsack_blk_t)); \ } while (tmp != NULL); \ (head) = NULL; \ } #ifdef __cplusplus } #endif #endif /* _INET_SACK_H */ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # LIBRARY = libtcpstubs.a OBJECTS = tcpstubs.o include ../Makefile.com CPPFLAGS += -I../tcp $(SOCKCPPFLAGS) include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include /* ARGSUSED */ void tcp_socket_init(struct inetboot_socket *arg) { errno = EPROTOTYPE; } /* ARGSUSED */ int tcp_connect(int arg) { errno = EPROTOTYPE; return (-1); } /* ARGSUSED */ int tcp_listen(int arg0, int arg1) { errno = EOPNOTSUPP; return (-1); } /* ARGSUSED */ int tcp_bind(int arg0) { errno = EBADF; return (-1); } /* ARGSUSED */ int tcp_send(int arg0, tcp_t *arg1, const void *arg2, int arg3) { errno = EBADF; return (-1); } /* ARGSUSED */ int tcp_opt_set(tcp_t *arg0, int arg1, int arg2, const void *arg3, socklen_t arg4) { errno = ENOPROTOOPT; return (-1); } /* ARGSUSED */ int tcp_accept(int arg0, struct sockaddr *arg1, socklen_t *arg2) { errno = EBADF; return (-1); } /* ARGSUSED */ int tcp_shutdown(int arg) { errno = EBADF; return (-1); } /* ARGSUSED */ void tcp_rcv_drain_sock(int sock_id) { errno = EBADF; } # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2004 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # LIBRARY = libxdr.a CMNOBJS = xdr.o xdr_array.o xdr_mem.o xdr_refer.o LOCOBJS = byteorder.o OBJECTS = $(LOCOBJS) $(CMNOBJS) include ../Makefile.com CMNDIR = $(TOPDIR)/uts/common/rpc SRCS = $(LOCOBJS:%.o=$(SRCDIR)/%.c) $(CMNOBJS:%.o=$(CMNDIR)/%.c) include Makefile.$(MACH).targ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2003 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include /* * htonll(), ntohll(), htonl(), ntohl(), htons(), ntohs() * * On little endian machines these functions reverse the byte order of the * input parameter and returns the result. This is to convert the byte order * from host byte order (little endian) to network byte order (big endian), * or vice versa. * * On big endian machines these functions just return the input parameter, * as the host byte order is the same as the network byte order (big endian). */ #ifdef _LITTLE_ENDIAN uint64_t htonll(uint64_t in) { return ((uint64_t)htonl((in >> 32) & 0xffffffff) | ((uint64_t)htonl(in & 0xffffffff) << 32)); } uint64_t ntohll(uint64_t in) { return ((uint64_t)ntohl((in >> 32) & 0xffffffff) | ((uint64_t)ntohl(in & 0xffffffff) << 32)); } uint32_t htonl(uint32_t in) { uint32_t i; i = (uint32_t)((in & (uint32_t)0xff000000) >> 24) + (uint32_t)((in & (uint32_t)0x00ff0000) >> 8) + (uint32_t)((in & (uint32_t)0x0000ff00) << 8) + (uint32_t)((in & (uint32_t)0x000000ff) << 24); return (i); } uint32_t ntohl(uint32_t in) { return (htonl(in)); } uint16_t htons(uint16_t in) { register int arg = (int)in; uint16_t i; i = (uint16_t)(((arg & 0xff00) >> 8) & 0xff); i |= (uint16_t)((arg & 0xff) << 8); return ((uint16_t)i); } uint16_t ntohs(uint16_t in) { return (htons(in)); } #else /* _LITTLE_ENDIAN */ #if defined(lint) uint64_t htonll(uint64_t in) { return (in); } uint64_t ntohll(uint64_t in) { return (in); } uint32_t htonl(uint32_t in) { return (in); } uint32_t ntohl(uint32_t in) { return (in); } uint16_t htons(uint16_t in) { return (in); } uint16_t ntohs(uint16_t in) { return (in); } #endif /* lint */ #endif /* _LITTLE_ENDIAN */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 1995-1996, Sun Microsystems, Inc. All Rights Reserved. */ #ifndef _SYS_BOOTCMN_H #define _SYS_BOOTCMN_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif /* dummy device names for boot and floppy devices */ #define BOOT_DEV_NAME "" #define FLOPPY0_NAME "/dev/diskette0" #define FLOPPY1_NAME "/dev/diskette1" /* Maximum size (in characters) allotted to DOS volume labels */ #define VOLLABELSIZE 11 #ifdef __cplusplus } #endif #endif /* _SYS_BOOTCMN_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 1996, 2001, 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_BOOTDEBUG_H #define _SYS_BOOTDEBUG_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif /* * a collection of usefule debug defines and macros */ /* #define COMPFS_OPS_DEBUG */ /* #define PCFS_OPS_DEBUG */ /* #define HSFS_OPS_DEBUG */ /* #define UFS_OPS_DEBUG */ /* #define NFS_OPS_DEBUG */ /* #define CFS_OPS_DEBUG */ /* #define VERIFY_HASH_REALLOC */ #include extern int boothowto; /* What boot options are set */ extern int verbosemode; #define dprintf if (boothowto & RB_DEBUG) printf #define DBFLAGS (RB_DEBUG | RB_VERBOSE) /* * Debug Message Macros - will print message if CFS_OPS_DEBUG * is defined. */ #ifdef CFS_OPS_DEBUG #define OPS_DEBUG(args) { printf args; } #define OPS_DEBUG_CK(args)\ { if ((boothowto & DBFLAGS) == DBFLAGS) printf args; } #else /* CFS_OPS_DEBUG */ #define OPS_DEBUG(args) /* nothing */ #define OPS_DEBUG_CK(args) /* nothing */ #endif /* CFS_OPS_DEBUG */ #ifdef __cplusplus } #endif #endif /* _SYS_BOOTDEBUG_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_BOOTHSFS_H #define _SYS_BOOTHSFS_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include #include extern struct boot_fs_ops boot_hsfs_ops; #ifdef __cplusplus } #endif #endif /* _SYS_BOOTHSFS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_BOOTSYMS_H #define _SYS_BOOTSYMS_H /* * This header file should not exist. * * Whether it be due to laziness, machismo, or just plain cluelessness, most * of the symbols over in psm/stand are not properly prototyped anywhere. * * To workaround this, developers have adopted the horrendous practice of * "externing" the symbols they need, leading to dozens of declarations of * the same symbol which have to be kept in sync. Unfortunately, no similar * workaround exists for lint's pass2, which requires definitions for all * symbols in order to properly perform cross-checks. * * Thus, this header file was created to address the problems: * * - The "extern" problem. All files beneath stand/lib should #include * this file rather than "extern" the symbol. Additionally, existing * externs should be removed as convenient. * * Of course, eventually some brave soul needs to venture over to the * slums of psm/stand and add all the proper header files, at which * point this file can be disposed of. * * Note that the set of symbols shared between stand/lib and psm/stand is * itself a moving target. As such, this file should be updated as needed * so that it always contains the *minimum* set of shared symbols needed to * avoid externs and placate lint. */ #include #ifdef __cplusplus extern "C" { #endif /* * From psm/stand/boot/$(MACH)/common/fsconf.c: */ extern int nfs_readsize; extern int boot_nfsw; extern struct boot_fs_ops *boot_fsw[]; extern struct boot_fs_ops *extendfs_ops; extern struct boot_fs_ops *origfs_ops; /* * From psm/stand/boot/common/boot.c: */ extern int boothowto; extern int verbosemode; extern char *systype; extern struct memlist *pfreelistp; extern struct memlist *vfreelistp; extern void set_default_filename(char *); /* * From psm/stand/boot/common/heap_kmem.c: */ extern void *bkmem_alloc(size_t); extern void *bkmem_zalloc(size_t); extern void bkmem_free(void *, size_t); /* * From psm/stand/boot/$(MACH)/common/$(MACH)_standalloc.c: */ extern caddr_t resalloc(enum RESOURCES, size_t, caddr_t, int); extern void resfree(enum RESOURCES, caddr_t, size_t); extern void reset_alloc(void); /* * From psm/stand/lib/names/$(MACH)/common/mfgname.c: (libnames) */ extern char *get_mfg_name(void); /* * From psm/stand/boot/i386/common/boot_plat.c or * psm/stand/boot/sparcv9/sun4u/machdep.c: */ extern int pagesize; extern int global_pages; #ifdef __sparc /* * From psm/stand/boot/sparc/common/fsconf.c: */ extern char *bootp_response; #endif /* __sparc */ #ifdef __cplusplus } #endif #endif /* _SYS_BOOTSYMS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_BOOTUFS_H #define _SYS_BOOTUFS_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include #include extern struct boot_fs_ops boot_ufs_ops; #ifdef __cplusplus } #endif #endif /* _SYS_BOOTUFS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_BOOTVFS_H #define _SYS_BOOTVFS_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include #include #include /* same as those in /usr/include/unistd.h */ #define SEEK_SET 0 /* Offset */ #define SEEK_CUR 1 /* Current + Offset */ #define SEEK_END 2 /* EOF + Offset */ /* mountroot/unmountroot return values */ #define VFS_SUCCESS 0 #define VFS_FAILURE -1 /* * unified (vfs-like) file system operations for booters */ struct boot_fs_ops { char *fsw_name; int (*fsw_mountroot)(char *str); int (*fsw_unmountroot)(void); int (*fsw_open)(char *filename, int flags); int (*fsw_close)(int fd); ssize_t (*fsw_read)(int fd, caddr_t buf, size_t size); off_t (*fsw_lseek)(int filefd, off_t addr, int whence); int (*fsw_fstat)(int filefd, struct bootstat *buf); void (*fsw_closeall)(int flag); int (*fsw_getdents)(int fd, struct dirent *buf, unsigned size); }; /* * Function prototypes * * fstat() (if exists) supports size and mode right now. */ extern int mountroot(char *str); extern int unmountroot(void); extern int open(const char *filename, int flags); extern int close(int fd); extern ssize_t read(int fd, void *buf, size_t size); extern off_t lseek(int filefd, off_t addr, int whence); extern int fstat(int fd, struct stat *buf); extern int stat(const char *filename, struct stat *buf); /* * The compfs filesystem provides additional fsswitch-like entry points, * though these are not yet hooked properly into the fsswitch. */ extern void closeall(int flag); extern ssize_t kern_read(int fd, caddr_t buf, size_t size); extern int kern_open(char *filename, int flags); extern off_t kern_seek(int fd, off_t hi, off_t lo); extern off_t kern_lseek(int fd, off_t hi, off_t lo); extern int kern_close(int fd); extern int kern_fstat(int fd, struct bootstat *buf); extern int kern_getdents(int fd, struct dirent *buf, size_t size); extern int kern_mountroot(char *path); extern int kern_unmountroot(void); /* * these are for common fs switch interface routines */ extern int boot_no_ops(void); /* no ops entry */ extern void boot_no_ops_void(void); /* no ops entry */ extern struct boot_fs_ops *get_default_fs(void); extern struct boot_fs_ops *get_fs_ops_pointer(char *fsw_name); extern void set_default_fs(char *fsw_name); extern void clr_default_fs(void); extern char *set_fstype(char *v2path, char *bpath); #ifdef __cplusplus } #endif #endif /* _SYS_BOOTVFS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SA_CMN_ERR_H #define _SA_CMN_ERR_H #pragma ident "%Z%%M% %I% %E% SMI" /* * Exported interfaces for standalone's subset of kernel's . * Really all that is needed are the printf functions defined in stdio.h. */ #include #endif /* _SA_CMN_ERR_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_SACACHE_H #define _SYS_SACACHE_H #pragma ident "%Z%%M% %I% %E% SMI" #ifdef __cplusplus extern "C" { #endif #include #include /* * there are common cache interface routines */ extern void *get_icache(int dev, int inum); extern void set_icache(int dev, int inum, void *buf, int len); extern int set_ricache(int dev, int inum, void *buf, int len); extern int get_dcache(int dev, char *name, int pnum); extern void set_dcache(int dev, char *name, int pnum, int inum); extern int set_rdcache(int dev, char *name, int pnum, int inum); extern caddr_t get_bcache(fileid_t *fp); extern int set_bcache(fileid_t *fp); extern void release_cache(int dev); extern void print_cache_data(void); extern int read_opt; #ifdef __cplusplus } #endif #endif /* _SYS_SACACHE_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2005 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_SAIO_H #define _SYS_SAIO_H #pragma ident "%Z%%M% %I% %E% SMI" /* from SunOS 4.1 */ /* * NOTE: This header file is a vestige from a previous era. The RESOURCES * enum should be move somewhere more appropriate (with an accompanying * proper prototype for resalloc()) and this should be removed. */ #include #include #ifdef __cplusplus extern "C" { #endif /* * Types of resources that can be allocated by resalloc(). */ enum RESOURCES { RES_MAINMEM, /* Main memory, accessible to CPU */ RES_RAWVIRT, /* Raw addr space that can be mapped */ RES_DMAMEM, /* Memory acc. by CPU and by all DMA I/O */ RES_DMAVIRT, /* Raw addr space accessible by DMA I/O */ RES_PHYSICAL, /* Physical address */ RES_VIRTALLOC, /* Virtual addresses used */ RES_BOOTSCRATCH, /* Memory <4MB used only by boot. */ #ifdef __sparc RES_CHILDVIRT, /* Virt anywhere, phys > 4MB */ RES_BOOTSCRATCH_NOFAIL #else RES_CHILDVIRT /* Virt anywhere, phys > 4MB */ #endif }; #ifdef __cplusplus } #endif #endif /* _SYS_SAIO_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_SALIB_H #define _SYS_SALIB_H #pragma ident "%Z%%M% %I% %E% SMI" #include #include /* * This header file contains most of the libc-like interfaces exported by * standalone's "libsa" library, and a few other odds and ends (witness the * externs below). This file should *only* be included from code that is * built *exclusively* for use in the standalone environment. Even then, it's * perfectly acceptable to instead just use the traditional libc names for * #include files (as we do below), since all standalone code is built against * an alternate set of C headers (located under $SRC/stand/lib/sa). */ #include #include #include #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif extern void init_boot_time(void); extern void *bkmem_alloc(size_t); extern void *bkmem_zalloc(size_t); extern void bkmem_free(void *, size_t); /* memlist.c */ extern caddr_t tablep; extern void print_memlist(struct memlist *); extern void *getlink(uint_t); extern struct memlist *get_memlist_struct(void); extern void add_to_freelist(struct memlist *); /* standalloc.c */ extern caddr_t kern_resalloc(caddr_t, size_t, int); extern void kern_resfree(caddr_t, size_t); extern int get_progmemory(caddr_t, size_t, int); #ifdef __sparc /* prom_misc.c */ enum encode_how { ENCODE_BYTES, ENCODE_STRING }; extern void prom_create_encoded_prop(char *, void *, int, enum encode_how); #endif #ifdef __cplusplus } #endif #endif /* _SYS_SALIB_H */